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/cloud/clouds/digitalocean.py
|
show_pricing
|
python
|
def show_pricing(kwargs=None, call=None):
'''
Show pricing for a particular profile. This is only an estimate, based on
unofficial pricing sources.
.. versionadded:: 2015.8.0
CLI Examples:
.. code-block:: bash
salt-cloud -f show_pricing my-digitalocean-config profile=my-profile
'''
profile = __opts__['profiles'].get(kwargs['profile'], {})
if not profile:
return {'Error': 'The requested profile was not found'}
# Make sure the profile belongs to DigitalOcean
provider = profile.get('provider', '0:0')
comps = provider.split(':')
if len(comps) < 2 or comps[1] != 'digitalocean':
return {'Error': 'The requested profile does not belong to DigitalOcean'}
raw = {}
ret = {}
sizes = avail_sizes()
ret['per_hour'] = decimal.Decimal(sizes[profile['size']]['price_hourly'])
ret['per_day'] = ret['per_hour'] * 24
ret['per_week'] = ret['per_day'] * 7
ret['per_month'] = decimal.Decimal(sizes[profile['size']]['price_monthly'])
ret['per_year'] = ret['per_week'] * 52
if kwargs.get('raw', False):
ret['_raw'] = raw
return {profile['profile']: ret}
|
Show pricing for a particular profile. This is only an estimate, based on
unofficial pricing sources.
.. versionadded:: 2015.8.0
CLI Examples:
.. code-block:: bash
salt-cloud -f show_pricing my-digitalocean-config profile=my-profile
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/digitalocean.py#L939-L975
|
[
"def avail_sizes(call=None):\n '''\n Return a list of the image sizes that are on the provider\n '''\n if call == 'action':\n raise SaltCloudSystemExit(\n 'The avail_sizes function must be called with '\n '-f or --function, or with the --list-sizes option'\n )\n\n items = query(method='sizes', command='?per_page=100')\n ret = {}\n for size in items['sizes']:\n ret[size['slug']] = {}\n for item in six.iterkeys(size):\n ret[size['slug']][item] = six.text_type(size[item])\n\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
DigitalOcean Cloud Module
=========================
The DigitalOcean cloud module is used to control access to the DigitalOcean VPS system.
Use of this module requires a requires a ``personal_access_token``, an ``ssh_key_file``,
and at least one SSH key name in ``ssh_key_names``. More ``ssh_key_names`` can be added
by separating each key with a comma. The ``personal_access_token`` can be found in the
DigitalOcean web interface in the "Apps & API" section. The SSH key name can be found
under the "SSH Keys" section.
.. code-block:: yaml
# Note: This example is for /etc/salt/cloud.providers or any file in the
# /etc/salt/cloud.providers.d/ directory.
my-digital-ocean-config:
personal_access_token: xxx
ssh_key_file: /path/to/ssh/key/file
ssh_key_names: my-key-name,my-key-name-2
driver: digitalocean
:depends: requests
'''
# Import Python Libs
from __future__ import absolute_import, print_function, unicode_literals
import decimal
import logging
import os
import pprint
import time
# Import Salt Libs
import salt.utils.cloud
import salt.utils.files
import salt.utils.json
import salt.utils.stringutils
import salt.config as config
from salt.exceptions import (
SaltCloudConfigError,
SaltInvocationError,
SaltCloudNotFound,
SaltCloudSystemExit,
SaltCloudExecutionFailure,
SaltCloudExecutionTimeout
)
from salt.ext import six
from salt.ext.six.moves import zip
# Import Third Party Libs
try:
import requests
HAS_REQUESTS = True
except ImportError:
HAS_REQUESTS = False
# Get logging started
log = logging.getLogger(__name__)
__virtualname__ = 'digitalocean'
__virtual_aliases__ = ('digital_ocean', 'do')
# Only load in this module if the DIGITALOCEAN configurations are in place
def __virtual__():
'''
Check for DigitalOcean configurations
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
opts=__opts__,
provider=__active_provider_name__ or __virtualname__,
aliases=__virtual_aliases__,
required_keys=('personal_access_token',)
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'requests': HAS_REQUESTS}
)
def avail_locations(call=None):
'''
Return a dict of all available VM locations on the cloud provider with
relevant data
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
items = query(method='regions')
ret = {}
for region in items['regions']:
ret[region['name']] = {}
for item in six.iterkeys(region):
ret[region['name']][item] = six.text_type(region[item])
return ret
def avail_images(call=None):
'''
Return a list of the images that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
fetch = True
page = 1
ret = {}
while fetch:
items = query(method='images', command='?page=' + six.text_type(page) + '&per_page=200')
for image in items['images']:
ret[image['name']] = {}
for item in six.iterkeys(image):
ret[image['name']][item] = image[item]
page += 1
try:
fetch = 'next' in items['links']['pages']
except KeyError:
fetch = False
return ret
def avail_sizes(call=None):
'''
Return a list of the image sizes that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
items = query(method='sizes', command='?per_page=100')
ret = {}
for size in items['sizes']:
ret[size['slug']] = {}
for item in six.iterkeys(size):
ret[size['slug']][item] = six.text_type(size[item])
return ret
def list_nodes(call=None):
'''
Return a list of the VMs that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
return _list_nodes()
def list_nodes_full(call=None, for_output=True):
'''
Return a list of the VMs that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or --function.'
)
return _list_nodes(full=True, for_output=for_output)
def list_nodes_select(call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
return salt.utils.cloud.list_nodes_select(
list_nodes_full('function'), __opts__['query.selection'], call,
)
def get_image(vm_):
'''
Return the image object to use
'''
images = avail_images()
vm_image = config.get_cloud_config_value(
'image', vm_, __opts__, search_global=False
)
if not isinstance(vm_image, six.string_types):
vm_image = six.text_type(vm_image)
for image in images:
if vm_image in (images[image]['name'],
images[image]['slug'],
images[image]['id']):
if images[image]['slug'] is not None:
return images[image]['slug']
return int(images[image]['id'])
raise SaltCloudNotFound(
'The specified image, \'{0}\', could not be found.'.format(vm_image)
)
def get_size(vm_):
'''
Return the VM's size. Used by create_node().
'''
sizes = avail_sizes()
vm_size = six.text_type(config.get_cloud_config_value(
'size', vm_, __opts__, search_global=False
))
for size in sizes:
if vm_size.lower() == sizes[size]['slug']:
return sizes[size]['slug']
raise SaltCloudNotFound(
'The specified size, \'{0}\', could not be found.'.format(vm_size)
)
def get_location(vm_):
'''
Return the VM's location
'''
locations = avail_locations()
vm_location = six.text_type(config.get_cloud_config_value(
'location', vm_, __opts__, search_global=False
))
for location in locations:
if vm_location in (locations[location]['name'],
locations[location]['slug']):
return locations[location]['slug']
raise SaltCloudNotFound(
'The specified location, \'{0}\', could not be found.'.format(
vm_location
)
)
def create_node(args):
'''
Create a node
'''
node = query(method='droplets', args=args, http_method='post')
return node
def create(vm_):
'''
Create a single VM from a data dict
'''
try:
# Check for required profile parameters before sending any API calls.
if vm_['profile'] and config.is_profile_configured(__opts__,
__active_provider_name__ or 'digitalocean',
vm_['profile'],
vm_=vm_) is False:
return False
except AttributeError:
pass
__utils__['cloud.fire_event'](
'event',
'starting create',
'salt/cloud/{0}/creating'.format(vm_['name']),
args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Creating Cloud VM %s', vm_['name'])
kwargs = {
'name': vm_['name'],
'size': get_size(vm_),
'image': get_image(vm_),
'region': get_location(vm_),
'ssh_keys': [],
'tags': []
}
# backwards compat
ssh_key_name = config.get_cloud_config_value(
'ssh_key_name', vm_, __opts__, search_global=False
)
if ssh_key_name:
kwargs['ssh_keys'].append(get_keyid(ssh_key_name))
ssh_key_names = config.get_cloud_config_value(
'ssh_key_names', vm_, __opts__, search_global=False, default=False
)
if ssh_key_names:
for key in ssh_key_names.split(','):
kwargs['ssh_keys'].append(get_keyid(key))
key_filename = config.get_cloud_config_value(
'ssh_key_file', vm_, __opts__, search_global=False, default=None
)
if key_filename is not None and not os.path.isfile(key_filename):
raise SaltCloudConfigError(
'The defined key_filename \'{0}\' does not exist'.format(
key_filename
)
)
if not __opts__.get('ssh_agent', False) and key_filename is None:
raise SaltCloudConfigError(
'The DigitalOcean driver requires an ssh_key_file and an ssh_key_name '
'because it does not supply a root password upon building the server.'
)
ssh_interface = config.get_cloud_config_value(
'ssh_interface', vm_, __opts__, search_global=False, default='public'
)
if ssh_interface in ['private', 'public']:
log.info("ssh_interface: Setting interface for ssh to %s", ssh_interface)
kwargs['ssh_interface'] = ssh_interface
else:
raise SaltCloudConfigError(
"The DigitalOcean driver requires ssh_interface to be defined as 'public' or 'private'."
)
private_networking = config.get_cloud_config_value(
'private_networking', vm_, __opts__, search_global=False, default=None,
)
if private_networking is not None:
if not isinstance(private_networking, bool):
raise SaltCloudConfigError("'private_networking' should be a boolean value.")
kwargs['private_networking'] = private_networking
if not private_networking and ssh_interface == 'private':
raise SaltCloudConfigError(
"The DigitalOcean driver requires ssh_interface if defined as 'private' "
"then private_networking should be set as 'True'."
)
backups_enabled = config.get_cloud_config_value(
'backups_enabled', vm_, __opts__, search_global=False, default=None,
)
if backups_enabled is not None:
if not isinstance(backups_enabled, bool):
raise SaltCloudConfigError("'backups_enabled' should be a boolean value.")
kwargs['backups'] = backups_enabled
ipv6 = config.get_cloud_config_value(
'ipv6', vm_, __opts__, search_global=False, default=None,
)
if ipv6 is not None:
if not isinstance(ipv6, bool):
raise SaltCloudConfigError("'ipv6' should be a boolean value.")
kwargs['ipv6'] = ipv6
monitoring = config.get_cloud_config_value(
'monitoring', vm_, __opts__, search_global=False, default=None,
)
if monitoring is not None:
if not isinstance(monitoring, bool):
raise SaltCloudConfigError("'monitoring' should be a boolean value.")
kwargs['monitoring'] = monitoring
kwargs['tags'] = config.get_cloud_config_value(
'tags', vm_, __opts__, search_global=False, default=False
)
userdata_file = config.get_cloud_config_value(
'userdata_file', vm_, __opts__, search_global=False, default=None
)
if userdata_file is not None:
try:
with salt.utils.files.fopen(userdata_file, 'r') as fp_:
kwargs['user_data'] = salt.utils.cloud.userdata_template(
__opts__, vm_, salt.utils.stringutils.to_unicode(fp_.read())
)
except Exception as exc:
log.exception(
'Failed to read userdata from %s: %s', userdata_file, exc)
create_dns_record = config.get_cloud_config_value(
'create_dns_record', vm_, __opts__, search_global=False, default=None,
)
if create_dns_record:
log.info('create_dns_record: will attempt to write DNS records')
default_dns_domain = None
dns_domain_name = vm_['name'].split('.')
if len(dns_domain_name) > 2:
log.debug('create_dns_record: inferring default dns_hostname, dns_domain from minion name as FQDN')
default_dns_hostname = '.'.join(dns_domain_name[:-2])
default_dns_domain = '.'.join(dns_domain_name[-2:])
else:
log.debug("create_dns_record: can't infer dns_domain from %s", vm_['name'])
default_dns_hostname = dns_domain_name[0]
dns_hostname = config.get_cloud_config_value(
'dns_hostname', vm_, __opts__, search_global=False, default=default_dns_hostname,
)
dns_domain = config.get_cloud_config_value(
'dns_domain', vm_, __opts__, search_global=False, default=default_dns_domain,
)
if dns_hostname and dns_domain:
log.info('create_dns_record: using dns_hostname="%s", dns_domain="%s"', dns_hostname, dns_domain)
__add_dns_addr__ = lambda t, d: post_dns_record(dns_domain=dns_domain,
name=dns_hostname,
record_type=t,
record_data=d)
log.debug('create_dns_record: %s', __add_dns_addr__)
else:
log.error('create_dns_record: could not determine dns_hostname and/or dns_domain')
raise SaltCloudConfigError(
'\'create_dns_record\' must be a dict specifying "domain" '
'and "hostname" or the minion name must be an FQDN.'
)
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args=__utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
try:
ret = create_node(kwargs)
except Exception as exc:
log.error(
'Error creating %s on DIGITALOCEAN\n\n'
'The following exception was thrown when trying to '
'run the initial deployment: %s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
def __query_node_data(vm_name):
data = show_instance(vm_name, 'action')
if not data:
# Trigger an error in the wait_for_ip function
return False
if data['networks'].get('v4'):
for network in data['networks']['v4']:
if network['type'] == 'public':
return data
return False
try:
data = salt.utils.cloud.wait_for_ip(
__query_node_data,
update_args=(vm_['name'],),
timeout=config.get_cloud_config_value(
'wait_for_ip_timeout', vm_, __opts__, default=10 * 60),
interval=config.get_cloud_config_value(
'wait_for_ip_interval', vm_, __opts__, default=10),
)
except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc:
try:
# It might be already up, let's destroy it!
destroy(vm_['name'])
except SaltCloudSystemExit:
pass
finally:
raise SaltCloudSystemExit(six.text_type(exc))
if not vm_.get('ssh_host'):
vm_['ssh_host'] = None
# add DNS records, set ssh_host, default to first found IP, preferring IPv4 for ssh bootstrap script target
addr_families, dns_arec_types = (('v4', 'v6'), ('A', 'AAAA'))
arec_map = dict(list(zip(addr_families, dns_arec_types)))
for facing, addr_family, ip_address in [(net['type'], family, net['ip_address'])
for family in addr_families
for net in data['networks'][family]]:
log.info('found %s IP%s interface for "%s"', facing, addr_family, ip_address)
dns_rec_type = arec_map[addr_family]
if facing == 'public':
if create_dns_record:
__add_dns_addr__(dns_rec_type, ip_address)
if facing == ssh_interface:
if not vm_['ssh_host']:
vm_['ssh_host'] = ip_address
if vm_['ssh_host'] is None:
raise SaltCloudSystemExit(
'No suitable IP addresses found for ssh minion bootstrapping: {0}'.format(repr(data['networks']))
)
log.debug(
'Found public IP address to use for ssh minion bootstrapping: %s',
vm_['ssh_host']
)
vm_['key_filename'] = key_filename
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
ret.update(data)
log.info('Created Cloud VM \'%s\'', vm_['name'])
log.debug(
'\'%s\' VM creation details:\n%s',
vm_['name'], pprint.pformat(data)
)
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return ret
def query(method='droplets', droplet_id=None, command=None, args=None, http_method='get'):
'''
Make a web call to DigitalOcean
'''
base_path = six.text_type(config.get_cloud_config_value(
'api_root',
get_configured_provider(),
__opts__,
search_global=False,
default='https://api.digitalocean.com/v2'
))
path = '{0}/{1}/'.format(base_path, method)
if droplet_id:
path += '{0}/'.format(droplet_id)
if command:
path += command
if not isinstance(args, dict):
args = {}
personal_access_token = config.get_cloud_config_value(
'personal_access_token', get_configured_provider(), __opts__, search_global=False
)
data = salt.utils.json.dumps(args)
requester = getattr(requests, http_method)
request = requester(path, data=data, headers={'Authorization': 'Bearer ' + personal_access_token, 'Content-Type': 'application/json'})
if request.status_code > 299:
raise SaltCloudSystemExit(
'An error occurred while querying DigitalOcean. HTTP Code: {0} '
'Error: \'{1}\''.format(
request.status_code,
# request.read()
request.text
)
)
log.debug(request.url)
# success without data
if request.status_code == 204:
return True
content = request.text
result = salt.utils.json.loads(content)
if result.get('status', '').lower() == 'error':
raise SaltCloudSystemExit(
pprint.pformat(result.get('error_message', {}))
)
return result
def script(vm_):
'''
Return the script deployment object
'''
deploy_script = salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
return deploy_script
def show_instance(name, call=None):
'''
Show the details from DigitalOcean concerning a droplet
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
node = _get_node(name)
__utils__['cloud.cache_node'](node, __active_provider_name__, __opts__)
return node
def _get_node(name):
attempts = 10
while attempts >= 0:
try:
return list_nodes_full(for_output=False)[name]
except KeyError:
attempts -= 1
log.debug(
'Failed to get the data for node \'%s\'. Remaining '
'attempts: %s', name, attempts
)
# Just a little delay between attempts...
time.sleep(0.5)
return {}
def list_keypairs(call=None):
'''
Return a dict of all available VM locations on the cloud provider with
relevant data
'''
if call != 'function':
log.error(
'The list_keypairs function must be called with -f or --function.'
)
return False
fetch = True
page = 1
ret = {}
while fetch:
items = query(method='account/keys', command='?page=' + six.text_type(page) +
'&per_page=100')
for key_pair in items['ssh_keys']:
name = key_pair['name']
if name in ret:
raise SaltCloudSystemExit(
'A duplicate key pair name, \'{0}\', was found in DigitalOcean\'s '
'key pair list. Please change the key name stored by DigitalOcean. '
'Be sure to adjust the value of \'ssh_key_file\' in your cloud '
'profile or provider configuration, if necessary.'.format(
name
)
)
ret[name] = {}
for item in six.iterkeys(key_pair):
ret[name][item] = six.text_type(key_pair[item])
page += 1
try:
fetch = 'next' in items['links']['pages']
except KeyError:
fetch = False
return ret
def show_keypair(kwargs=None, call=None):
'''
Show the details of an SSH keypair
'''
if call != 'function':
log.error(
'The show_keypair function must be called with -f or --function.'
)
return False
if not kwargs:
kwargs = {}
if 'keyname' not in kwargs:
log.error('A keyname is required.')
return False
keypairs = list_keypairs(call='function')
keyid = keypairs[kwargs['keyname']]['id']
log.debug('Key ID is %s', keyid)
details = query(method='account/keys', command=keyid)
return details
def import_keypair(kwargs=None, call=None):
'''
Upload public key to cloud provider.
Similar to EC2 import_keypair.
.. versionadded:: 2016.11.0
kwargs
file(mandatory): public key file-name
keyname(mandatory): public key name in the provider
'''
with salt.utils.files.fopen(kwargs['file'], 'r') as public_key_filename:
public_key_content = salt.utils.stringutils.to_unicode(public_key_filename.read())
digitalocean_kwargs = {
'name': kwargs['keyname'],
'public_key': public_key_content
}
created_result = create_key(digitalocean_kwargs, call=call)
return created_result
def create_key(kwargs=None, call=None):
'''
Upload a public key
'''
if call != 'function':
log.error(
'The create_key function must be called with -f or --function.'
)
return False
try:
result = query(
method='account',
command='keys',
args={'name': kwargs['name'],
'public_key': kwargs['public_key']},
http_method='post'
)
except KeyError:
log.info('`name` and `public_key` arguments must be specified')
return False
return result
def remove_key(kwargs=None, call=None):
'''
Delete public key
'''
if call != 'function':
log.error(
'The create_key function must be called with -f or --function.'
)
return False
try:
result = query(
method='account',
command='keys/' + kwargs['id'],
http_method='delete'
)
except KeyError:
log.info('`id` argument must be specified')
return False
return result
def get_keyid(keyname):
'''
Return the ID of the keyname
'''
if not keyname:
return None
keypairs = list_keypairs(call='function')
keyid = keypairs[keyname]['id']
if keyid:
return keyid
raise SaltCloudNotFound('The specified ssh key could not be found.')
def destroy(name, call=None):
'''
Destroy a node. Will check termination protection and warn if enabled.
CLI Example:
.. code-block:: bash
salt-cloud --destroy mymachine
'''
if call == 'function':
raise SaltCloudSystemExit(
'The destroy action must be called with -d, --destroy, '
'-a or --action.'
)
__utils__['cloud.fire_event'](
'event',
'destroying instance',
'salt/cloud/{0}/destroying'.format(name),
args={'name': name},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
data = show_instance(name, call='action')
node = query(method='droplets', droplet_id=data['id'], http_method='delete')
## This is all terribly optomistic:
# vm_ = get_vm_config(name=name)
# delete_dns_record = config.get_cloud_config_value(
# 'delete_dns_record', vm_, __opts__, search_global=False, default=None,
# )
# TODO: when _vm config data can be made available, we should honor the configuration settings,
# but until then, we should assume stale DNS records are bad, and default behavior should be to
# delete them if we can. When this is resolved, also resolve the comments a couple of lines below.
delete_dns_record = True
if not isinstance(delete_dns_record, bool):
raise SaltCloudConfigError(
'\'delete_dns_record\' should be a boolean value.'
)
# When the "to do" a few lines up is resolved, remove these lines and use the if/else logic below.
log.debug('Deleting DNS records for %s.', name)
destroy_dns_records(name)
# Until the "to do" from line 754 is taken care of, we don't need this logic.
# if delete_dns_record:
# log.debug('Deleting DNS records for %s.', name)
# destroy_dns_records(name)
# else:
# log.debug('delete_dns_record : %s', delete_dns_record)
# for line in pprint.pformat(dir()).splitlines():
# log.debug('delete context: %s', line)
__utils__['cloud.fire_event'](
'event',
'destroyed instance',
'salt/cloud/{0}/destroyed'.format(name),
args={'name': name},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
if __opts__.get('update_cachedir', False) is True:
__utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__)
return node
def post_dns_record(**kwargs):
'''
Creates a DNS record for the given name if the domain is managed with DO.
'''
if 'kwargs' in kwargs: # flatten kwargs if called via salt-cloud -f
f_kwargs = kwargs['kwargs']
del kwargs['kwargs']
kwargs.update(f_kwargs)
mandatory_kwargs = ('dns_domain', 'name', 'record_type', 'record_data')
for i in mandatory_kwargs:
if kwargs[i]:
pass
else:
error = '{0}="{1}" ## all mandatory args must be provided: {2}'.format(i, kwargs[i], mandatory_kwargs)
raise SaltInvocationError(error)
domain = query(method='domains', droplet_id=kwargs['dns_domain'])
if domain:
result = query(
method='domains',
droplet_id=kwargs['dns_domain'],
command='records',
args={'type': kwargs['record_type'], 'name': kwargs['name'], 'data': kwargs['record_data']},
http_method='post'
)
return result
return False
def destroy_dns_records(fqdn):
'''
Deletes DNS records for the given hostname if the domain is managed with DO.
'''
domain = '.'.join(fqdn.split('.')[-2:])
hostname = '.'.join(fqdn.split('.')[:-2])
# TODO: remove this when the todo on 754 is available
try:
response = query(method='domains', droplet_id=domain, command='records')
except SaltCloudSystemExit:
log.debug('Failed to find domains.')
return False
log.debug("found DNS records: %s", pprint.pformat(response))
records = response['domain_records']
if records:
record_ids = [r['id'] for r in records if r['name'].decode() == hostname]
log.debug("deleting DNS record IDs: %s", record_ids)
for id_ in record_ids:
try:
log.info('deleting DNS record %s', id_)
ret = query(
method='domains',
droplet_id=domain,
command='records/{0}'.format(id_),
http_method='delete'
)
except SaltCloudSystemExit:
log.error('failed to delete DNS domain %s record ID %s.', domain, hostname)
log.debug('DNS deletion REST call returned: %s', pprint.pformat(ret))
return False
def list_floating_ips(call=None):
'''
Return a list of the floating ips that are on the provider
.. versionadded:: 2016.3.0
CLI Examples:
.. code-block:: bash
salt-cloud -f list_floating_ips my-digitalocean-config
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_floating_ips function must be called with '
'-f or --function, or with the --list-floating-ips option'
)
fetch = True
page = 1
ret = {}
while fetch:
items = query(method='floating_ips',
command='?page=' + six.text_type(page) + '&per_page=200')
for floating_ip in items['floating_ips']:
ret[floating_ip['ip']] = {}
for item in six.iterkeys(floating_ip):
ret[floating_ip['ip']][item] = floating_ip[item]
page += 1
try:
fetch = 'next' in items['links']['pages']
except KeyError:
fetch = False
return ret
def show_floating_ip(kwargs=None, call=None):
'''
Show the details of a floating IP
.. versionadded:: 2016.3.0
CLI Examples:
.. code-block:: bash
salt-cloud -f show_floating_ip my-digitalocean-config floating_ip='45.55.96.47'
'''
if call != 'function':
log.error(
'The show_floating_ip function must be called with -f or --function.'
)
return False
if not kwargs:
kwargs = {}
if 'floating_ip' not in kwargs:
log.error('A floating IP is required.')
return False
floating_ip = kwargs['floating_ip']
log.debug('Floating ip is %s', floating_ip)
details = query(method='floating_ips', command=floating_ip)
return details
def create_floating_ip(kwargs=None, call=None):
'''
Create a new floating IP
.. versionadded:: 2016.3.0
CLI Examples:
.. code-block:: bash
salt-cloud -f create_floating_ip my-digitalocean-config region='NYC2'
salt-cloud -f create_floating_ip my-digitalocean-config droplet_id='1234567'
'''
if call != 'function':
log.error(
'The create_floating_ip function must be called with -f or --function.'
)
return False
if not kwargs:
kwargs = {}
if 'droplet_id' in kwargs:
result = query(method='floating_ips',
args={'droplet_id': kwargs['droplet_id']},
http_method='post')
return result
elif 'region' in kwargs:
result = query(method='floating_ips',
args={'region': kwargs['region']},
http_method='post')
return result
else:
log.error('A droplet_id or region is required.')
return False
def delete_floating_ip(kwargs=None, call=None):
'''
Delete a floating IP
.. versionadded:: 2016.3.0
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_floating_ip my-digitalocean-config floating_ip='45.55.96.47'
'''
if call != 'function':
log.error(
'The delete_floating_ip function must be called with -f or --function.'
)
return False
if not kwargs:
kwargs = {}
if 'floating_ip' not in kwargs:
log.error('A floating IP is required.')
return False
floating_ip = kwargs['floating_ip']
log.debug('Floating ip is %s', kwargs['floating_ip'])
result = query(method='floating_ips',
command=floating_ip,
http_method='delete')
return result
def assign_floating_ip(kwargs=None, call=None):
'''
Assign a floating IP
.. versionadded:: 2016.3.0
CLI Examples:
.. code-block:: bash
salt-cloud -f assign_floating_ip my-digitalocean-config droplet_id=1234567 floating_ip='45.55.96.47'
'''
if call != 'function':
log.error(
'The assign_floating_ip function must be called with -f or --function.'
)
return False
if not kwargs:
kwargs = {}
if 'floating_ip' and 'droplet_id' not in kwargs:
log.error('A floating IP and droplet_id is required.')
return False
result = query(method='floating_ips',
command=kwargs['floating_ip'] + '/actions',
args={'droplet_id': kwargs['droplet_id'], 'type': 'assign'},
http_method='post')
return result
def unassign_floating_ip(kwargs=None, call=None):
'''
Unassign a floating IP
.. versionadded:: 2016.3.0
CLI Examples:
.. code-block:: bash
salt-cloud -f unassign_floating_ip my-digitalocean-config floating_ip='45.55.96.47'
'''
if call != 'function':
log.error(
'The inassign_floating_ip function must be called with -f or --function.'
)
return False
if not kwargs:
kwargs = {}
if 'floating_ip' not in kwargs:
log.error('A floating IP is required.')
return False
result = query(method='floating_ips',
command=kwargs['floating_ip'] + '/actions',
args={'type': 'unassign'},
http_method='post')
return result
def _list_nodes(full=False, for_output=False):
'''
Helper function to format and parse node data.
'''
fetch = True
page = 1
ret = {}
while fetch:
items = query(method='droplets',
command='?page=' + six.text_type(page) + '&per_page=200')
for node in items['droplets']:
name = node['name']
ret[name] = {}
if full:
ret[name] = _get_full_output(node, for_output=for_output)
else:
public_ips, private_ips = _get_ips(node['networks'])
ret[name] = {
'id': node['id'],
'image': node['image']['name'],
'name': name,
'private_ips': private_ips,
'public_ips': public_ips,
'size': node['size_slug'],
'state': six.text_type(node['status']),
}
page += 1
try:
fetch = 'next' in items['links']['pages']
except KeyError:
fetch = False
return ret
def reboot(name, call=None):
'''
Reboot a droplet in DigitalOcean.
.. versionadded:: 2015.8.8
name
The name of the droplet to restart.
CLI Example:
.. code-block:: bash
salt-cloud -a reboot droplet_name
'''
if call != 'action':
raise SaltCloudSystemExit(
'The restart action must be called with -a or --action.'
)
data = show_instance(name, call='action')
if data.get('status') == 'off':
return {'success': True,
'action': 'stop',
'status': 'off',
'msg': 'Machine is already off.'}
ret = query(droplet_id=data['id'],
command='actions',
args={'type': 'reboot'},
http_method='post')
return {'success': True,
'action': ret['action']['type'],
'state': ret['action']['status']}
def start(name, call=None):
'''
Start a droplet in DigitalOcean.
.. versionadded:: 2015.8.8
name
The name of the droplet to start.
CLI Example:
.. code-block:: bash
salt-cloud -a start droplet_name
'''
if call != 'action':
raise SaltCloudSystemExit(
'The start action must be called with -a or --action.'
)
data = show_instance(name, call='action')
if data.get('status') == 'active':
return {'success': True,
'action': 'start',
'status': 'active',
'msg': 'Machine is already running.'}
ret = query(droplet_id=data['id'],
command='actions',
args={'type': 'power_on'},
http_method='post')
return {'success': True,
'action': ret['action']['type'],
'state': ret['action']['status']}
def stop(name, call=None):
'''
Stop a droplet in DigitalOcean.
.. versionadded:: 2015.8.8
name
The name of the droplet to stop.
CLI Example:
.. code-block:: bash
salt-cloud -a stop droplet_name
'''
if call != 'action':
raise SaltCloudSystemExit(
'The stop action must be called with -a or --action.'
)
data = show_instance(name, call='action')
if data.get('status') == 'off':
return {'success': True,
'action': 'stop',
'status': 'off',
'msg': 'Machine is already off.'}
ret = query(droplet_id=data['id'],
command='actions',
args={'type': 'shutdown'},
http_method='post')
return {'success': True,
'action': ret['action']['type'],
'state': ret['action']['status']}
def _get_full_output(node, for_output=False):
'''
Helper function for _list_nodes to loop through all node information.
Returns a dictionary containing the full information of a node.
'''
ret = {}
for item in six.iterkeys(node):
value = node[item]
if value is not None and for_output:
value = six.text_type(value)
ret[item] = value
return ret
def _get_ips(networks):
'''
Helper function for list_nodes. Returns public and private ip lists based on a
given network dictionary.
'''
v4s = networks.get('v4')
v6s = networks.get('v6')
public_ips = []
private_ips = []
if v4s:
for item in v4s:
ip_type = item.get('type')
ip_address = item.get('ip_address')
if ip_type == 'public':
public_ips.append(ip_address)
if ip_type == 'private':
private_ips.append(ip_address)
if v6s:
for item in v6s:
ip_type = item.get('type')
ip_address = item.get('ip_address')
if ip_type == 'public':
public_ips.append(ip_address)
if ip_type == 'private':
private_ips.append(ip_address)
return public_ips, private_ips
|
saltstack/salt
|
salt/cloud/clouds/digitalocean.py
|
show_floating_ip
|
python
|
def show_floating_ip(kwargs=None, call=None):
'''
Show the details of a floating IP
.. versionadded:: 2016.3.0
CLI Examples:
.. code-block:: bash
salt-cloud -f show_floating_ip my-digitalocean-config floating_ip='45.55.96.47'
'''
if call != 'function':
log.error(
'The show_floating_ip function must be called with -f or --function.'
)
return False
if not kwargs:
kwargs = {}
if 'floating_ip' not in kwargs:
log.error('A floating IP is required.')
return False
floating_ip = kwargs['floating_ip']
log.debug('Floating ip is %s', floating_ip)
details = query(method='floating_ips', command=floating_ip)
return details
|
Show the details of a floating IP
.. versionadded:: 2016.3.0
CLI Examples:
.. code-block:: bash
salt-cloud -f show_floating_ip my-digitalocean-config floating_ip='45.55.96.47'
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/digitalocean.py#L1018-L1048
|
[
"def query(method='droplets', droplet_id=None, command=None, args=None, http_method='get'):\n '''\n Make a web call to DigitalOcean\n '''\n base_path = six.text_type(config.get_cloud_config_value(\n 'api_root',\n get_configured_provider(),\n __opts__,\n search_global=False,\n default='https://api.digitalocean.com/v2'\n ))\n\n path = '{0}/{1}/'.format(base_path, method)\n\n if droplet_id:\n path += '{0}/'.format(droplet_id)\n\n if command:\n path += command\n\n if not isinstance(args, dict):\n args = {}\n\n personal_access_token = config.get_cloud_config_value(\n 'personal_access_token', get_configured_provider(), __opts__, search_global=False\n )\n\n data = salt.utils.json.dumps(args)\n\n requester = getattr(requests, http_method)\n request = requester(path, data=data, headers={'Authorization': 'Bearer ' + personal_access_token, 'Content-Type': 'application/json'})\n if request.status_code > 299:\n raise SaltCloudSystemExit(\n 'An error occurred while querying DigitalOcean. HTTP Code: {0} '\n 'Error: \\'{1}\\''.format(\n request.status_code,\n # request.read()\n request.text\n )\n )\n\n log.debug(request.url)\n\n # success without data\n if request.status_code == 204:\n return True\n\n content = request.text\n\n result = salt.utils.json.loads(content)\n if result.get('status', '').lower() == 'error':\n raise SaltCloudSystemExit(\n pprint.pformat(result.get('error_message', {}))\n )\n\n return result\n"
] |
# -*- coding: utf-8 -*-
'''
DigitalOcean Cloud Module
=========================
The DigitalOcean cloud module is used to control access to the DigitalOcean VPS system.
Use of this module requires a requires a ``personal_access_token``, an ``ssh_key_file``,
and at least one SSH key name in ``ssh_key_names``. More ``ssh_key_names`` can be added
by separating each key with a comma. The ``personal_access_token`` can be found in the
DigitalOcean web interface in the "Apps & API" section. The SSH key name can be found
under the "SSH Keys" section.
.. code-block:: yaml
# Note: This example is for /etc/salt/cloud.providers or any file in the
# /etc/salt/cloud.providers.d/ directory.
my-digital-ocean-config:
personal_access_token: xxx
ssh_key_file: /path/to/ssh/key/file
ssh_key_names: my-key-name,my-key-name-2
driver: digitalocean
:depends: requests
'''
# Import Python Libs
from __future__ import absolute_import, print_function, unicode_literals
import decimal
import logging
import os
import pprint
import time
# Import Salt Libs
import salt.utils.cloud
import salt.utils.files
import salt.utils.json
import salt.utils.stringutils
import salt.config as config
from salt.exceptions import (
SaltCloudConfigError,
SaltInvocationError,
SaltCloudNotFound,
SaltCloudSystemExit,
SaltCloudExecutionFailure,
SaltCloudExecutionTimeout
)
from salt.ext import six
from salt.ext.six.moves import zip
# Import Third Party Libs
try:
import requests
HAS_REQUESTS = True
except ImportError:
HAS_REQUESTS = False
# Get logging started
log = logging.getLogger(__name__)
__virtualname__ = 'digitalocean'
__virtual_aliases__ = ('digital_ocean', 'do')
# Only load in this module if the DIGITALOCEAN configurations are in place
def __virtual__():
'''
Check for DigitalOcean configurations
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
opts=__opts__,
provider=__active_provider_name__ or __virtualname__,
aliases=__virtual_aliases__,
required_keys=('personal_access_token',)
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'requests': HAS_REQUESTS}
)
def avail_locations(call=None):
'''
Return a dict of all available VM locations on the cloud provider with
relevant data
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
items = query(method='regions')
ret = {}
for region in items['regions']:
ret[region['name']] = {}
for item in six.iterkeys(region):
ret[region['name']][item] = six.text_type(region[item])
return ret
def avail_images(call=None):
'''
Return a list of the images that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
fetch = True
page = 1
ret = {}
while fetch:
items = query(method='images', command='?page=' + six.text_type(page) + '&per_page=200')
for image in items['images']:
ret[image['name']] = {}
for item in six.iterkeys(image):
ret[image['name']][item] = image[item]
page += 1
try:
fetch = 'next' in items['links']['pages']
except KeyError:
fetch = False
return ret
def avail_sizes(call=None):
'''
Return a list of the image sizes that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
items = query(method='sizes', command='?per_page=100')
ret = {}
for size in items['sizes']:
ret[size['slug']] = {}
for item in six.iterkeys(size):
ret[size['slug']][item] = six.text_type(size[item])
return ret
def list_nodes(call=None):
'''
Return a list of the VMs that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
return _list_nodes()
def list_nodes_full(call=None, for_output=True):
'''
Return a list of the VMs that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or --function.'
)
return _list_nodes(full=True, for_output=for_output)
def list_nodes_select(call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
return salt.utils.cloud.list_nodes_select(
list_nodes_full('function'), __opts__['query.selection'], call,
)
def get_image(vm_):
'''
Return the image object to use
'''
images = avail_images()
vm_image = config.get_cloud_config_value(
'image', vm_, __opts__, search_global=False
)
if not isinstance(vm_image, six.string_types):
vm_image = six.text_type(vm_image)
for image in images:
if vm_image in (images[image]['name'],
images[image]['slug'],
images[image]['id']):
if images[image]['slug'] is not None:
return images[image]['slug']
return int(images[image]['id'])
raise SaltCloudNotFound(
'The specified image, \'{0}\', could not be found.'.format(vm_image)
)
def get_size(vm_):
'''
Return the VM's size. Used by create_node().
'''
sizes = avail_sizes()
vm_size = six.text_type(config.get_cloud_config_value(
'size', vm_, __opts__, search_global=False
))
for size in sizes:
if vm_size.lower() == sizes[size]['slug']:
return sizes[size]['slug']
raise SaltCloudNotFound(
'The specified size, \'{0}\', could not be found.'.format(vm_size)
)
def get_location(vm_):
'''
Return the VM's location
'''
locations = avail_locations()
vm_location = six.text_type(config.get_cloud_config_value(
'location', vm_, __opts__, search_global=False
))
for location in locations:
if vm_location in (locations[location]['name'],
locations[location]['slug']):
return locations[location]['slug']
raise SaltCloudNotFound(
'The specified location, \'{0}\', could not be found.'.format(
vm_location
)
)
def create_node(args):
'''
Create a node
'''
node = query(method='droplets', args=args, http_method='post')
return node
def create(vm_):
'''
Create a single VM from a data dict
'''
try:
# Check for required profile parameters before sending any API calls.
if vm_['profile'] and config.is_profile_configured(__opts__,
__active_provider_name__ or 'digitalocean',
vm_['profile'],
vm_=vm_) is False:
return False
except AttributeError:
pass
__utils__['cloud.fire_event'](
'event',
'starting create',
'salt/cloud/{0}/creating'.format(vm_['name']),
args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Creating Cloud VM %s', vm_['name'])
kwargs = {
'name': vm_['name'],
'size': get_size(vm_),
'image': get_image(vm_),
'region': get_location(vm_),
'ssh_keys': [],
'tags': []
}
# backwards compat
ssh_key_name = config.get_cloud_config_value(
'ssh_key_name', vm_, __opts__, search_global=False
)
if ssh_key_name:
kwargs['ssh_keys'].append(get_keyid(ssh_key_name))
ssh_key_names = config.get_cloud_config_value(
'ssh_key_names', vm_, __opts__, search_global=False, default=False
)
if ssh_key_names:
for key in ssh_key_names.split(','):
kwargs['ssh_keys'].append(get_keyid(key))
key_filename = config.get_cloud_config_value(
'ssh_key_file', vm_, __opts__, search_global=False, default=None
)
if key_filename is not None and not os.path.isfile(key_filename):
raise SaltCloudConfigError(
'The defined key_filename \'{0}\' does not exist'.format(
key_filename
)
)
if not __opts__.get('ssh_agent', False) and key_filename is None:
raise SaltCloudConfigError(
'The DigitalOcean driver requires an ssh_key_file and an ssh_key_name '
'because it does not supply a root password upon building the server.'
)
ssh_interface = config.get_cloud_config_value(
'ssh_interface', vm_, __opts__, search_global=False, default='public'
)
if ssh_interface in ['private', 'public']:
log.info("ssh_interface: Setting interface for ssh to %s", ssh_interface)
kwargs['ssh_interface'] = ssh_interface
else:
raise SaltCloudConfigError(
"The DigitalOcean driver requires ssh_interface to be defined as 'public' or 'private'."
)
private_networking = config.get_cloud_config_value(
'private_networking', vm_, __opts__, search_global=False, default=None,
)
if private_networking is not None:
if not isinstance(private_networking, bool):
raise SaltCloudConfigError("'private_networking' should be a boolean value.")
kwargs['private_networking'] = private_networking
if not private_networking and ssh_interface == 'private':
raise SaltCloudConfigError(
"The DigitalOcean driver requires ssh_interface if defined as 'private' "
"then private_networking should be set as 'True'."
)
backups_enabled = config.get_cloud_config_value(
'backups_enabled', vm_, __opts__, search_global=False, default=None,
)
if backups_enabled is not None:
if not isinstance(backups_enabled, bool):
raise SaltCloudConfigError("'backups_enabled' should be a boolean value.")
kwargs['backups'] = backups_enabled
ipv6 = config.get_cloud_config_value(
'ipv6', vm_, __opts__, search_global=False, default=None,
)
if ipv6 is not None:
if not isinstance(ipv6, bool):
raise SaltCloudConfigError("'ipv6' should be a boolean value.")
kwargs['ipv6'] = ipv6
monitoring = config.get_cloud_config_value(
'monitoring', vm_, __opts__, search_global=False, default=None,
)
if monitoring is not None:
if not isinstance(monitoring, bool):
raise SaltCloudConfigError("'monitoring' should be a boolean value.")
kwargs['monitoring'] = monitoring
kwargs['tags'] = config.get_cloud_config_value(
'tags', vm_, __opts__, search_global=False, default=False
)
userdata_file = config.get_cloud_config_value(
'userdata_file', vm_, __opts__, search_global=False, default=None
)
if userdata_file is not None:
try:
with salt.utils.files.fopen(userdata_file, 'r') as fp_:
kwargs['user_data'] = salt.utils.cloud.userdata_template(
__opts__, vm_, salt.utils.stringutils.to_unicode(fp_.read())
)
except Exception as exc:
log.exception(
'Failed to read userdata from %s: %s', userdata_file, exc)
create_dns_record = config.get_cloud_config_value(
'create_dns_record', vm_, __opts__, search_global=False, default=None,
)
if create_dns_record:
log.info('create_dns_record: will attempt to write DNS records')
default_dns_domain = None
dns_domain_name = vm_['name'].split('.')
if len(dns_domain_name) > 2:
log.debug('create_dns_record: inferring default dns_hostname, dns_domain from minion name as FQDN')
default_dns_hostname = '.'.join(dns_domain_name[:-2])
default_dns_domain = '.'.join(dns_domain_name[-2:])
else:
log.debug("create_dns_record: can't infer dns_domain from %s", vm_['name'])
default_dns_hostname = dns_domain_name[0]
dns_hostname = config.get_cloud_config_value(
'dns_hostname', vm_, __opts__, search_global=False, default=default_dns_hostname,
)
dns_domain = config.get_cloud_config_value(
'dns_domain', vm_, __opts__, search_global=False, default=default_dns_domain,
)
if dns_hostname and dns_domain:
log.info('create_dns_record: using dns_hostname="%s", dns_domain="%s"', dns_hostname, dns_domain)
__add_dns_addr__ = lambda t, d: post_dns_record(dns_domain=dns_domain,
name=dns_hostname,
record_type=t,
record_data=d)
log.debug('create_dns_record: %s', __add_dns_addr__)
else:
log.error('create_dns_record: could not determine dns_hostname and/or dns_domain')
raise SaltCloudConfigError(
'\'create_dns_record\' must be a dict specifying "domain" '
'and "hostname" or the minion name must be an FQDN.'
)
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args=__utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
try:
ret = create_node(kwargs)
except Exception as exc:
log.error(
'Error creating %s on DIGITALOCEAN\n\n'
'The following exception was thrown when trying to '
'run the initial deployment: %s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
def __query_node_data(vm_name):
data = show_instance(vm_name, 'action')
if not data:
# Trigger an error in the wait_for_ip function
return False
if data['networks'].get('v4'):
for network in data['networks']['v4']:
if network['type'] == 'public':
return data
return False
try:
data = salt.utils.cloud.wait_for_ip(
__query_node_data,
update_args=(vm_['name'],),
timeout=config.get_cloud_config_value(
'wait_for_ip_timeout', vm_, __opts__, default=10 * 60),
interval=config.get_cloud_config_value(
'wait_for_ip_interval', vm_, __opts__, default=10),
)
except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc:
try:
# It might be already up, let's destroy it!
destroy(vm_['name'])
except SaltCloudSystemExit:
pass
finally:
raise SaltCloudSystemExit(six.text_type(exc))
if not vm_.get('ssh_host'):
vm_['ssh_host'] = None
# add DNS records, set ssh_host, default to first found IP, preferring IPv4 for ssh bootstrap script target
addr_families, dns_arec_types = (('v4', 'v6'), ('A', 'AAAA'))
arec_map = dict(list(zip(addr_families, dns_arec_types)))
for facing, addr_family, ip_address in [(net['type'], family, net['ip_address'])
for family in addr_families
for net in data['networks'][family]]:
log.info('found %s IP%s interface for "%s"', facing, addr_family, ip_address)
dns_rec_type = arec_map[addr_family]
if facing == 'public':
if create_dns_record:
__add_dns_addr__(dns_rec_type, ip_address)
if facing == ssh_interface:
if not vm_['ssh_host']:
vm_['ssh_host'] = ip_address
if vm_['ssh_host'] is None:
raise SaltCloudSystemExit(
'No suitable IP addresses found for ssh minion bootstrapping: {0}'.format(repr(data['networks']))
)
log.debug(
'Found public IP address to use for ssh minion bootstrapping: %s',
vm_['ssh_host']
)
vm_['key_filename'] = key_filename
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
ret.update(data)
log.info('Created Cloud VM \'%s\'', vm_['name'])
log.debug(
'\'%s\' VM creation details:\n%s',
vm_['name'], pprint.pformat(data)
)
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return ret
def query(method='droplets', droplet_id=None, command=None, args=None, http_method='get'):
'''
Make a web call to DigitalOcean
'''
base_path = six.text_type(config.get_cloud_config_value(
'api_root',
get_configured_provider(),
__opts__,
search_global=False,
default='https://api.digitalocean.com/v2'
))
path = '{0}/{1}/'.format(base_path, method)
if droplet_id:
path += '{0}/'.format(droplet_id)
if command:
path += command
if not isinstance(args, dict):
args = {}
personal_access_token = config.get_cloud_config_value(
'personal_access_token', get_configured_provider(), __opts__, search_global=False
)
data = salt.utils.json.dumps(args)
requester = getattr(requests, http_method)
request = requester(path, data=data, headers={'Authorization': 'Bearer ' + personal_access_token, 'Content-Type': 'application/json'})
if request.status_code > 299:
raise SaltCloudSystemExit(
'An error occurred while querying DigitalOcean. HTTP Code: {0} '
'Error: \'{1}\''.format(
request.status_code,
# request.read()
request.text
)
)
log.debug(request.url)
# success without data
if request.status_code == 204:
return True
content = request.text
result = salt.utils.json.loads(content)
if result.get('status', '').lower() == 'error':
raise SaltCloudSystemExit(
pprint.pformat(result.get('error_message', {}))
)
return result
def script(vm_):
'''
Return the script deployment object
'''
deploy_script = salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
return deploy_script
def show_instance(name, call=None):
'''
Show the details from DigitalOcean concerning a droplet
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
node = _get_node(name)
__utils__['cloud.cache_node'](node, __active_provider_name__, __opts__)
return node
def _get_node(name):
attempts = 10
while attempts >= 0:
try:
return list_nodes_full(for_output=False)[name]
except KeyError:
attempts -= 1
log.debug(
'Failed to get the data for node \'%s\'. Remaining '
'attempts: %s', name, attempts
)
# Just a little delay between attempts...
time.sleep(0.5)
return {}
def list_keypairs(call=None):
'''
Return a dict of all available VM locations on the cloud provider with
relevant data
'''
if call != 'function':
log.error(
'The list_keypairs function must be called with -f or --function.'
)
return False
fetch = True
page = 1
ret = {}
while fetch:
items = query(method='account/keys', command='?page=' + six.text_type(page) +
'&per_page=100')
for key_pair in items['ssh_keys']:
name = key_pair['name']
if name in ret:
raise SaltCloudSystemExit(
'A duplicate key pair name, \'{0}\', was found in DigitalOcean\'s '
'key pair list. Please change the key name stored by DigitalOcean. '
'Be sure to adjust the value of \'ssh_key_file\' in your cloud '
'profile or provider configuration, if necessary.'.format(
name
)
)
ret[name] = {}
for item in six.iterkeys(key_pair):
ret[name][item] = six.text_type(key_pair[item])
page += 1
try:
fetch = 'next' in items['links']['pages']
except KeyError:
fetch = False
return ret
def show_keypair(kwargs=None, call=None):
'''
Show the details of an SSH keypair
'''
if call != 'function':
log.error(
'The show_keypair function must be called with -f or --function.'
)
return False
if not kwargs:
kwargs = {}
if 'keyname' not in kwargs:
log.error('A keyname is required.')
return False
keypairs = list_keypairs(call='function')
keyid = keypairs[kwargs['keyname']]['id']
log.debug('Key ID is %s', keyid)
details = query(method='account/keys', command=keyid)
return details
def import_keypair(kwargs=None, call=None):
'''
Upload public key to cloud provider.
Similar to EC2 import_keypair.
.. versionadded:: 2016.11.0
kwargs
file(mandatory): public key file-name
keyname(mandatory): public key name in the provider
'''
with salt.utils.files.fopen(kwargs['file'], 'r') as public_key_filename:
public_key_content = salt.utils.stringutils.to_unicode(public_key_filename.read())
digitalocean_kwargs = {
'name': kwargs['keyname'],
'public_key': public_key_content
}
created_result = create_key(digitalocean_kwargs, call=call)
return created_result
def create_key(kwargs=None, call=None):
'''
Upload a public key
'''
if call != 'function':
log.error(
'The create_key function must be called with -f or --function.'
)
return False
try:
result = query(
method='account',
command='keys',
args={'name': kwargs['name'],
'public_key': kwargs['public_key']},
http_method='post'
)
except KeyError:
log.info('`name` and `public_key` arguments must be specified')
return False
return result
def remove_key(kwargs=None, call=None):
'''
Delete public key
'''
if call != 'function':
log.error(
'The create_key function must be called with -f or --function.'
)
return False
try:
result = query(
method='account',
command='keys/' + kwargs['id'],
http_method='delete'
)
except KeyError:
log.info('`id` argument must be specified')
return False
return result
def get_keyid(keyname):
'''
Return the ID of the keyname
'''
if not keyname:
return None
keypairs = list_keypairs(call='function')
keyid = keypairs[keyname]['id']
if keyid:
return keyid
raise SaltCloudNotFound('The specified ssh key could not be found.')
def destroy(name, call=None):
'''
Destroy a node. Will check termination protection and warn if enabled.
CLI Example:
.. code-block:: bash
salt-cloud --destroy mymachine
'''
if call == 'function':
raise SaltCloudSystemExit(
'The destroy action must be called with -d, --destroy, '
'-a or --action.'
)
__utils__['cloud.fire_event'](
'event',
'destroying instance',
'salt/cloud/{0}/destroying'.format(name),
args={'name': name},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
data = show_instance(name, call='action')
node = query(method='droplets', droplet_id=data['id'], http_method='delete')
## This is all terribly optomistic:
# vm_ = get_vm_config(name=name)
# delete_dns_record = config.get_cloud_config_value(
# 'delete_dns_record', vm_, __opts__, search_global=False, default=None,
# )
# TODO: when _vm config data can be made available, we should honor the configuration settings,
# but until then, we should assume stale DNS records are bad, and default behavior should be to
# delete them if we can. When this is resolved, also resolve the comments a couple of lines below.
delete_dns_record = True
if not isinstance(delete_dns_record, bool):
raise SaltCloudConfigError(
'\'delete_dns_record\' should be a boolean value.'
)
# When the "to do" a few lines up is resolved, remove these lines and use the if/else logic below.
log.debug('Deleting DNS records for %s.', name)
destroy_dns_records(name)
# Until the "to do" from line 754 is taken care of, we don't need this logic.
# if delete_dns_record:
# log.debug('Deleting DNS records for %s.', name)
# destroy_dns_records(name)
# else:
# log.debug('delete_dns_record : %s', delete_dns_record)
# for line in pprint.pformat(dir()).splitlines():
# log.debug('delete context: %s', line)
__utils__['cloud.fire_event'](
'event',
'destroyed instance',
'salt/cloud/{0}/destroyed'.format(name),
args={'name': name},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
if __opts__.get('update_cachedir', False) is True:
__utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__)
return node
def post_dns_record(**kwargs):
'''
Creates a DNS record for the given name if the domain is managed with DO.
'''
if 'kwargs' in kwargs: # flatten kwargs if called via salt-cloud -f
f_kwargs = kwargs['kwargs']
del kwargs['kwargs']
kwargs.update(f_kwargs)
mandatory_kwargs = ('dns_domain', 'name', 'record_type', 'record_data')
for i in mandatory_kwargs:
if kwargs[i]:
pass
else:
error = '{0}="{1}" ## all mandatory args must be provided: {2}'.format(i, kwargs[i], mandatory_kwargs)
raise SaltInvocationError(error)
domain = query(method='domains', droplet_id=kwargs['dns_domain'])
if domain:
result = query(
method='domains',
droplet_id=kwargs['dns_domain'],
command='records',
args={'type': kwargs['record_type'], 'name': kwargs['name'], 'data': kwargs['record_data']},
http_method='post'
)
return result
return False
def destroy_dns_records(fqdn):
'''
Deletes DNS records for the given hostname if the domain is managed with DO.
'''
domain = '.'.join(fqdn.split('.')[-2:])
hostname = '.'.join(fqdn.split('.')[:-2])
# TODO: remove this when the todo on 754 is available
try:
response = query(method='domains', droplet_id=domain, command='records')
except SaltCloudSystemExit:
log.debug('Failed to find domains.')
return False
log.debug("found DNS records: %s", pprint.pformat(response))
records = response['domain_records']
if records:
record_ids = [r['id'] for r in records if r['name'].decode() == hostname]
log.debug("deleting DNS record IDs: %s", record_ids)
for id_ in record_ids:
try:
log.info('deleting DNS record %s', id_)
ret = query(
method='domains',
droplet_id=domain,
command='records/{0}'.format(id_),
http_method='delete'
)
except SaltCloudSystemExit:
log.error('failed to delete DNS domain %s record ID %s.', domain, hostname)
log.debug('DNS deletion REST call returned: %s', pprint.pformat(ret))
return False
def show_pricing(kwargs=None, call=None):
'''
Show pricing for a particular profile. This is only an estimate, based on
unofficial pricing sources.
.. versionadded:: 2015.8.0
CLI Examples:
.. code-block:: bash
salt-cloud -f show_pricing my-digitalocean-config profile=my-profile
'''
profile = __opts__['profiles'].get(kwargs['profile'], {})
if not profile:
return {'Error': 'The requested profile was not found'}
# Make sure the profile belongs to DigitalOcean
provider = profile.get('provider', '0:0')
comps = provider.split(':')
if len(comps) < 2 or comps[1] != 'digitalocean':
return {'Error': 'The requested profile does not belong to DigitalOcean'}
raw = {}
ret = {}
sizes = avail_sizes()
ret['per_hour'] = decimal.Decimal(sizes[profile['size']]['price_hourly'])
ret['per_day'] = ret['per_hour'] * 24
ret['per_week'] = ret['per_day'] * 7
ret['per_month'] = decimal.Decimal(sizes[profile['size']]['price_monthly'])
ret['per_year'] = ret['per_week'] * 52
if kwargs.get('raw', False):
ret['_raw'] = raw
return {profile['profile']: ret}
def list_floating_ips(call=None):
'''
Return a list of the floating ips that are on the provider
.. versionadded:: 2016.3.0
CLI Examples:
.. code-block:: bash
salt-cloud -f list_floating_ips my-digitalocean-config
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_floating_ips function must be called with '
'-f or --function, or with the --list-floating-ips option'
)
fetch = True
page = 1
ret = {}
while fetch:
items = query(method='floating_ips',
command='?page=' + six.text_type(page) + '&per_page=200')
for floating_ip in items['floating_ips']:
ret[floating_ip['ip']] = {}
for item in six.iterkeys(floating_ip):
ret[floating_ip['ip']][item] = floating_ip[item]
page += 1
try:
fetch = 'next' in items['links']['pages']
except KeyError:
fetch = False
return ret
def create_floating_ip(kwargs=None, call=None):
'''
Create a new floating IP
.. versionadded:: 2016.3.0
CLI Examples:
.. code-block:: bash
salt-cloud -f create_floating_ip my-digitalocean-config region='NYC2'
salt-cloud -f create_floating_ip my-digitalocean-config droplet_id='1234567'
'''
if call != 'function':
log.error(
'The create_floating_ip function must be called with -f or --function.'
)
return False
if not kwargs:
kwargs = {}
if 'droplet_id' in kwargs:
result = query(method='floating_ips',
args={'droplet_id': kwargs['droplet_id']},
http_method='post')
return result
elif 'region' in kwargs:
result = query(method='floating_ips',
args={'region': kwargs['region']},
http_method='post')
return result
else:
log.error('A droplet_id or region is required.')
return False
def delete_floating_ip(kwargs=None, call=None):
'''
Delete a floating IP
.. versionadded:: 2016.3.0
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_floating_ip my-digitalocean-config floating_ip='45.55.96.47'
'''
if call != 'function':
log.error(
'The delete_floating_ip function must be called with -f or --function.'
)
return False
if not kwargs:
kwargs = {}
if 'floating_ip' not in kwargs:
log.error('A floating IP is required.')
return False
floating_ip = kwargs['floating_ip']
log.debug('Floating ip is %s', kwargs['floating_ip'])
result = query(method='floating_ips',
command=floating_ip,
http_method='delete')
return result
def assign_floating_ip(kwargs=None, call=None):
'''
Assign a floating IP
.. versionadded:: 2016.3.0
CLI Examples:
.. code-block:: bash
salt-cloud -f assign_floating_ip my-digitalocean-config droplet_id=1234567 floating_ip='45.55.96.47'
'''
if call != 'function':
log.error(
'The assign_floating_ip function must be called with -f or --function.'
)
return False
if not kwargs:
kwargs = {}
if 'floating_ip' and 'droplet_id' not in kwargs:
log.error('A floating IP and droplet_id is required.')
return False
result = query(method='floating_ips',
command=kwargs['floating_ip'] + '/actions',
args={'droplet_id': kwargs['droplet_id'], 'type': 'assign'},
http_method='post')
return result
def unassign_floating_ip(kwargs=None, call=None):
'''
Unassign a floating IP
.. versionadded:: 2016.3.0
CLI Examples:
.. code-block:: bash
salt-cloud -f unassign_floating_ip my-digitalocean-config floating_ip='45.55.96.47'
'''
if call != 'function':
log.error(
'The inassign_floating_ip function must be called with -f or --function.'
)
return False
if not kwargs:
kwargs = {}
if 'floating_ip' not in kwargs:
log.error('A floating IP is required.')
return False
result = query(method='floating_ips',
command=kwargs['floating_ip'] + '/actions',
args={'type': 'unassign'},
http_method='post')
return result
def _list_nodes(full=False, for_output=False):
'''
Helper function to format and parse node data.
'''
fetch = True
page = 1
ret = {}
while fetch:
items = query(method='droplets',
command='?page=' + six.text_type(page) + '&per_page=200')
for node in items['droplets']:
name = node['name']
ret[name] = {}
if full:
ret[name] = _get_full_output(node, for_output=for_output)
else:
public_ips, private_ips = _get_ips(node['networks'])
ret[name] = {
'id': node['id'],
'image': node['image']['name'],
'name': name,
'private_ips': private_ips,
'public_ips': public_ips,
'size': node['size_slug'],
'state': six.text_type(node['status']),
}
page += 1
try:
fetch = 'next' in items['links']['pages']
except KeyError:
fetch = False
return ret
def reboot(name, call=None):
'''
Reboot a droplet in DigitalOcean.
.. versionadded:: 2015.8.8
name
The name of the droplet to restart.
CLI Example:
.. code-block:: bash
salt-cloud -a reboot droplet_name
'''
if call != 'action':
raise SaltCloudSystemExit(
'The restart action must be called with -a or --action.'
)
data = show_instance(name, call='action')
if data.get('status') == 'off':
return {'success': True,
'action': 'stop',
'status': 'off',
'msg': 'Machine is already off.'}
ret = query(droplet_id=data['id'],
command='actions',
args={'type': 'reboot'},
http_method='post')
return {'success': True,
'action': ret['action']['type'],
'state': ret['action']['status']}
def start(name, call=None):
'''
Start a droplet in DigitalOcean.
.. versionadded:: 2015.8.8
name
The name of the droplet to start.
CLI Example:
.. code-block:: bash
salt-cloud -a start droplet_name
'''
if call != 'action':
raise SaltCloudSystemExit(
'The start action must be called with -a or --action.'
)
data = show_instance(name, call='action')
if data.get('status') == 'active':
return {'success': True,
'action': 'start',
'status': 'active',
'msg': 'Machine is already running.'}
ret = query(droplet_id=data['id'],
command='actions',
args={'type': 'power_on'},
http_method='post')
return {'success': True,
'action': ret['action']['type'],
'state': ret['action']['status']}
def stop(name, call=None):
'''
Stop a droplet in DigitalOcean.
.. versionadded:: 2015.8.8
name
The name of the droplet to stop.
CLI Example:
.. code-block:: bash
salt-cloud -a stop droplet_name
'''
if call != 'action':
raise SaltCloudSystemExit(
'The stop action must be called with -a or --action.'
)
data = show_instance(name, call='action')
if data.get('status') == 'off':
return {'success': True,
'action': 'stop',
'status': 'off',
'msg': 'Machine is already off.'}
ret = query(droplet_id=data['id'],
command='actions',
args={'type': 'shutdown'},
http_method='post')
return {'success': True,
'action': ret['action']['type'],
'state': ret['action']['status']}
def _get_full_output(node, for_output=False):
'''
Helper function for _list_nodes to loop through all node information.
Returns a dictionary containing the full information of a node.
'''
ret = {}
for item in six.iterkeys(node):
value = node[item]
if value is not None and for_output:
value = six.text_type(value)
ret[item] = value
return ret
def _get_ips(networks):
'''
Helper function for list_nodes. Returns public and private ip lists based on a
given network dictionary.
'''
v4s = networks.get('v4')
v6s = networks.get('v6')
public_ips = []
private_ips = []
if v4s:
for item in v4s:
ip_type = item.get('type')
ip_address = item.get('ip_address')
if ip_type == 'public':
public_ips.append(ip_address)
if ip_type == 'private':
private_ips.append(ip_address)
if v6s:
for item in v6s:
ip_type = item.get('type')
ip_address = item.get('ip_address')
if ip_type == 'public':
public_ips.append(ip_address)
if ip_type == 'private':
private_ips.append(ip_address)
return public_ips, private_ips
|
saltstack/salt
|
salt/cloud/clouds/digitalocean.py
|
create_floating_ip
|
python
|
def create_floating_ip(kwargs=None, call=None):
'''
Create a new floating IP
.. versionadded:: 2016.3.0
CLI Examples:
.. code-block:: bash
salt-cloud -f create_floating_ip my-digitalocean-config region='NYC2'
salt-cloud -f create_floating_ip my-digitalocean-config droplet_id='1234567'
'''
if call != 'function':
log.error(
'The create_floating_ip function must be called with -f or --function.'
)
return False
if not kwargs:
kwargs = {}
if 'droplet_id' in kwargs:
result = query(method='floating_ips',
args={'droplet_id': kwargs['droplet_id']},
http_method='post')
return result
elif 'region' in kwargs:
result = query(method='floating_ips',
args={'region': kwargs['region']},
http_method='post')
return result
else:
log.error('A droplet_id or region is required.')
return False
|
Create a new floating IP
.. versionadded:: 2016.3.0
CLI Examples:
.. code-block:: bash
salt-cloud -f create_floating_ip my-digitalocean-config region='NYC2'
salt-cloud -f create_floating_ip my-digitalocean-config droplet_id='1234567'
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/digitalocean.py#L1051-L1090
|
[
"def query(method='droplets', droplet_id=None, command=None, args=None, http_method='get'):\n '''\n Make a web call to DigitalOcean\n '''\n base_path = six.text_type(config.get_cloud_config_value(\n 'api_root',\n get_configured_provider(),\n __opts__,\n search_global=False,\n default='https://api.digitalocean.com/v2'\n ))\n\n path = '{0}/{1}/'.format(base_path, method)\n\n if droplet_id:\n path += '{0}/'.format(droplet_id)\n\n if command:\n path += command\n\n if not isinstance(args, dict):\n args = {}\n\n personal_access_token = config.get_cloud_config_value(\n 'personal_access_token', get_configured_provider(), __opts__, search_global=False\n )\n\n data = salt.utils.json.dumps(args)\n\n requester = getattr(requests, http_method)\n request = requester(path, data=data, headers={'Authorization': 'Bearer ' + personal_access_token, 'Content-Type': 'application/json'})\n if request.status_code > 299:\n raise SaltCloudSystemExit(\n 'An error occurred while querying DigitalOcean. HTTP Code: {0} '\n 'Error: \\'{1}\\''.format(\n request.status_code,\n # request.read()\n request.text\n )\n )\n\n log.debug(request.url)\n\n # success without data\n if request.status_code == 204:\n return True\n\n content = request.text\n\n result = salt.utils.json.loads(content)\n if result.get('status', '').lower() == 'error':\n raise SaltCloudSystemExit(\n pprint.pformat(result.get('error_message', {}))\n )\n\n return result\n"
] |
# -*- coding: utf-8 -*-
'''
DigitalOcean Cloud Module
=========================
The DigitalOcean cloud module is used to control access to the DigitalOcean VPS system.
Use of this module requires a requires a ``personal_access_token``, an ``ssh_key_file``,
and at least one SSH key name in ``ssh_key_names``. More ``ssh_key_names`` can be added
by separating each key with a comma. The ``personal_access_token`` can be found in the
DigitalOcean web interface in the "Apps & API" section. The SSH key name can be found
under the "SSH Keys" section.
.. code-block:: yaml
# Note: This example is for /etc/salt/cloud.providers or any file in the
# /etc/salt/cloud.providers.d/ directory.
my-digital-ocean-config:
personal_access_token: xxx
ssh_key_file: /path/to/ssh/key/file
ssh_key_names: my-key-name,my-key-name-2
driver: digitalocean
:depends: requests
'''
# Import Python Libs
from __future__ import absolute_import, print_function, unicode_literals
import decimal
import logging
import os
import pprint
import time
# Import Salt Libs
import salt.utils.cloud
import salt.utils.files
import salt.utils.json
import salt.utils.stringutils
import salt.config as config
from salt.exceptions import (
SaltCloudConfigError,
SaltInvocationError,
SaltCloudNotFound,
SaltCloudSystemExit,
SaltCloudExecutionFailure,
SaltCloudExecutionTimeout
)
from salt.ext import six
from salt.ext.six.moves import zip
# Import Third Party Libs
try:
import requests
HAS_REQUESTS = True
except ImportError:
HAS_REQUESTS = False
# Get logging started
log = logging.getLogger(__name__)
__virtualname__ = 'digitalocean'
__virtual_aliases__ = ('digital_ocean', 'do')
# Only load in this module if the DIGITALOCEAN configurations are in place
def __virtual__():
'''
Check for DigitalOcean configurations
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
opts=__opts__,
provider=__active_provider_name__ or __virtualname__,
aliases=__virtual_aliases__,
required_keys=('personal_access_token',)
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'requests': HAS_REQUESTS}
)
def avail_locations(call=None):
'''
Return a dict of all available VM locations on the cloud provider with
relevant data
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
items = query(method='regions')
ret = {}
for region in items['regions']:
ret[region['name']] = {}
for item in six.iterkeys(region):
ret[region['name']][item] = six.text_type(region[item])
return ret
def avail_images(call=None):
'''
Return a list of the images that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
fetch = True
page = 1
ret = {}
while fetch:
items = query(method='images', command='?page=' + six.text_type(page) + '&per_page=200')
for image in items['images']:
ret[image['name']] = {}
for item in six.iterkeys(image):
ret[image['name']][item] = image[item]
page += 1
try:
fetch = 'next' in items['links']['pages']
except KeyError:
fetch = False
return ret
def avail_sizes(call=None):
'''
Return a list of the image sizes that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
items = query(method='sizes', command='?per_page=100')
ret = {}
for size in items['sizes']:
ret[size['slug']] = {}
for item in six.iterkeys(size):
ret[size['slug']][item] = six.text_type(size[item])
return ret
def list_nodes(call=None):
'''
Return a list of the VMs that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
return _list_nodes()
def list_nodes_full(call=None, for_output=True):
'''
Return a list of the VMs that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or --function.'
)
return _list_nodes(full=True, for_output=for_output)
def list_nodes_select(call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
return salt.utils.cloud.list_nodes_select(
list_nodes_full('function'), __opts__['query.selection'], call,
)
def get_image(vm_):
'''
Return the image object to use
'''
images = avail_images()
vm_image = config.get_cloud_config_value(
'image', vm_, __opts__, search_global=False
)
if not isinstance(vm_image, six.string_types):
vm_image = six.text_type(vm_image)
for image in images:
if vm_image in (images[image]['name'],
images[image]['slug'],
images[image]['id']):
if images[image]['slug'] is not None:
return images[image]['slug']
return int(images[image]['id'])
raise SaltCloudNotFound(
'The specified image, \'{0}\', could not be found.'.format(vm_image)
)
def get_size(vm_):
'''
Return the VM's size. Used by create_node().
'''
sizes = avail_sizes()
vm_size = six.text_type(config.get_cloud_config_value(
'size', vm_, __opts__, search_global=False
))
for size in sizes:
if vm_size.lower() == sizes[size]['slug']:
return sizes[size]['slug']
raise SaltCloudNotFound(
'The specified size, \'{0}\', could not be found.'.format(vm_size)
)
def get_location(vm_):
'''
Return the VM's location
'''
locations = avail_locations()
vm_location = six.text_type(config.get_cloud_config_value(
'location', vm_, __opts__, search_global=False
))
for location in locations:
if vm_location in (locations[location]['name'],
locations[location]['slug']):
return locations[location]['slug']
raise SaltCloudNotFound(
'The specified location, \'{0}\', could not be found.'.format(
vm_location
)
)
def create_node(args):
'''
Create a node
'''
node = query(method='droplets', args=args, http_method='post')
return node
def create(vm_):
'''
Create a single VM from a data dict
'''
try:
# Check for required profile parameters before sending any API calls.
if vm_['profile'] and config.is_profile_configured(__opts__,
__active_provider_name__ or 'digitalocean',
vm_['profile'],
vm_=vm_) is False:
return False
except AttributeError:
pass
__utils__['cloud.fire_event'](
'event',
'starting create',
'salt/cloud/{0}/creating'.format(vm_['name']),
args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Creating Cloud VM %s', vm_['name'])
kwargs = {
'name': vm_['name'],
'size': get_size(vm_),
'image': get_image(vm_),
'region': get_location(vm_),
'ssh_keys': [],
'tags': []
}
# backwards compat
ssh_key_name = config.get_cloud_config_value(
'ssh_key_name', vm_, __opts__, search_global=False
)
if ssh_key_name:
kwargs['ssh_keys'].append(get_keyid(ssh_key_name))
ssh_key_names = config.get_cloud_config_value(
'ssh_key_names', vm_, __opts__, search_global=False, default=False
)
if ssh_key_names:
for key in ssh_key_names.split(','):
kwargs['ssh_keys'].append(get_keyid(key))
key_filename = config.get_cloud_config_value(
'ssh_key_file', vm_, __opts__, search_global=False, default=None
)
if key_filename is not None and not os.path.isfile(key_filename):
raise SaltCloudConfigError(
'The defined key_filename \'{0}\' does not exist'.format(
key_filename
)
)
if not __opts__.get('ssh_agent', False) and key_filename is None:
raise SaltCloudConfigError(
'The DigitalOcean driver requires an ssh_key_file and an ssh_key_name '
'because it does not supply a root password upon building the server.'
)
ssh_interface = config.get_cloud_config_value(
'ssh_interface', vm_, __opts__, search_global=False, default='public'
)
if ssh_interface in ['private', 'public']:
log.info("ssh_interface: Setting interface for ssh to %s", ssh_interface)
kwargs['ssh_interface'] = ssh_interface
else:
raise SaltCloudConfigError(
"The DigitalOcean driver requires ssh_interface to be defined as 'public' or 'private'."
)
private_networking = config.get_cloud_config_value(
'private_networking', vm_, __opts__, search_global=False, default=None,
)
if private_networking is not None:
if not isinstance(private_networking, bool):
raise SaltCloudConfigError("'private_networking' should be a boolean value.")
kwargs['private_networking'] = private_networking
if not private_networking and ssh_interface == 'private':
raise SaltCloudConfigError(
"The DigitalOcean driver requires ssh_interface if defined as 'private' "
"then private_networking should be set as 'True'."
)
backups_enabled = config.get_cloud_config_value(
'backups_enabled', vm_, __opts__, search_global=False, default=None,
)
if backups_enabled is not None:
if not isinstance(backups_enabled, bool):
raise SaltCloudConfigError("'backups_enabled' should be a boolean value.")
kwargs['backups'] = backups_enabled
ipv6 = config.get_cloud_config_value(
'ipv6', vm_, __opts__, search_global=False, default=None,
)
if ipv6 is not None:
if not isinstance(ipv6, bool):
raise SaltCloudConfigError("'ipv6' should be a boolean value.")
kwargs['ipv6'] = ipv6
monitoring = config.get_cloud_config_value(
'monitoring', vm_, __opts__, search_global=False, default=None,
)
if monitoring is not None:
if not isinstance(monitoring, bool):
raise SaltCloudConfigError("'monitoring' should be a boolean value.")
kwargs['monitoring'] = monitoring
kwargs['tags'] = config.get_cloud_config_value(
'tags', vm_, __opts__, search_global=False, default=False
)
userdata_file = config.get_cloud_config_value(
'userdata_file', vm_, __opts__, search_global=False, default=None
)
if userdata_file is not None:
try:
with salt.utils.files.fopen(userdata_file, 'r') as fp_:
kwargs['user_data'] = salt.utils.cloud.userdata_template(
__opts__, vm_, salt.utils.stringutils.to_unicode(fp_.read())
)
except Exception as exc:
log.exception(
'Failed to read userdata from %s: %s', userdata_file, exc)
create_dns_record = config.get_cloud_config_value(
'create_dns_record', vm_, __opts__, search_global=False, default=None,
)
if create_dns_record:
log.info('create_dns_record: will attempt to write DNS records')
default_dns_domain = None
dns_domain_name = vm_['name'].split('.')
if len(dns_domain_name) > 2:
log.debug('create_dns_record: inferring default dns_hostname, dns_domain from minion name as FQDN')
default_dns_hostname = '.'.join(dns_domain_name[:-2])
default_dns_domain = '.'.join(dns_domain_name[-2:])
else:
log.debug("create_dns_record: can't infer dns_domain from %s", vm_['name'])
default_dns_hostname = dns_domain_name[0]
dns_hostname = config.get_cloud_config_value(
'dns_hostname', vm_, __opts__, search_global=False, default=default_dns_hostname,
)
dns_domain = config.get_cloud_config_value(
'dns_domain', vm_, __opts__, search_global=False, default=default_dns_domain,
)
if dns_hostname and dns_domain:
log.info('create_dns_record: using dns_hostname="%s", dns_domain="%s"', dns_hostname, dns_domain)
__add_dns_addr__ = lambda t, d: post_dns_record(dns_domain=dns_domain,
name=dns_hostname,
record_type=t,
record_data=d)
log.debug('create_dns_record: %s', __add_dns_addr__)
else:
log.error('create_dns_record: could not determine dns_hostname and/or dns_domain')
raise SaltCloudConfigError(
'\'create_dns_record\' must be a dict specifying "domain" '
'and "hostname" or the minion name must be an FQDN.'
)
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args=__utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
try:
ret = create_node(kwargs)
except Exception as exc:
log.error(
'Error creating %s on DIGITALOCEAN\n\n'
'The following exception was thrown when trying to '
'run the initial deployment: %s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
def __query_node_data(vm_name):
data = show_instance(vm_name, 'action')
if not data:
# Trigger an error in the wait_for_ip function
return False
if data['networks'].get('v4'):
for network in data['networks']['v4']:
if network['type'] == 'public':
return data
return False
try:
data = salt.utils.cloud.wait_for_ip(
__query_node_data,
update_args=(vm_['name'],),
timeout=config.get_cloud_config_value(
'wait_for_ip_timeout', vm_, __opts__, default=10 * 60),
interval=config.get_cloud_config_value(
'wait_for_ip_interval', vm_, __opts__, default=10),
)
except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc:
try:
# It might be already up, let's destroy it!
destroy(vm_['name'])
except SaltCloudSystemExit:
pass
finally:
raise SaltCloudSystemExit(six.text_type(exc))
if not vm_.get('ssh_host'):
vm_['ssh_host'] = None
# add DNS records, set ssh_host, default to first found IP, preferring IPv4 for ssh bootstrap script target
addr_families, dns_arec_types = (('v4', 'v6'), ('A', 'AAAA'))
arec_map = dict(list(zip(addr_families, dns_arec_types)))
for facing, addr_family, ip_address in [(net['type'], family, net['ip_address'])
for family in addr_families
for net in data['networks'][family]]:
log.info('found %s IP%s interface for "%s"', facing, addr_family, ip_address)
dns_rec_type = arec_map[addr_family]
if facing == 'public':
if create_dns_record:
__add_dns_addr__(dns_rec_type, ip_address)
if facing == ssh_interface:
if not vm_['ssh_host']:
vm_['ssh_host'] = ip_address
if vm_['ssh_host'] is None:
raise SaltCloudSystemExit(
'No suitable IP addresses found for ssh minion bootstrapping: {0}'.format(repr(data['networks']))
)
log.debug(
'Found public IP address to use for ssh minion bootstrapping: %s',
vm_['ssh_host']
)
vm_['key_filename'] = key_filename
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
ret.update(data)
log.info('Created Cloud VM \'%s\'', vm_['name'])
log.debug(
'\'%s\' VM creation details:\n%s',
vm_['name'], pprint.pformat(data)
)
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return ret
def query(method='droplets', droplet_id=None, command=None, args=None, http_method='get'):
'''
Make a web call to DigitalOcean
'''
base_path = six.text_type(config.get_cloud_config_value(
'api_root',
get_configured_provider(),
__opts__,
search_global=False,
default='https://api.digitalocean.com/v2'
))
path = '{0}/{1}/'.format(base_path, method)
if droplet_id:
path += '{0}/'.format(droplet_id)
if command:
path += command
if not isinstance(args, dict):
args = {}
personal_access_token = config.get_cloud_config_value(
'personal_access_token', get_configured_provider(), __opts__, search_global=False
)
data = salt.utils.json.dumps(args)
requester = getattr(requests, http_method)
request = requester(path, data=data, headers={'Authorization': 'Bearer ' + personal_access_token, 'Content-Type': 'application/json'})
if request.status_code > 299:
raise SaltCloudSystemExit(
'An error occurred while querying DigitalOcean. HTTP Code: {0} '
'Error: \'{1}\''.format(
request.status_code,
# request.read()
request.text
)
)
log.debug(request.url)
# success without data
if request.status_code == 204:
return True
content = request.text
result = salt.utils.json.loads(content)
if result.get('status', '').lower() == 'error':
raise SaltCloudSystemExit(
pprint.pformat(result.get('error_message', {}))
)
return result
def script(vm_):
'''
Return the script deployment object
'''
deploy_script = salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
return deploy_script
def show_instance(name, call=None):
'''
Show the details from DigitalOcean concerning a droplet
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
node = _get_node(name)
__utils__['cloud.cache_node'](node, __active_provider_name__, __opts__)
return node
def _get_node(name):
attempts = 10
while attempts >= 0:
try:
return list_nodes_full(for_output=False)[name]
except KeyError:
attempts -= 1
log.debug(
'Failed to get the data for node \'%s\'. Remaining '
'attempts: %s', name, attempts
)
# Just a little delay between attempts...
time.sleep(0.5)
return {}
def list_keypairs(call=None):
'''
Return a dict of all available VM locations on the cloud provider with
relevant data
'''
if call != 'function':
log.error(
'The list_keypairs function must be called with -f or --function.'
)
return False
fetch = True
page = 1
ret = {}
while fetch:
items = query(method='account/keys', command='?page=' + six.text_type(page) +
'&per_page=100')
for key_pair in items['ssh_keys']:
name = key_pair['name']
if name in ret:
raise SaltCloudSystemExit(
'A duplicate key pair name, \'{0}\', was found in DigitalOcean\'s '
'key pair list. Please change the key name stored by DigitalOcean. '
'Be sure to adjust the value of \'ssh_key_file\' in your cloud '
'profile or provider configuration, if necessary.'.format(
name
)
)
ret[name] = {}
for item in six.iterkeys(key_pair):
ret[name][item] = six.text_type(key_pair[item])
page += 1
try:
fetch = 'next' in items['links']['pages']
except KeyError:
fetch = False
return ret
def show_keypair(kwargs=None, call=None):
'''
Show the details of an SSH keypair
'''
if call != 'function':
log.error(
'The show_keypair function must be called with -f or --function.'
)
return False
if not kwargs:
kwargs = {}
if 'keyname' not in kwargs:
log.error('A keyname is required.')
return False
keypairs = list_keypairs(call='function')
keyid = keypairs[kwargs['keyname']]['id']
log.debug('Key ID is %s', keyid)
details = query(method='account/keys', command=keyid)
return details
def import_keypair(kwargs=None, call=None):
'''
Upload public key to cloud provider.
Similar to EC2 import_keypair.
.. versionadded:: 2016.11.0
kwargs
file(mandatory): public key file-name
keyname(mandatory): public key name in the provider
'''
with salt.utils.files.fopen(kwargs['file'], 'r') as public_key_filename:
public_key_content = salt.utils.stringutils.to_unicode(public_key_filename.read())
digitalocean_kwargs = {
'name': kwargs['keyname'],
'public_key': public_key_content
}
created_result = create_key(digitalocean_kwargs, call=call)
return created_result
def create_key(kwargs=None, call=None):
'''
Upload a public key
'''
if call != 'function':
log.error(
'The create_key function must be called with -f or --function.'
)
return False
try:
result = query(
method='account',
command='keys',
args={'name': kwargs['name'],
'public_key': kwargs['public_key']},
http_method='post'
)
except KeyError:
log.info('`name` and `public_key` arguments must be specified')
return False
return result
def remove_key(kwargs=None, call=None):
'''
Delete public key
'''
if call != 'function':
log.error(
'The create_key function must be called with -f or --function.'
)
return False
try:
result = query(
method='account',
command='keys/' + kwargs['id'],
http_method='delete'
)
except KeyError:
log.info('`id` argument must be specified')
return False
return result
def get_keyid(keyname):
'''
Return the ID of the keyname
'''
if not keyname:
return None
keypairs = list_keypairs(call='function')
keyid = keypairs[keyname]['id']
if keyid:
return keyid
raise SaltCloudNotFound('The specified ssh key could not be found.')
def destroy(name, call=None):
'''
Destroy a node. Will check termination protection and warn if enabled.
CLI Example:
.. code-block:: bash
salt-cloud --destroy mymachine
'''
if call == 'function':
raise SaltCloudSystemExit(
'The destroy action must be called with -d, --destroy, '
'-a or --action.'
)
__utils__['cloud.fire_event'](
'event',
'destroying instance',
'salt/cloud/{0}/destroying'.format(name),
args={'name': name},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
data = show_instance(name, call='action')
node = query(method='droplets', droplet_id=data['id'], http_method='delete')
## This is all terribly optomistic:
# vm_ = get_vm_config(name=name)
# delete_dns_record = config.get_cloud_config_value(
# 'delete_dns_record', vm_, __opts__, search_global=False, default=None,
# )
# TODO: when _vm config data can be made available, we should honor the configuration settings,
# but until then, we should assume stale DNS records are bad, and default behavior should be to
# delete them if we can. When this is resolved, also resolve the comments a couple of lines below.
delete_dns_record = True
if not isinstance(delete_dns_record, bool):
raise SaltCloudConfigError(
'\'delete_dns_record\' should be a boolean value.'
)
# When the "to do" a few lines up is resolved, remove these lines and use the if/else logic below.
log.debug('Deleting DNS records for %s.', name)
destroy_dns_records(name)
# Until the "to do" from line 754 is taken care of, we don't need this logic.
# if delete_dns_record:
# log.debug('Deleting DNS records for %s.', name)
# destroy_dns_records(name)
# else:
# log.debug('delete_dns_record : %s', delete_dns_record)
# for line in pprint.pformat(dir()).splitlines():
# log.debug('delete context: %s', line)
__utils__['cloud.fire_event'](
'event',
'destroyed instance',
'salt/cloud/{0}/destroyed'.format(name),
args={'name': name},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
if __opts__.get('update_cachedir', False) is True:
__utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__)
return node
def post_dns_record(**kwargs):
'''
Creates a DNS record for the given name if the domain is managed with DO.
'''
if 'kwargs' in kwargs: # flatten kwargs if called via salt-cloud -f
f_kwargs = kwargs['kwargs']
del kwargs['kwargs']
kwargs.update(f_kwargs)
mandatory_kwargs = ('dns_domain', 'name', 'record_type', 'record_data')
for i in mandatory_kwargs:
if kwargs[i]:
pass
else:
error = '{0}="{1}" ## all mandatory args must be provided: {2}'.format(i, kwargs[i], mandatory_kwargs)
raise SaltInvocationError(error)
domain = query(method='domains', droplet_id=kwargs['dns_domain'])
if domain:
result = query(
method='domains',
droplet_id=kwargs['dns_domain'],
command='records',
args={'type': kwargs['record_type'], 'name': kwargs['name'], 'data': kwargs['record_data']},
http_method='post'
)
return result
return False
def destroy_dns_records(fqdn):
'''
Deletes DNS records for the given hostname if the domain is managed with DO.
'''
domain = '.'.join(fqdn.split('.')[-2:])
hostname = '.'.join(fqdn.split('.')[:-2])
# TODO: remove this when the todo on 754 is available
try:
response = query(method='domains', droplet_id=domain, command='records')
except SaltCloudSystemExit:
log.debug('Failed to find domains.')
return False
log.debug("found DNS records: %s", pprint.pformat(response))
records = response['domain_records']
if records:
record_ids = [r['id'] for r in records if r['name'].decode() == hostname]
log.debug("deleting DNS record IDs: %s", record_ids)
for id_ in record_ids:
try:
log.info('deleting DNS record %s', id_)
ret = query(
method='domains',
droplet_id=domain,
command='records/{0}'.format(id_),
http_method='delete'
)
except SaltCloudSystemExit:
log.error('failed to delete DNS domain %s record ID %s.', domain, hostname)
log.debug('DNS deletion REST call returned: %s', pprint.pformat(ret))
return False
def show_pricing(kwargs=None, call=None):
'''
Show pricing for a particular profile. This is only an estimate, based on
unofficial pricing sources.
.. versionadded:: 2015.8.0
CLI Examples:
.. code-block:: bash
salt-cloud -f show_pricing my-digitalocean-config profile=my-profile
'''
profile = __opts__['profiles'].get(kwargs['profile'], {})
if not profile:
return {'Error': 'The requested profile was not found'}
# Make sure the profile belongs to DigitalOcean
provider = profile.get('provider', '0:0')
comps = provider.split(':')
if len(comps) < 2 or comps[1] != 'digitalocean':
return {'Error': 'The requested profile does not belong to DigitalOcean'}
raw = {}
ret = {}
sizes = avail_sizes()
ret['per_hour'] = decimal.Decimal(sizes[profile['size']]['price_hourly'])
ret['per_day'] = ret['per_hour'] * 24
ret['per_week'] = ret['per_day'] * 7
ret['per_month'] = decimal.Decimal(sizes[profile['size']]['price_monthly'])
ret['per_year'] = ret['per_week'] * 52
if kwargs.get('raw', False):
ret['_raw'] = raw
return {profile['profile']: ret}
def list_floating_ips(call=None):
'''
Return a list of the floating ips that are on the provider
.. versionadded:: 2016.3.0
CLI Examples:
.. code-block:: bash
salt-cloud -f list_floating_ips my-digitalocean-config
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_floating_ips function must be called with '
'-f or --function, or with the --list-floating-ips option'
)
fetch = True
page = 1
ret = {}
while fetch:
items = query(method='floating_ips',
command='?page=' + six.text_type(page) + '&per_page=200')
for floating_ip in items['floating_ips']:
ret[floating_ip['ip']] = {}
for item in six.iterkeys(floating_ip):
ret[floating_ip['ip']][item] = floating_ip[item]
page += 1
try:
fetch = 'next' in items['links']['pages']
except KeyError:
fetch = False
return ret
def show_floating_ip(kwargs=None, call=None):
'''
Show the details of a floating IP
.. versionadded:: 2016.3.0
CLI Examples:
.. code-block:: bash
salt-cloud -f show_floating_ip my-digitalocean-config floating_ip='45.55.96.47'
'''
if call != 'function':
log.error(
'The show_floating_ip function must be called with -f or --function.'
)
return False
if not kwargs:
kwargs = {}
if 'floating_ip' not in kwargs:
log.error('A floating IP is required.')
return False
floating_ip = kwargs['floating_ip']
log.debug('Floating ip is %s', floating_ip)
details = query(method='floating_ips', command=floating_ip)
return details
def delete_floating_ip(kwargs=None, call=None):
'''
Delete a floating IP
.. versionadded:: 2016.3.0
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_floating_ip my-digitalocean-config floating_ip='45.55.96.47'
'''
if call != 'function':
log.error(
'The delete_floating_ip function must be called with -f or --function.'
)
return False
if not kwargs:
kwargs = {}
if 'floating_ip' not in kwargs:
log.error('A floating IP is required.')
return False
floating_ip = kwargs['floating_ip']
log.debug('Floating ip is %s', kwargs['floating_ip'])
result = query(method='floating_ips',
command=floating_ip,
http_method='delete')
return result
def assign_floating_ip(kwargs=None, call=None):
'''
Assign a floating IP
.. versionadded:: 2016.3.0
CLI Examples:
.. code-block:: bash
salt-cloud -f assign_floating_ip my-digitalocean-config droplet_id=1234567 floating_ip='45.55.96.47'
'''
if call != 'function':
log.error(
'The assign_floating_ip function must be called with -f or --function.'
)
return False
if not kwargs:
kwargs = {}
if 'floating_ip' and 'droplet_id' not in kwargs:
log.error('A floating IP and droplet_id is required.')
return False
result = query(method='floating_ips',
command=kwargs['floating_ip'] + '/actions',
args={'droplet_id': kwargs['droplet_id'], 'type': 'assign'},
http_method='post')
return result
def unassign_floating_ip(kwargs=None, call=None):
'''
Unassign a floating IP
.. versionadded:: 2016.3.0
CLI Examples:
.. code-block:: bash
salt-cloud -f unassign_floating_ip my-digitalocean-config floating_ip='45.55.96.47'
'''
if call != 'function':
log.error(
'The inassign_floating_ip function must be called with -f or --function.'
)
return False
if not kwargs:
kwargs = {}
if 'floating_ip' not in kwargs:
log.error('A floating IP is required.')
return False
result = query(method='floating_ips',
command=kwargs['floating_ip'] + '/actions',
args={'type': 'unassign'},
http_method='post')
return result
def _list_nodes(full=False, for_output=False):
'''
Helper function to format and parse node data.
'''
fetch = True
page = 1
ret = {}
while fetch:
items = query(method='droplets',
command='?page=' + six.text_type(page) + '&per_page=200')
for node in items['droplets']:
name = node['name']
ret[name] = {}
if full:
ret[name] = _get_full_output(node, for_output=for_output)
else:
public_ips, private_ips = _get_ips(node['networks'])
ret[name] = {
'id': node['id'],
'image': node['image']['name'],
'name': name,
'private_ips': private_ips,
'public_ips': public_ips,
'size': node['size_slug'],
'state': six.text_type(node['status']),
}
page += 1
try:
fetch = 'next' in items['links']['pages']
except KeyError:
fetch = False
return ret
def reboot(name, call=None):
'''
Reboot a droplet in DigitalOcean.
.. versionadded:: 2015.8.8
name
The name of the droplet to restart.
CLI Example:
.. code-block:: bash
salt-cloud -a reboot droplet_name
'''
if call != 'action':
raise SaltCloudSystemExit(
'The restart action must be called with -a or --action.'
)
data = show_instance(name, call='action')
if data.get('status') == 'off':
return {'success': True,
'action': 'stop',
'status': 'off',
'msg': 'Machine is already off.'}
ret = query(droplet_id=data['id'],
command='actions',
args={'type': 'reboot'},
http_method='post')
return {'success': True,
'action': ret['action']['type'],
'state': ret['action']['status']}
def start(name, call=None):
'''
Start a droplet in DigitalOcean.
.. versionadded:: 2015.8.8
name
The name of the droplet to start.
CLI Example:
.. code-block:: bash
salt-cloud -a start droplet_name
'''
if call != 'action':
raise SaltCloudSystemExit(
'The start action must be called with -a or --action.'
)
data = show_instance(name, call='action')
if data.get('status') == 'active':
return {'success': True,
'action': 'start',
'status': 'active',
'msg': 'Machine is already running.'}
ret = query(droplet_id=data['id'],
command='actions',
args={'type': 'power_on'},
http_method='post')
return {'success': True,
'action': ret['action']['type'],
'state': ret['action']['status']}
def stop(name, call=None):
'''
Stop a droplet in DigitalOcean.
.. versionadded:: 2015.8.8
name
The name of the droplet to stop.
CLI Example:
.. code-block:: bash
salt-cloud -a stop droplet_name
'''
if call != 'action':
raise SaltCloudSystemExit(
'The stop action must be called with -a or --action.'
)
data = show_instance(name, call='action')
if data.get('status') == 'off':
return {'success': True,
'action': 'stop',
'status': 'off',
'msg': 'Machine is already off.'}
ret = query(droplet_id=data['id'],
command='actions',
args={'type': 'shutdown'},
http_method='post')
return {'success': True,
'action': ret['action']['type'],
'state': ret['action']['status']}
def _get_full_output(node, for_output=False):
'''
Helper function for _list_nodes to loop through all node information.
Returns a dictionary containing the full information of a node.
'''
ret = {}
for item in six.iterkeys(node):
value = node[item]
if value is not None and for_output:
value = six.text_type(value)
ret[item] = value
return ret
def _get_ips(networks):
'''
Helper function for list_nodes. Returns public and private ip lists based on a
given network dictionary.
'''
v4s = networks.get('v4')
v6s = networks.get('v6')
public_ips = []
private_ips = []
if v4s:
for item in v4s:
ip_type = item.get('type')
ip_address = item.get('ip_address')
if ip_type == 'public':
public_ips.append(ip_address)
if ip_type == 'private':
private_ips.append(ip_address)
if v6s:
for item in v6s:
ip_type = item.get('type')
ip_address = item.get('ip_address')
if ip_type == 'public':
public_ips.append(ip_address)
if ip_type == 'private':
private_ips.append(ip_address)
return public_ips, private_ips
|
saltstack/salt
|
salt/cloud/clouds/digitalocean.py
|
delete_floating_ip
|
python
|
def delete_floating_ip(kwargs=None, call=None):
'''
Delete a floating IP
.. versionadded:: 2016.3.0
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_floating_ip my-digitalocean-config floating_ip='45.55.96.47'
'''
if call != 'function':
log.error(
'The delete_floating_ip function must be called with -f or --function.'
)
return False
if not kwargs:
kwargs = {}
if 'floating_ip' not in kwargs:
log.error('A floating IP is required.')
return False
floating_ip = kwargs['floating_ip']
log.debug('Floating ip is %s', kwargs['floating_ip'])
result = query(method='floating_ips',
command=floating_ip,
http_method='delete')
return result
|
Delete a floating IP
.. versionadded:: 2016.3.0
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_floating_ip my-digitalocean-config floating_ip='45.55.96.47'
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/digitalocean.py#L1093-L1125
|
[
"def query(method='droplets', droplet_id=None, command=None, args=None, http_method='get'):\n '''\n Make a web call to DigitalOcean\n '''\n base_path = six.text_type(config.get_cloud_config_value(\n 'api_root',\n get_configured_provider(),\n __opts__,\n search_global=False,\n default='https://api.digitalocean.com/v2'\n ))\n\n path = '{0}/{1}/'.format(base_path, method)\n\n if droplet_id:\n path += '{0}/'.format(droplet_id)\n\n if command:\n path += command\n\n if not isinstance(args, dict):\n args = {}\n\n personal_access_token = config.get_cloud_config_value(\n 'personal_access_token', get_configured_provider(), __opts__, search_global=False\n )\n\n data = salt.utils.json.dumps(args)\n\n requester = getattr(requests, http_method)\n request = requester(path, data=data, headers={'Authorization': 'Bearer ' + personal_access_token, 'Content-Type': 'application/json'})\n if request.status_code > 299:\n raise SaltCloudSystemExit(\n 'An error occurred while querying DigitalOcean. HTTP Code: {0} '\n 'Error: \\'{1}\\''.format(\n request.status_code,\n # request.read()\n request.text\n )\n )\n\n log.debug(request.url)\n\n # success without data\n if request.status_code == 204:\n return True\n\n content = request.text\n\n result = salt.utils.json.loads(content)\n if result.get('status', '').lower() == 'error':\n raise SaltCloudSystemExit(\n pprint.pformat(result.get('error_message', {}))\n )\n\n return result\n"
] |
# -*- coding: utf-8 -*-
'''
DigitalOcean Cloud Module
=========================
The DigitalOcean cloud module is used to control access to the DigitalOcean VPS system.
Use of this module requires a requires a ``personal_access_token``, an ``ssh_key_file``,
and at least one SSH key name in ``ssh_key_names``. More ``ssh_key_names`` can be added
by separating each key with a comma. The ``personal_access_token`` can be found in the
DigitalOcean web interface in the "Apps & API" section. The SSH key name can be found
under the "SSH Keys" section.
.. code-block:: yaml
# Note: This example is for /etc/salt/cloud.providers or any file in the
# /etc/salt/cloud.providers.d/ directory.
my-digital-ocean-config:
personal_access_token: xxx
ssh_key_file: /path/to/ssh/key/file
ssh_key_names: my-key-name,my-key-name-2
driver: digitalocean
:depends: requests
'''
# Import Python Libs
from __future__ import absolute_import, print_function, unicode_literals
import decimal
import logging
import os
import pprint
import time
# Import Salt Libs
import salt.utils.cloud
import salt.utils.files
import salt.utils.json
import salt.utils.stringutils
import salt.config as config
from salt.exceptions import (
SaltCloudConfigError,
SaltInvocationError,
SaltCloudNotFound,
SaltCloudSystemExit,
SaltCloudExecutionFailure,
SaltCloudExecutionTimeout
)
from salt.ext import six
from salt.ext.six.moves import zip
# Import Third Party Libs
try:
import requests
HAS_REQUESTS = True
except ImportError:
HAS_REQUESTS = False
# Get logging started
log = logging.getLogger(__name__)
__virtualname__ = 'digitalocean'
__virtual_aliases__ = ('digital_ocean', 'do')
# Only load in this module if the DIGITALOCEAN configurations are in place
def __virtual__():
'''
Check for DigitalOcean configurations
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
opts=__opts__,
provider=__active_provider_name__ or __virtualname__,
aliases=__virtual_aliases__,
required_keys=('personal_access_token',)
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'requests': HAS_REQUESTS}
)
def avail_locations(call=None):
'''
Return a dict of all available VM locations on the cloud provider with
relevant data
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
items = query(method='regions')
ret = {}
for region in items['regions']:
ret[region['name']] = {}
for item in six.iterkeys(region):
ret[region['name']][item] = six.text_type(region[item])
return ret
def avail_images(call=None):
'''
Return a list of the images that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
fetch = True
page = 1
ret = {}
while fetch:
items = query(method='images', command='?page=' + six.text_type(page) + '&per_page=200')
for image in items['images']:
ret[image['name']] = {}
for item in six.iterkeys(image):
ret[image['name']][item] = image[item]
page += 1
try:
fetch = 'next' in items['links']['pages']
except KeyError:
fetch = False
return ret
def avail_sizes(call=None):
'''
Return a list of the image sizes that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
items = query(method='sizes', command='?per_page=100')
ret = {}
for size in items['sizes']:
ret[size['slug']] = {}
for item in six.iterkeys(size):
ret[size['slug']][item] = six.text_type(size[item])
return ret
def list_nodes(call=None):
'''
Return a list of the VMs that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
return _list_nodes()
def list_nodes_full(call=None, for_output=True):
'''
Return a list of the VMs that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or --function.'
)
return _list_nodes(full=True, for_output=for_output)
def list_nodes_select(call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
return salt.utils.cloud.list_nodes_select(
list_nodes_full('function'), __opts__['query.selection'], call,
)
def get_image(vm_):
'''
Return the image object to use
'''
images = avail_images()
vm_image = config.get_cloud_config_value(
'image', vm_, __opts__, search_global=False
)
if not isinstance(vm_image, six.string_types):
vm_image = six.text_type(vm_image)
for image in images:
if vm_image in (images[image]['name'],
images[image]['slug'],
images[image]['id']):
if images[image]['slug'] is not None:
return images[image]['slug']
return int(images[image]['id'])
raise SaltCloudNotFound(
'The specified image, \'{0}\', could not be found.'.format(vm_image)
)
def get_size(vm_):
'''
Return the VM's size. Used by create_node().
'''
sizes = avail_sizes()
vm_size = six.text_type(config.get_cloud_config_value(
'size', vm_, __opts__, search_global=False
))
for size in sizes:
if vm_size.lower() == sizes[size]['slug']:
return sizes[size]['slug']
raise SaltCloudNotFound(
'The specified size, \'{0}\', could not be found.'.format(vm_size)
)
def get_location(vm_):
'''
Return the VM's location
'''
locations = avail_locations()
vm_location = six.text_type(config.get_cloud_config_value(
'location', vm_, __opts__, search_global=False
))
for location in locations:
if vm_location in (locations[location]['name'],
locations[location]['slug']):
return locations[location]['slug']
raise SaltCloudNotFound(
'The specified location, \'{0}\', could not be found.'.format(
vm_location
)
)
def create_node(args):
'''
Create a node
'''
node = query(method='droplets', args=args, http_method='post')
return node
def create(vm_):
'''
Create a single VM from a data dict
'''
try:
# Check for required profile parameters before sending any API calls.
if vm_['profile'] and config.is_profile_configured(__opts__,
__active_provider_name__ or 'digitalocean',
vm_['profile'],
vm_=vm_) is False:
return False
except AttributeError:
pass
__utils__['cloud.fire_event'](
'event',
'starting create',
'salt/cloud/{0}/creating'.format(vm_['name']),
args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Creating Cloud VM %s', vm_['name'])
kwargs = {
'name': vm_['name'],
'size': get_size(vm_),
'image': get_image(vm_),
'region': get_location(vm_),
'ssh_keys': [],
'tags': []
}
# backwards compat
ssh_key_name = config.get_cloud_config_value(
'ssh_key_name', vm_, __opts__, search_global=False
)
if ssh_key_name:
kwargs['ssh_keys'].append(get_keyid(ssh_key_name))
ssh_key_names = config.get_cloud_config_value(
'ssh_key_names', vm_, __opts__, search_global=False, default=False
)
if ssh_key_names:
for key in ssh_key_names.split(','):
kwargs['ssh_keys'].append(get_keyid(key))
key_filename = config.get_cloud_config_value(
'ssh_key_file', vm_, __opts__, search_global=False, default=None
)
if key_filename is not None and not os.path.isfile(key_filename):
raise SaltCloudConfigError(
'The defined key_filename \'{0}\' does not exist'.format(
key_filename
)
)
if not __opts__.get('ssh_agent', False) and key_filename is None:
raise SaltCloudConfigError(
'The DigitalOcean driver requires an ssh_key_file and an ssh_key_name '
'because it does not supply a root password upon building the server.'
)
ssh_interface = config.get_cloud_config_value(
'ssh_interface', vm_, __opts__, search_global=False, default='public'
)
if ssh_interface in ['private', 'public']:
log.info("ssh_interface: Setting interface for ssh to %s", ssh_interface)
kwargs['ssh_interface'] = ssh_interface
else:
raise SaltCloudConfigError(
"The DigitalOcean driver requires ssh_interface to be defined as 'public' or 'private'."
)
private_networking = config.get_cloud_config_value(
'private_networking', vm_, __opts__, search_global=False, default=None,
)
if private_networking is not None:
if not isinstance(private_networking, bool):
raise SaltCloudConfigError("'private_networking' should be a boolean value.")
kwargs['private_networking'] = private_networking
if not private_networking and ssh_interface == 'private':
raise SaltCloudConfigError(
"The DigitalOcean driver requires ssh_interface if defined as 'private' "
"then private_networking should be set as 'True'."
)
backups_enabled = config.get_cloud_config_value(
'backups_enabled', vm_, __opts__, search_global=False, default=None,
)
if backups_enabled is not None:
if not isinstance(backups_enabled, bool):
raise SaltCloudConfigError("'backups_enabled' should be a boolean value.")
kwargs['backups'] = backups_enabled
ipv6 = config.get_cloud_config_value(
'ipv6', vm_, __opts__, search_global=False, default=None,
)
if ipv6 is not None:
if not isinstance(ipv6, bool):
raise SaltCloudConfigError("'ipv6' should be a boolean value.")
kwargs['ipv6'] = ipv6
monitoring = config.get_cloud_config_value(
'monitoring', vm_, __opts__, search_global=False, default=None,
)
if monitoring is not None:
if not isinstance(monitoring, bool):
raise SaltCloudConfigError("'monitoring' should be a boolean value.")
kwargs['monitoring'] = monitoring
kwargs['tags'] = config.get_cloud_config_value(
'tags', vm_, __opts__, search_global=False, default=False
)
userdata_file = config.get_cloud_config_value(
'userdata_file', vm_, __opts__, search_global=False, default=None
)
if userdata_file is not None:
try:
with salt.utils.files.fopen(userdata_file, 'r') as fp_:
kwargs['user_data'] = salt.utils.cloud.userdata_template(
__opts__, vm_, salt.utils.stringutils.to_unicode(fp_.read())
)
except Exception as exc:
log.exception(
'Failed to read userdata from %s: %s', userdata_file, exc)
create_dns_record = config.get_cloud_config_value(
'create_dns_record', vm_, __opts__, search_global=False, default=None,
)
if create_dns_record:
log.info('create_dns_record: will attempt to write DNS records')
default_dns_domain = None
dns_domain_name = vm_['name'].split('.')
if len(dns_domain_name) > 2:
log.debug('create_dns_record: inferring default dns_hostname, dns_domain from minion name as FQDN')
default_dns_hostname = '.'.join(dns_domain_name[:-2])
default_dns_domain = '.'.join(dns_domain_name[-2:])
else:
log.debug("create_dns_record: can't infer dns_domain from %s", vm_['name'])
default_dns_hostname = dns_domain_name[0]
dns_hostname = config.get_cloud_config_value(
'dns_hostname', vm_, __opts__, search_global=False, default=default_dns_hostname,
)
dns_domain = config.get_cloud_config_value(
'dns_domain', vm_, __opts__, search_global=False, default=default_dns_domain,
)
if dns_hostname and dns_domain:
log.info('create_dns_record: using dns_hostname="%s", dns_domain="%s"', dns_hostname, dns_domain)
__add_dns_addr__ = lambda t, d: post_dns_record(dns_domain=dns_domain,
name=dns_hostname,
record_type=t,
record_data=d)
log.debug('create_dns_record: %s', __add_dns_addr__)
else:
log.error('create_dns_record: could not determine dns_hostname and/or dns_domain')
raise SaltCloudConfigError(
'\'create_dns_record\' must be a dict specifying "domain" '
'and "hostname" or the minion name must be an FQDN.'
)
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args=__utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
try:
ret = create_node(kwargs)
except Exception as exc:
log.error(
'Error creating %s on DIGITALOCEAN\n\n'
'The following exception was thrown when trying to '
'run the initial deployment: %s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
def __query_node_data(vm_name):
data = show_instance(vm_name, 'action')
if not data:
# Trigger an error in the wait_for_ip function
return False
if data['networks'].get('v4'):
for network in data['networks']['v4']:
if network['type'] == 'public':
return data
return False
try:
data = salt.utils.cloud.wait_for_ip(
__query_node_data,
update_args=(vm_['name'],),
timeout=config.get_cloud_config_value(
'wait_for_ip_timeout', vm_, __opts__, default=10 * 60),
interval=config.get_cloud_config_value(
'wait_for_ip_interval', vm_, __opts__, default=10),
)
except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc:
try:
# It might be already up, let's destroy it!
destroy(vm_['name'])
except SaltCloudSystemExit:
pass
finally:
raise SaltCloudSystemExit(six.text_type(exc))
if not vm_.get('ssh_host'):
vm_['ssh_host'] = None
# add DNS records, set ssh_host, default to first found IP, preferring IPv4 for ssh bootstrap script target
addr_families, dns_arec_types = (('v4', 'v6'), ('A', 'AAAA'))
arec_map = dict(list(zip(addr_families, dns_arec_types)))
for facing, addr_family, ip_address in [(net['type'], family, net['ip_address'])
for family in addr_families
for net in data['networks'][family]]:
log.info('found %s IP%s interface for "%s"', facing, addr_family, ip_address)
dns_rec_type = arec_map[addr_family]
if facing == 'public':
if create_dns_record:
__add_dns_addr__(dns_rec_type, ip_address)
if facing == ssh_interface:
if not vm_['ssh_host']:
vm_['ssh_host'] = ip_address
if vm_['ssh_host'] is None:
raise SaltCloudSystemExit(
'No suitable IP addresses found for ssh minion bootstrapping: {0}'.format(repr(data['networks']))
)
log.debug(
'Found public IP address to use for ssh minion bootstrapping: %s',
vm_['ssh_host']
)
vm_['key_filename'] = key_filename
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
ret.update(data)
log.info('Created Cloud VM \'%s\'', vm_['name'])
log.debug(
'\'%s\' VM creation details:\n%s',
vm_['name'], pprint.pformat(data)
)
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return ret
def query(method='droplets', droplet_id=None, command=None, args=None, http_method='get'):
'''
Make a web call to DigitalOcean
'''
base_path = six.text_type(config.get_cloud_config_value(
'api_root',
get_configured_provider(),
__opts__,
search_global=False,
default='https://api.digitalocean.com/v2'
))
path = '{0}/{1}/'.format(base_path, method)
if droplet_id:
path += '{0}/'.format(droplet_id)
if command:
path += command
if not isinstance(args, dict):
args = {}
personal_access_token = config.get_cloud_config_value(
'personal_access_token', get_configured_provider(), __opts__, search_global=False
)
data = salt.utils.json.dumps(args)
requester = getattr(requests, http_method)
request = requester(path, data=data, headers={'Authorization': 'Bearer ' + personal_access_token, 'Content-Type': 'application/json'})
if request.status_code > 299:
raise SaltCloudSystemExit(
'An error occurred while querying DigitalOcean. HTTP Code: {0} '
'Error: \'{1}\''.format(
request.status_code,
# request.read()
request.text
)
)
log.debug(request.url)
# success without data
if request.status_code == 204:
return True
content = request.text
result = salt.utils.json.loads(content)
if result.get('status', '').lower() == 'error':
raise SaltCloudSystemExit(
pprint.pformat(result.get('error_message', {}))
)
return result
def script(vm_):
'''
Return the script deployment object
'''
deploy_script = salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
return deploy_script
def show_instance(name, call=None):
'''
Show the details from DigitalOcean concerning a droplet
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
node = _get_node(name)
__utils__['cloud.cache_node'](node, __active_provider_name__, __opts__)
return node
def _get_node(name):
attempts = 10
while attempts >= 0:
try:
return list_nodes_full(for_output=False)[name]
except KeyError:
attempts -= 1
log.debug(
'Failed to get the data for node \'%s\'. Remaining '
'attempts: %s', name, attempts
)
# Just a little delay between attempts...
time.sleep(0.5)
return {}
def list_keypairs(call=None):
'''
Return a dict of all available VM locations on the cloud provider with
relevant data
'''
if call != 'function':
log.error(
'The list_keypairs function must be called with -f or --function.'
)
return False
fetch = True
page = 1
ret = {}
while fetch:
items = query(method='account/keys', command='?page=' + six.text_type(page) +
'&per_page=100')
for key_pair in items['ssh_keys']:
name = key_pair['name']
if name in ret:
raise SaltCloudSystemExit(
'A duplicate key pair name, \'{0}\', was found in DigitalOcean\'s '
'key pair list. Please change the key name stored by DigitalOcean. '
'Be sure to adjust the value of \'ssh_key_file\' in your cloud '
'profile or provider configuration, if necessary.'.format(
name
)
)
ret[name] = {}
for item in six.iterkeys(key_pair):
ret[name][item] = six.text_type(key_pair[item])
page += 1
try:
fetch = 'next' in items['links']['pages']
except KeyError:
fetch = False
return ret
def show_keypair(kwargs=None, call=None):
'''
Show the details of an SSH keypair
'''
if call != 'function':
log.error(
'The show_keypair function must be called with -f or --function.'
)
return False
if not kwargs:
kwargs = {}
if 'keyname' not in kwargs:
log.error('A keyname is required.')
return False
keypairs = list_keypairs(call='function')
keyid = keypairs[kwargs['keyname']]['id']
log.debug('Key ID is %s', keyid)
details = query(method='account/keys', command=keyid)
return details
def import_keypair(kwargs=None, call=None):
'''
Upload public key to cloud provider.
Similar to EC2 import_keypair.
.. versionadded:: 2016.11.0
kwargs
file(mandatory): public key file-name
keyname(mandatory): public key name in the provider
'''
with salt.utils.files.fopen(kwargs['file'], 'r') as public_key_filename:
public_key_content = salt.utils.stringutils.to_unicode(public_key_filename.read())
digitalocean_kwargs = {
'name': kwargs['keyname'],
'public_key': public_key_content
}
created_result = create_key(digitalocean_kwargs, call=call)
return created_result
def create_key(kwargs=None, call=None):
'''
Upload a public key
'''
if call != 'function':
log.error(
'The create_key function must be called with -f or --function.'
)
return False
try:
result = query(
method='account',
command='keys',
args={'name': kwargs['name'],
'public_key': kwargs['public_key']},
http_method='post'
)
except KeyError:
log.info('`name` and `public_key` arguments must be specified')
return False
return result
def remove_key(kwargs=None, call=None):
'''
Delete public key
'''
if call != 'function':
log.error(
'The create_key function must be called with -f or --function.'
)
return False
try:
result = query(
method='account',
command='keys/' + kwargs['id'],
http_method='delete'
)
except KeyError:
log.info('`id` argument must be specified')
return False
return result
def get_keyid(keyname):
'''
Return the ID of the keyname
'''
if not keyname:
return None
keypairs = list_keypairs(call='function')
keyid = keypairs[keyname]['id']
if keyid:
return keyid
raise SaltCloudNotFound('The specified ssh key could not be found.')
def destroy(name, call=None):
'''
Destroy a node. Will check termination protection and warn if enabled.
CLI Example:
.. code-block:: bash
salt-cloud --destroy mymachine
'''
if call == 'function':
raise SaltCloudSystemExit(
'The destroy action must be called with -d, --destroy, '
'-a or --action.'
)
__utils__['cloud.fire_event'](
'event',
'destroying instance',
'salt/cloud/{0}/destroying'.format(name),
args={'name': name},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
data = show_instance(name, call='action')
node = query(method='droplets', droplet_id=data['id'], http_method='delete')
## This is all terribly optomistic:
# vm_ = get_vm_config(name=name)
# delete_dns_record = config.get_cloud_config_value(
# 'delete_dns_record', vm_, __opts__, search_global=False, default=None,
# )
# TODO: when _vm config data can be made available, we should honor the configuration settings,
# but until then, we should assume stale DNS records are bad, and default behavior should be to
# delete them if we can. When this is resolved, also resolve the comments a couple of lines below.
delete_dns_record = True
if not isinstance(delete_dns_record, bool):
raise SaltCloudConfigError(
'\'delete_dns_record\' should be a boolean value.'
)
# When the "to do" a few lines up is resolved, remove these lines and use the if/else logic below.
log.debug('Deleting DNS records for %s.', name)
destroy_dns_records(name)
# Until the "to do" from line 754 is taken care of, we don't need this logic.
# if delete_dns_record:
# log.debug('Deleting DNS records for %s.', name)
# destroy_dns_records(name)
# else:
# log.debug('delete_dns_record : %s', delete_dns_record)
# for line in pprint.pformat(dir()).splitlines():
# log.debug('delete context: %s', line)
__utils__['cloud.fire_event'](
'event',
'destroyed instance',
'salt/cloud/{0}/destroyed'.format(name),
args={'name': name},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
if __opts__.get('update_cachedir', False) is True:
__utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__)
return node
def post_dns_record(**kwargs):
'''
Creates a DNS record for the given name if the domain is managed with DO.
'''
if 'kwargs' in kwargs: # flatten kwargs if called via salt-cloud -f
f_kwargs = kwargs['kwargs']
del kwargs['kwargs']
kwargs.update(f_kwargs)
mandatory_kwargs = ('dns_domain', 'name', 'record_type', 'record_data')
for i in mandatory_kwargs:
if kwargs[i]:
pass
else:
error = '{0}="{1}" ## all mandatory args must be provided: {2}'.format(i, kwargs[i], mandatory_kwargs)
raise SaltInvocationError(error)
domain = query(method='domains', droplet_id=kwargs['dns_domain'])
if domain:
result = query(
method='domains',
droplet_id=kwargs['dns_domain'],
command='records',
args={'type': kwargs['record_type'], 'name': kwargs['name'], 'data': kwargs['record_data']},
http_method='post'
)
return result
return False
def destroy_dns_records(fqdn):
'''
Deletes DNS records for the given hostname if the domain is managed with DO.
'''
domain = '.'.join(fqdn.split('.')[-2:])
hostname = '.'.join(fqdn.split('.')[:-2])
# TODO: remove this when the todo on 754 is available
try:
response = query(method='domains', droplet_id=domain, command='records')
except SaltCloudSystemExit:
log.debug('Failed to find domains.')
return False
log.debug("found DNS records: %s", pprint.pformat(response))
records = response['domain_records']
if records:
record_ids = [r['id'] for r in records if r['name'].decode() == hostname]
log.debug("deleting DNS record IDs: %s", record_ids)
for id_ in record_ids:
try:
log.info('deleting DNS record %s', id_)
ret = query(
method='domains',
droplet_id=domain,
command='records/{0}'.format(id_),
http_method='delete'
)
except SaltCloudSystemExit:
log.error('failed to delete DNS domain %s record ID %s.', domain, hostname)
log.debug('DNS deletion REST call returned: %s', pprint.pformat(ret))
return False
def show_pricing(kwargs=None, call=None):
'''
Show pricing for a particular profile. This is only an estimate, based on
unofficial pricing sources.
.. versionadded:: 2015.8.0
CLI Examples:
.. code-block:: bash
salt-cloud -f show_pricing my-digitalocean-config profile=my-profile
'''
profile = __opts__['profiles'].get(kwargs['profile'], {})
if not profile:
return {'Error': 'The requested profile was not found'}
# Make sure the profile belongs to DigitalOcean
provider = profile.get('provider', '0:0')
comps = provider.split(':')
if len(comps) < 2 or comps[1] != 'digitalocean':
return {'Error': 'The requested profile does not belong to DigitalOcean'}
raw = {}
ret = {}
sizes = avail_sizes()
ret['per_hour'] = decimal.Decimal(sizes[profile['size']]['price_hourly'])
ret['per_day'] = ret['per_hour'] * 24
ret['per_week'] = ret['per_day'] * 7
ret['per_month'] = decimal.Decimal(sizes[profile['size']]['price_monthly'])
ret['per_year'] = ret['per_week'] * 52
if kwargs.get('raw', False):
ret['_raw'] = raw
return {profile['profile']: ret}
def list_floating_ips(call=None):
'''
Return a list of the floating ips that are on the provider
.. versionadded:: 2016.3.0
CLI Examples:
.. code-block:: bash
salt-cloud -f list_floating_ips my-digitalocean-config
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_floating_ips function must be called with '
'-f or --function, or with the --list-floating-ips option'
)
fetch = True
page = 1
ret = {}
while fetch:
items = query(method='floating_ips',
command='?page=' + six.text_type(page) + '&per_page=200')
for floating_ip in items['floating_ips']:
ret[floating_ip['ip']] = {}
for item in six.iterkeys(floating_ip):
ret[floating_ip['ip']][item] = floating_ip[item]
page += 1
try:
fetch = 'next' in items['links']['pages']
except KeyError:
fetch = False
return ret
def show_floating_ip(kwargs=None, call=None):
'''
Show the details of a floating IP
.. versionadded:: 2016.3.0
CLI Examples:
.. code-block:: bash
salt-cloud -f show_floating_ip my-digitalocean-config floating_ip='45.55.96.47'
'''
if call != 'function':
log.error(
'The show_floating_ip function must be called with -f or --function.'
)
return False
if not kwargs:
kwargs = {}
if 'floating_ip' not in kwargs:
log.error('A floating IP is required.')
return False
floating_ip = kwargs['floating_ip']
log.debug('Floating ip is %s', floating_ip)
details = query(method='floating_ips', command=floating_ip)
return details
def create_floating_ip(kwargs=None, call=None):
'''
Create a new floating IP
.. versionadded:: 2016.3.0
CLI Examples:
.. code-block:: bash
salt-cloud -f create_floating_ip my-digitalocean-config region='NYC2'
salt-cloud -f create_floating_ip my-digitalocean-config droplet_id='1234567'
'''
if call != 'function':
log.error(
'The create_floating_ip function must be called with -f or --function.'
)
return False
if not kwargs:
kwargs = {}
if 'droplet_id' in kwargs:
result = query(method='floating_ips',
args={'droplet_id': kwargs['droplet_id']},
http_method='post')
return result
elif 'region' in kwargs:
result = query(method='floating_ips',
args={'region': kwargs['region']},
http_method='post')
return result
else:
log.error('A droplet_id or region is required.')
return False
def assign_floating_ip(kwargs=None, call=None):
'''
Assign a floating IP
.. versionadded:: 2016.3.0
CLI Examples:
.. code-block:: bash
salt-cloud -f assign_floating_ip my-digitalocean-config droplet_id=1234567 floating_ip='45.55.96.47'
'''
if call != 'function':
log.error(
'The assign_floating_ip function must be called with -f or --function.'
)
return False
if not kwargs:
kwargs = {}
if 'floating_ip' and 'droplet_id' not in kwargs:
log.error('A floating IP and droplet_id is required.')
return False
result = query(method='floating_ips',
command=kwargs['floating_ip'] + '/actions',
args={'droplet_id': kwargs['droplet_id'], 'type': 'assign'},
http_method='post')
return result
def unassign_floating_ip(kwargs=None, call=None):
'''
Unassign a floating IP
.. versionadded:: 2016.3.0
CLI Examples:
.. code-block:: bash
salt-cloud -f unassign_floating_ip my-digitalocean-config floating_ip='45.55.96.47'
'''
if call != 'function':
log.error(
'The inassign_floating_ip function must be called with -f or --function.'
)
return False
if not kwargs:
kwargs = {}
if 'floating_ip' not in kwargs:
log.error('A floating IP is required.')
return False
result = query(method='floating_ips',
command=kwargs['floating_ip'] + '/actions',
args={'type': 'unassign'},
http_method='post')
return result
def _list_nodes(full=False, for_output=False):
'''
Helper function to format and parse node data.
'''
fetch = True
page = 1
ret = {}
while fetch:
items = query(method='droplets',
command='?page=' + six.text_type(page) + '&per_page=200')
for node in items['droplets']:
name = node['name']
ret[name] = {}
if full:
ret[name] = _get_full_output(node, for_output=for_output)
else:
public_ips, private_ips = _get_ips(node['networks'])
ret[name] = {
'id': node['id'],
'image': node['image']['name'],
'name': name,
'private_ips': private_ips,
'public_ips': public_ips,
'size': node['size_slug'],
'state': six.text_type(node['status']),
}
page += 1
try:
fetch = 'next' in items['links']['pages']
except KeyError:
fetch = False
return ret
def reboot(name, call=None):
'''
Reboot a droplet in DigitalOcean.
.. versionadded:: 2015.8.8
name
The name of the droplet to restart.
CLI Example:
.. code-block:: bash
salt-cloud -a reboot droplet_name
'''
if call != 'action':
raise SaltCloudSystemExit(
'The restart action must be called with -a or --action.'
)
data = show_instance(name, call='action')
if data.get('status') == 'off':
return {'success': True,
'action': 'stop',
'status': 'off',
'msg': 'Machine is already off.'}
ret = query(droplet_id=data['id'],
command='actions',
args={'type': 'reboot'},
http_method='post')
return {'success': True,
'action': ret['action']['type'],
'state': ret['action']['status']}
def start(name, call=None):
'''
Start a droplet in DigitalOcean.
.. versionadded:: 2015.8.8
name
The name of the droplet to start.
CLI Example:
.. code-block:: bash
salt-cloud -a start droplet_name
'''
if call != 'action':
raise SaltCloudSystemExit(
'The start action must be called with -a or --action.'
)
data = show_instance(name, call='action')
if data.get('status') == 'active':
return {'success': True,
'action': 'start',
'status': 'active',
'msg': 'Machine is already running.'}
ret = query(droplet_id=data['id'],
command='actions',
args={'type': 'power_on'},
http_method='post')
return {'success': True,
'action': ret['action']['type'],
'state': ret['action']['status']}
def stop(name, call=None):
'''
Stop a droplet in DigitalOcean.
.. versionadded:: 2015.8.8
name
The name of the droplet to stop.
CLI Example:
.. code-block:: bash
salt-cloud -a stop droplet_name
'''
if call != 'action':
raise SaltCloudSystemExit(
'The stop action must be called with -a or --action.'
)
data = show_instance(name, call='action')
if data.get('status') == 'off':
return {'success': True,
'action': 'stop',
'status': 'off',
'msg': 'Machine is already off.'}
ret = query(droplet_id=data['id'],
command='actions',
args={'type': 'shutdown'},
http_method='post')
return {'success': True,
'action': ret['action']['type'],
'state': ret['action']['status']}
def _get_full_output(node, for_output=False):
'''
Helper function for _list_nodes to loop through all node information.
Returns a dictionary containing the full information of a node.
'''
ret = {}
for item in six.iterkeys(node):
value = node[item]
if value is not None and for_output:
value = six.text_type(value)
ret[item] = value
return ret
def _get_ips(networks):
'''
Helper function for list_nodes. Returns public and private ip lists based on a
given network dictionary.
'''
v4s = networks.get('v4')
v6s = networks.get('v6')
public_ips = []
private_ips = []
if v4s:
for item in v4s:
ip_type = item.get('type')
ip_address = item.get('ip_address')
if ip_type == 'public':
public_ips.append(ip_address)
if ip_type == 'private':
private_ips.append(ip_address)
if v6s:
for item in v6s:
ip_type = item.get('type')
ip_address = item.get('ip_address')
if ip_type == 'public':
public_ips.append(ip_address)
if ip_type == 'private':
private_ips.append(ip_address)
return public_ips, private_ips
|
saltstack/salt
|
salt/cloud/clouds/digitalocean.py
|
unassign_floating_ip
|
python
|
def unassign_floating_ip(kwargs=None, call=None):
'''
Unassign a floating IP
.. versionadded:: 2016.3.0
CLI Examples:
.. code-block:: bash
salt-cloud -f unassign_floating_ip my-digitalocean-config floating_ip='45.55.96.47'
'''
if call != 'function':
log.error(
'The inassign_floating_ip function must be called with -f or --function.'
)
return False
if not kwargs:
kwargs = {}
if 'floating_ip' not in kwargs:
log.error('A floating IP is required.')
return False
result = query(method='floating_ips',
command=kwargs['floating_ip'] + '/actions',
args={'type': 'unassign'},
http_method='post')
return result
|
Unassign a floating IP
.. versionadded:: 2016.3.0
CLI Examples:
.. code-block:: bash
salt-cloud -f unassign_floating_ip my-digitalocean-config floating_ip='45.55.96.47'
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/digitalocean.py#L1161-L1191
|
[
"def query(method='droplets', droplet_id=None, command=None, args=None, http_method='get'):\n '''\n Make a web call to DigitalOcean\n '''\n base_path = six.text_type(config.get_cloud_config_value(\n 'api_root',\n get_configured_provider(),\n __opts__,\n search_global=False,\n default='https://api.digitalocean.com/v2'\n ))\n\n path = '{0}/{1}/'.format(base_path, method)\n\n if droplet_id:\n path += '{0}/'.format(droplet_id)\n\n if command:\n path += command\n\n if not isinstance(args, dict):\n args = {}\n\n personal_access_token = config.get_cloud_config_value(\n 'personal_access_token', get_configured_provider(), __opts__, search_global=False\n )\n\n data = salt.utils.json.dumps(args)\n\n requester = getattr(requests, http_method)\n request = requester(path, data=data, headers={'Authorization': 'Bearer ' + personal_access_token, 'Content-Type': 'application/json'})\n if request.status_code > 299:\n raise SaltCloudSystemExit(\n 'An error occurred while querying DigitalOcean. HTTP Code: {0} '\n 'Error: \\'{1}\\''.format(\n request.status_code,\n # request.read()\n request.text\n )\n )\n\n log.debug(request.url)\n\n # success without data\n if request.status_code == 204:\n return True\n\n content = request.text\n\n result = salt.utils.json.loads(content)\n if result.get('status', '').lower() == 'error':\n raise SaltCloudSystemExit(\n pprint.pformat(result.get('error_message', {}))\n )\n\n return result\n"
] |
# -*- coding: utf-8 -*-
'''
DigitalOcean Cloud Module
=========================
The DigitalOcean cloud module is used to control access to the DigitalOcean VPS system.
Use of this module requires a requires a ``personal_access_token``, an ``ssh_key_file``,
and at least one SSH key name in ``ssh_key_names``. More ``ssh_key_names`` can be added
by separating each key with a comma. The ``personal_access_token`` can be found in the
DigitalOcean web interface in the "Apps & API" section. The SSH key name can be found
under the "SSH Keys" section.
.. code-block:: yaml
# Note: This example is for /etc/salt/cloud.providers or any file in the
# /etc/salt/cloud.providers.d/ directory.
my-digital-ocean-config:
personal_access_token: xxx
ssh_key_file: /path/to/ssh/key/file
ssh_key_names: my-key-name,my-key-name-2
driver: digitalocean
:depends: requests
'''
# Import Python Libs
from __future__ import absolute_import, print_function, unicode_literals
import decimal
import logging
import os
import pprint
import time
# Import Salt Libs
import salt.utils.cloud
import salt.utils.files
import salt.utils.json
import salt.utils.stringutils
import salt.config as config
from salt.exceptions import (
SaltCloudConfigError,
SaltInvocationError,
SaltCloudNotFound,
SaltCloudSystemExit,
SaltCloudExecutionFailure,
SaltCloudExecutionTimeout
)
from salt.ext import six
from salt.ext.six.moves import zip
# Import Third Party Libs
try:
import requests
HAS_REQUESTS = True
except ImportError:
HAS_REQUESTS = False
# Get logging started
log = logging.getLogger(__name__)
__virtualname__ = 'digitalocean'
__virtual_aliases__ = ('digital_ocean', 'do')
# Only load in this module if the DIGITALOCEAN configurations are in place
def __virtual__():
'''
Check for DigitalOcean configurations
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
opts=__opts__,
provider=__active_provider_name__ or __virtualname__,
aliases=__virtual_aliases__,
required_keys=('personal_access_token',)
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'requests': HAS_REQUESTS}
)
def avail_locations(call=None):
'''
Return a dict of all available VM locations on the cloud provider with
relevant data
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
items = query(method='regions')
ret = {}
for region in items['regions']:
ret[region['name']] = {}
for item in six.iterkeys(region):
ret[region['name']][item] = six.text_type(region[item])
return ret
def avail_images(call=None):
'''
Return a list of the images that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
fetch = True
page = 1
ret = {}
while fetch:
items = query(method='images', command='?page=' + six.text_type(page) + '&per_page=200')
for image in items['images']:
ret[image['name']] = {}
for item in six.iterkeys(image):
ret[image['name']][item] = image[item]
page += 1
try:
fetch = 'next' in items['links']['pages']
except KeyError:
fetch = False
return ret
def avail_sizes(call=None):
'''
Return a list of the image sizes that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
items = query(method='sizes', command='?per_page=100')
ret = {}
for size in items['sizes']:
ret[size['slug']] = {}
for item in six.iterkeys(size):
ret[size['slug']][item] = six.text_type(size[item])
return ret
def list_nodes(call=None):
'''
Return a list of the VMs that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
return _list_nodes()
def list_nodes_full(call=None, for_output=True):
'''
Return a list of the VMs that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or --function.'
)
return _list_nodes(full=True, for_output=for_output)
def list_nodes_select(call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
return salt.utils.cloud.list_nodes_select(
list_nodes_full('function'), __opts__['query.selection'], call,
)
def get_image(vm_):
'''
Return the image object to use
'''
images = avail_images()
vm_image = config.get_cloud_config_value(
'image', vm_, __opts__, search_global=False
)
if not isinstance(vm_image, six.string_types):
vm_image = six.text_type(vm_image)
for image in images:
if vm_image in (images[image]['name'],
images[image]['slug'],
images[image]['id']):
if images[image]['slug'] is not None:
return images[image]['slug']
return int(images[image]['id'])
raise SaltCloudNotFound(
'The specified image, \'{0}\', could not be found.'.format(vm_image)
)
def get_size(vm_):
'''
Return the VM's size. Used by create_node().
'''
sizes = avail_sizes()
vm_size = six.text_type(config.get_cloud_config_value(
'size', vm_, __opts__, search_global=False
))
for size in sizes:
if vm_size.lower() == sizes[size]['slug']:
return sizes[size]['slug']
raise SaltCloudNotFound(
'The specified size, \'{0}\', could not be found.'.format(vm_size)
)
def get_location(vm_):
'''
Return the VM's location
'''
locations = avail_locations()
vm_location = six.text_type(config.get_cloud_config_value(
'location', vm_, __opts__, search_global=False
))
for location in locations:
if vm_location in (locations[location]['name'],
locations[location]['slug']):
return locations[location]['slug']
raise SaltCloudNotFound(
'The specified location, \'{0}\', could not be found.'.format(
vm_location
)
)
def create_node(args):
'''
Create a node
'''
node = query(method='droplets', args=args, http_method='post')
return node
def create(vm_):
'''
Create a single VM from a data dict
'''
try:
# Check for required profile parameters before sending any API calls.
if vm_['profile'] and config.is_profile_configured(__opts__,
__active_provider_name__ or 'digitalocean',
vm_['profile'],
vm_=vm_) is False:
return False
except AttributeError:
pass
__utils__['cloud.fire_event'](
'event',
'starting create',
'salt/cloud/{0}/creating'.format(vm_['name']),
args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Creating Cloud VM %s', vm_['name'])
kwargs = {
'name': vm_['name'],
'size': get_size(vm_),
'image': get_image(vm_),
'region': get_location(vm_),
'ssh_keys': [],
'tags': []
}
# backwards compat
ssh_key_name = config.get_cloud_config_value(
'ssh_key_name', vm_, __opts__, search_global=False
)
if ssh_key_name:
kwargs['ssh_keys'].append(get_keyid(ssh_key_name))
ssh_key_names = config.get_cloud_config_value(
'ssh_key_names', vm_, __opts__, search_global=False, default=False
)
if ssh_key_names:
for key in ssh_key_names.split(','):
kwargs['ssh_keys'].append(get_keyid(key))
key_filename = config.get_cloud_config_value(
'ssh_key_file', vm_, __opts__, search_global=False, default=None
)
if key_filename is not None and not os.path.isfile(key_filename):
raise SaltCloudConfigError(
'The defined key_filename \'{0}\' does not exist'.format(
key_filename
)
)
if not __opts__.get('ssh_agent', False) and key_filename is None:
raise SaltCloudConfigError(
'The DigitalOcean driver requires an ssh_key_file and an ssh_key_name '
'because it does not supply a root password upon building the server.'
)
ssh_interface = config.get_cloud_config_value(
'ssh_interface', vm_, __opts__, search_global=False, default='public'
)
if ssh_interface in ['private', 'public']:
log.info("ssh_interface: Setting interface for ssh to %s", ssh_interface)
kwargs['ssh_interface'] = ssh_interface
else:
raise SaltCloudConfigError(
"The DigitalOcean driver requires ssh_interface to be defined as 'public' or 'private'."
)
private_networking = config.get_cloud_config_value(
'private_networking', vm_, __opts__, search_global=False, default=None,
)
if private_networking is not None:
if not isinstance(private_networking, bool):
raise SaltCloudConfigError("'private_networking' should be a boolean value.")
kwargs['private_networking'] = private_networking
if not private_networking and ssh_interface == 'private':
raise SaltCloudConfigError(
"The DigitalOcean driver requires ssh_interface if defined as 'private' "
"then private_networking should be set as 'True'."
)
backups_enabled = config.get_cloud_config_value(
'backups_enabled', vm_, __opts__, search_global=False, default=None,
)
if backups_enabled is not None:
if not isinstance(backups_enabled, bool):
raise SaltCloudConfigError("'backups_enabled' should be a boolean value.")
kwargs['backups'] = backups_enabled
ipv6 = config.get_cloud_config_value(
'ipv6', vm_, __opts__, search_global=False, default=None,
)
if ipv6 is not None:
if not isinstance(ipv6, bool):
raise SaltCloudConfigError("'ipv6' should be a boolean value.")
kwargs['ipv6'] = ipv6
monitoring = config.get_cloud_config_value(
'monitoring', vm_, __opts__, search_global=False, default=None,
)
if monitoring is not None:
if not isinstance(monitoring, bool):
raise SaltCloudConfigError("'monitoring' should be a boolean value.")
kwargs['monitoring'] = monitoring
kwargs['tags'] = config.get_cloud_config_value(
'tags', vm_, __opts__, search_global=False, default=False
)
userdata_file = config.get_cloud_config_value(
'userdata_file', vm_, __opts__, search_global=False, default=None
)
if userdata_file is not None:
try:
with salt.utils.files.fopen(userdata_file, 'r') as fp_:
kwargs['user_data'] = salt.utils.cloud.userdata_template(
__opts__, vm_, salt.utils.stringutils.to_unicode(fp_.read())
)
except Exception as exc:
log.exception(
'Failed to read userdata from %s: %s', userdata_file, exc)
create_dns_record = config.get_cloud_config_value(
'create_dns_record', vm_, __opts__, search_global=False, default=None,
)
if create_dns_record:
log.info('create_dns_record: will attempt to write DNS records')
default_dns_domain = None
dns_domain_name = vm_['name'].split('.')
if len(dns_domain_name) > 2:
log.debug('create_dns_record: inferring default dns_hostname, dns_domain from minion name as FQDN')
default_dns_hostname = '.'.join(dns_domain_name[:-2])
default_dns_domain = '.'.join(dns_domain_name[-2:])
else:
log.debug("create_dns_record: can't infer dns_domain from %s", vm_['name'])
default_dns_hostname = dns_domain_name[0]
dns_hostname = config.get_cloud_config_value(
'dns_hostname', vm_, __opts__, search_global=False, default=default_dns_hostname,
)
dns_domain = config.get_cloud_config_value(
'dns_domain', vm_, __opts__, search_global=False, default=default_dns_domain,
)
if dns_hostname and dns_domain:
log.info('create_dns_record: using dns_hostname="%s", dns_domain="%s"', dns_hostname, dns_domain)
__add_dns_addr__ = lambda t, d: post_dns_record(dns_domain=dns_domain,
name=dns_hostname,
record_type=t,
record_data=d)
log.debug('create_dns_record: %s', __add_dns_addr__)
else:
log.error('create_dns_record: could not determine dns_hostname and/or dns_domain')
raise SaltCloudConfigError(
'\'create_dns_record\' must be a dict specifying "domain" '
'and "hostname" or the minion name must be an FQDN.'
)
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args=__utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
try:
ret = create_node(kwargs)
except Exception as exc:
log.error(
'Error creating %s on DIGITALOCEAN\n\n'
'The following exception was thrown when trying to '
'run the initial deployment: %s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
def __query_node_data(vm_name):
data = show_instance(vm_name, 'action')
if not data:
# Trigger an error in the wait_for_ip function
return False
if data['networks'].get('v4'):
for network in data['networks']['v4']:
if network['type'] == 'public':
return data
return False
try:
data = salt.utils.cloud.wait_for_ip(
__query_node_data,
update_args=(vm_['name'],),
timeout=config.get_cloud_config_value(
'wait_for_ip_timeout', vm_, __opts__, default=10 * 60),
interval=config.get_cloud_config_value(
'wait_for_ip_interval', vm_, __opts__, default=10),
)
except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc:
try:
# It might be already up, let's destroy it!
destroy(vm_['name'])
except SaltCloudSystemExit:
pass
finally:
raise SaltCloudSystemExit(six.text_type(exc))
if not vm_.get('ssh_host'):
vm_['ssh_host'] = None
# add DNS records, set ssh_host, default to first found IP, preferring IPv4 for ssh bootstrap script target
addr_families, dns_arec_types = (('v4', 'v6'), ('A', 'AAAA'))
arec_map = dict(list(zip(addr_families, dns_arec_types)))
for facing, addr_family, ip_address in [(net['type'], family, net['ip_address'])
for family in addr_families
for net in data['networks'][family]]:
log.info('found %s IP%s interface for "%s"', facing, addr_family, ip_address)
dns_rec_type = arec_map[addr_family]
if facing == 'public':
if create_dns_record:
__add_dns_addr__(dns_rec_type, ip_address)
if facing == ssh_interface:
if not vm_['ssh_host']:
vm_['ssh_host'] = ip_address
if vm_['ssh_host'] is None:
raise SaltCloudSystemExit(
'No suitable IP addresses found for ssh minion bootstrapping: {0}'.format(repr(data['networks']))
)
log.debug(
'Found public IP address to use for ssh minion bootstrapping: %s',
vm_['ssh_host']
)
vm_['key_filename'] = key_filename
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
ret.update(data)
log.info('Created Cloud VM \'%s\'', vm_['name'])
log.debug(
'\'%s\' VM creation details:\n%s',
vm_['name'], pprint.pformat(data)
)
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return ret
def query(method='droplets', droplet_id=None, command=None, args=None, http_method='get'):
'''
Make a web call to DigitalOcean
'''
base_path = six.text_type(config.get_cloud_config_value(
'api_root',
get_configured_provider(),
__opts__,
search_global=False,
default='https://api.digitalocean.com/v2'
))
path = '{0}/{1}/'.format(base_path, method)
if droplet_id:
path += '{0}/'.format(droplet_id)
if command:
path += command
if not isinstance(args, dict):
args = {}
personal_access_token = config.get_cloud_config_value(
'personal_access_token', get_configured_provider(), __opts__, search_global=False
)
data = salt.utils.json.dumps(args)
requester = getattr(requests, http_method)
request = requester(path, data=data, headers={'Authorization': 'Bearer ' + personal_access_token, 'Content-Type': 'application/json'})
if request.status_code > 299:
raise SaltCloudSystemExit(
'An error occurred while querying DigitalOcean. HTTP Code: {0} '
'Error: \'{1}\''.format(
request.status_code,
# request.read()
request.text
)
)
log.debug(request.url)
# success without data
if request.status_code == 204:
return True
content = request.text
result = salt.utils.json.loads(content)
if result.get('status', '').lower() == 'error':
raise SaltCloudSystemExit(
pprint.pformat(result.get('error_message', {}))
)
return result
def script(vm_):
'''
Return the script deployment object
'''
deploy_script = salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
return deploy_script
def show_instance(name, call=None):
'''
Show the details from DigitalOcean concerning a droplet
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
node = _get_node(name)
__utils__['cloud.cache_node'](node, __active_provider_name__, __opts__)
return node
def _get_node(name):
attempts = 10
while attempts >= 0:
try:
return list_nodes_full(for_output=False)[name]
except KeyError:
attempts -= 1
log.debug(
'Failed to get the data for node \'%s\'. Remaining '
'attempts: %s', name, attempts
)
# Just a little delay between attempts...
time.sleep(0.5)
return {}
def list_keypairs(call=None):
'''
Return a dict of all available VM locations on the cloud provider with
relevant data
'''
if call != 'function':
log.error(
'The list_keypairs function must be called with -f or --function.'
)
return False
fetch = True
page = 1
ret = {}
while fetch:
items = query(method='account/keys', command='?page=' + six.text_type(page) +
'&per_page=100')
for key_pair in items['ssh_keys']:
name = key_pair['name']
if name in ret:
raise SaltCloudSystemExit(
'A duplicate key pair name, \'{0}\', was found in DigitalOcean\'s '
'key pair list. Please change the key name stored by DigitalOcean. '
'Be sure to adjust the value of \'ssh_key_file\' in your cloud '
'profile or provider configuration, if necessary.'.format(
name
)
)
ret[name] = {}
for item in six.iterkeys(key_pair):
ret[name][item] = six.text_type(key_pair[item])
page += 1
try:
fetch = 'next' in items['links']['pages']
except KeyError:
fetch = False
return ret
def show_keypair(kwargs=None, call=None):
'''
Show the details of an SSH keypair
'''
if call != 'function':
log.error(
'The show_keypair function must be called with -f or --function.'
)
return False
if not kwargs:
kwargs = {}
if 'keyname' not in kwargs:
log.error('A keyname is required.')
return False
keypairs = list_keypairs(call='function')
keyid = keypairs[kwargs['keyname']]['id']
log.debug('Key ID is %s', keyid)
details = query(method='account/keys', command=keyid)
return details
def import_keypair(kwargs=None, call=None):
'''
Upload public key to cloud provider.
Similar to EC2 import_keypair.
.. versionadded:: 2016.11.0
kwargs
file(mandatory): public key file-name
keyname(mandatory): public key name in the provider
'''
with salt.utils.files.fopen(kwargs['file'], 'r') as public_key_filename:
public_key_content = salt.utils.stringutils.to_unicode(public_key_filename.read())
digitalocean_kwargs = {
'name': kwargs['keyname'],
'public_key': public_key_content
}
created_result = create_key(digitalocean_kwargs, call=call)
return created_result
def create_key(kwargs=None, call=None):
'''
Upload a public key
'''
if call != 'function':
log.error(
'The create_key function must be called with -f or --function.'
)
return False
try:
result = query(
method='account',
command='keys',
args={'name': kwargs['name'],
'public_key': kwargs['public_key']},
http_method='post'
)
except KeyError:
log.info('`name` and `public_key` arguments must be specified')
return False
return result
def remove_key(kwargs=None, call=None):
'''
Delete public key
'''
if call != 'function':
log.error(
'The create_key function must be called with -f or --function.'
)
return False
try:
result = query(
method='account',
command='keys/' + kwargs['id'],
http_method='delete'
)
except KeyError:
log.info('`id` argument must be specified')
return False
return result
def get_keyid(keyname):
'''
Return the ID of the keyname
'''
if not keyname:
return None
keypairs = list_keypairs(call='function')
keyid = keypairs[keyname]['id']
if keyid:
return keyid
raise SaltCloudNotFound('The specified ssh key could not be found.')
def destroy(name, call=None):
'''
Destroy a node. Will check termination protection and warn if enabled.
CLI Example:
.. code-block:: bash
salt-cloud --destroy mymachine
'''
if call == 'function':
raise SaltCloudSystemExit(
'The destroy action must be called with -d, --destroy, '
'-a or --action.'
)
__utils__['cloud.fire_event'](
'event',
'destroying instance',
'salt/cloud/{0}/destroying'.format(name),
args={'name': name},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
data = show_instance(name, call='action')
node = query(method='droplets', droplet_id=data['id'], http_method='delete')
## This is all terribly optomistic:
# vm_ = get_vm_config(name=name)
# delete_dns_record = config.get_cloud_config_value(
# 'delete_dns_record', vm_, __opts__, search_global=False, default=None,
# )
# TODO: when _vm config data can be made available, we should honor the configuration settings,
# but until then, we should assume stale DNS records are bad, and default behavior should be to
# delete them if we can. When this is resolved, also resolve the comments a couple of lines below.
delete_dns_record = True
if not isinstance(delete_dns_record, bool):
raise SaltCloudConfigError(
'\'delete_dns_record\' should be a boolean value.'
)
# When the "to do" a few lines up is resolved, remove these lines and use the if/else logic below.
log.debug('Deleting DNS records for %s.', name)
destroy_dns_records(name)
# Until the "to do" from line 754 is taken care of, we don't need this logic.
# if delete_dns_record:
# log.debug('Deleting DNS records for %s.', name)
# destroy_dns_records(name)
# else:
# log.debug('delete_dns_record : %s', delete_dns_record)
# for line in pprint.pformat(dir()).splitlines():
# log.debug('delete context: %s', line)
__utils__['cloud.fire_event'](
'event',
'destroyed instance',
'salt/cloud/{0}/destroyed'.format(name),
args={'name': name},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
if __opts__.get('update_cachedir', False) is True:
__utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__)
return node
def post_dns_record(**kwargs):
'''
Creates a DNS record for the given name if the domain is managed with DO.
'''
if 'kwargs' in kwargs: # flatten kwargs if called via salt-cloud -f
f_kwargs = kwargs['kwargs']
del kwargs['kwargs']
kwargs.update(f_kwargs)
mandatory_kwargs = ('dns_domain', 'name', 'record_type', 'record_data')
for i in mandatory_kwargs:
if kwargs[i]:
pass
else:
error = '{0}="{1}" ## all mandatory args must be provided: {2}'.format(i, kwargs[i], mandatory_kwargs)
raise SaltInvocationError(error)
domain = query(method='domains', droplet_id=kwargs['dns_domain'])
if domain:
result = query(
method='domains',
droplet_id=kwargs['dns_domain'],
command='records',
args={'type': kwargs['record_type'], 'name': kwargs['name'], 'data': kwargs['record_data']},
http_method='post'
)
return result
return False
def destroy_dns_records(fqdn):
'''
Deletes DNS records for the given hostname if the domain is managed with DO.
'''
domain = '.'.join(fqdn.split('.')[-2:])
hostname = '.'.join(fqdn.split('.')[:-2])
# TODO: remove this when the todo on 754 is available
try:
response = query(method='domains', droplet_id=domain, command='records')
except SaltCloudSystemExit:
log.debug('Failed to find domains.')
return False
log.debug("found DNS records: %s", pprint.pformat(response))
records = response['domain_records']
if records:
record_ids = [r['id'] for r in records if r['name'].decode() == hostname]
log.debug("deleting DNS record IDs: %s", record_ids)
for id_ in record_ids:
try:
log.info('deleting DNS record %s', id_)
ret = query(
method='domains',
droplet_id=domain,
command='records/{0}'.format(id_),
http_method='delete'
)
except SaltCloudSystemExit:
log.error('failed to delete DNS domain %s record ID %s.', domain, hostname)
log.debug('DNS deletion REST call returned: %s', pprint.pformat(ret))
return False
def show_pricing(kwargs=None, call=None):
'''
Show pricing for a particular profile. This is only an estimate, based on
unofficial pricing sources.
.. versionadded:: 2015.8.0
CLI Examples:
.. code-block:: bash
salt-cloud -f show_pricing my-digitalocean-config profile=my-profile
'''
profile = __opts__['profiles'].get(kwargs['profile'], {})
if not profile:
return {'Error': 'The requested profile was not found'}
# Make sure the profile belongs to DigitalOcean
provider = profile.get('provider', '0:0')
comps = provider.split(':')
if len(comps) < 2 or comps[1] != 'digitalocean':
return {'Error': 'The requested profile does not belong to DigitalOcean'}
raw = {}
ret = {}
sizes = avail_sizes()
ret['per_hour'] = decimal.Decimal(sizes[profile['size']]['price_hourly'])
ret['per_day'] = ret['per_hour'] * 24
ret['per_week'] = ret['per_day'] * 7
ret['per_month'] = decimal.Decimal(sizes[profile['size']]['price_monthly'])
ret['per_year'] = ret['per_week'] * 52
if kwargs.get('raw', False):
ret['_raw'] = raw
return {profile['profile']: ret}
def list_floating_ips(call=None):
'''
Return a list of the floating ips that are on the provider
.. versionadded:: 2016.3.0
CLI Examples:
.. code-block:: bash
salt-cloud -f list_floating_ips my-digitalocean-config
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_floating_ips function must be called with '
'-f or --function, or with the --list-floating-ips option'
)
fetch = True
page = 1
ret = {}
while fetch:
items = query(method='floating_ips',
command='?page=' + six.text_type(page) + '&per_page=200')
for floating_ip in items['floating_ips']:
ret[floating_ip['ip']] = {}
for item in six.iterkeys(floating_ip):
ret[floating_ip['ip']][item] = floating_ip[item]
page += 1
try:
fetch = 'next' in items['links']['pages']
except KeyError:
fetch = False
return ret
def show_floating_ip(kwargs=None, call=None):
'''
Show the details of a floating IP
.. versionadded:: 2016.3.0
CLI Examples:
.. code-block:: bash
salt-cloud -f show_floating_ip my-digitalocean-config floating_ip='45.55.96.47'
'''
if call != 'function':
log.error(
'The show_floating_ip function must be called with -f or --function.'
)
return False
if not kwargs:
kwargs = {}
if 'floating_ip' not in kwargs:
log.error('A floating IP is required.')
return False
floating_ip = kwargs['floating_ip']
log.debug('Floating ip is %s', floating_ip)
details = query(method='floating_ips', command=floating_ip)
return details
def create_floating_ip(kwargs=None, call=None):
'''
Create a new floating IP
.. versionadded:: 2016.3.0
CLI Examples:
.. code-block:: bash
salt-cloud -f create_floating_ip my-digitalocean-config region='NYC2'
salt-cloud -f create_floating_ip my-digitalocean-config droplet_id='1234567'
'''
if call != 'function':
log.error(
'The create_floating_ip function must be called with -f or --function.'
)
return False
if not kwargs:
kwargs = {}
if 'droplet_id' in kwargs:
result = query(method='floating_ips',
args={'droplet_id': kwargs['droplet_id']},
http_method='post')
return result
elif 'region' in kwargs:
result = query(method='floating_ips',
args={'region': kwargs['region']},
http_method='post')
return result
else:
log.error('A droplet_id or region is required.')
return False
def delete_floating_ip(kwargs=None, call=None):
'''
Delete a floating IP
.. versionadded:: 2016.3.0
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_floating_ip my-digitalocean-config floating_ip='45.55.96.47'
'''
if call != 'function':
log.error(
'The delete_floating_ip function must be called with -f or --function.'
)
return False
if not kwargs:
kwargs = {}
if 'floating_ip' not in kwargs:
log.error('A floating IP is required.')
return False
floating_ip = kwargs['floating_ip']
log.debug('Floating ip is %s', kwargs['floating_ip'])
result = query(method='floating_ips',
command=floating_ip,
http_method='delete')
return result
def assign_floating_ip(kwargs=None, call=None):
'''
Assign a floating IP
.. versionadded:: 2016.3.0
CLI Examples:
.. code-block:: bash
salt-cloud -f assign_floating_ip my-digitalocean-config droplet_id=1234567 floating_ip='45.55.96.47'
'''
if call != 'function':
log.error(
'The assign_floating_ip function must be called with -f or --function.'
)
return False
if not kwargs:
kwargs = {}
if 'floating_ip' and 'droplet_id' not in kwargs:
log.error('A floating IP and droplet_id is required.')
return False
result = query(method='floating_ips',
command=kwargs['floating_ip'] + '/actions',
args={'droplet_id': kwargs['droplet_id'], 'type': 'assign'},
http_method='post')
return result
def _list_nodes(full=False, for_output=False):
'''
Helper function to format and parse node data.
'''
fetch = True
page = 1
ret = {}
while fetch:
items = query(method='droplets',
command='?page=' + six.text_type(page) + '&per_page=200')
for node in items['droplets']:
name = node['name']
ret[name] = {}
if full:
ret[name] = _get_full_output(node, for_output=for_output)
else:
public_ips, private_ips = _get_ips(node['networks'])
ret[name] = {
'id': node['id'],
'image': node['image']['name'],
'name': name,
'private_ips': private_ips,
'public_ips': public_ips,
'size': node['size_slug'],
'state': six.text_type(node['status']),
}
page += 1
try:
fetch = 'next' in items['links']['pages']
except KeyError:
fetch = False
return ret
def reboot(name, call=None):
'''
Reboot a droplet in DigitalOcean.
.. versionadded:: 2015.8.8
name
The name of the droplet to restart.
CLI Example:
.. code-block:: bash
salt-cloud -a reboot droplet_name
'''
if call != 'action':
raise SaltCloudSystemExit(
'The restart action must be called with -a or --action.'
)
data = show_instance(name, call='action')
if data.get('status') == 'off':
return {'success': True,
'action': 'stop',
'status': 'off',
'msg': 'Machine is already off.'}
ret = query(droplet_id=data['id'],
command='actions',
args={'type': 'reboot'},
http_method='post')
return {'success': True,
'action': ret['action']['type'],
'state': ret['action']['status']}
def start(name, call=None):
'''
Start a droplet in DigitalOcean.
.. versionadded:: 2015.8.8
name
The name of the droplet to start.
CLI Example:
.. code-block:: bash
salt-cloud -a start droplet_name
'''
if call != 'action':
raise SaltCloudSystemExit(
'The start action must be called with -a or --action.'
)
data = show_instance(name, call='action')
if data.get('status') == 'active':
return {'success': True,
'action': 'start',
'status': 'active',
'msg': 'Machine is already running.'}
ret = query(droplet_id=data['id'],
command='actions',
args={'type': 'power_on'},
http_method='post')
return {'success': True,
'action': ret['action']['type'],
'state': ret['action']['status']}
def stop(name, call=None):
'''
Stop a droplet in DigitalOcean.
.. versionadded:: 2015.8.8
name
The name of the droplet to stop.
CLI Example:
.. code-block:: bash
salt-cloud -a stop droplet_name
'''
if call != 'action':
raise SaltCloudSystemExit(
'The stop action must be called with -a or --action.'
)
data = show_instance(name, call='action')
if data.get('status') == 'off':
return {'success': True,
'action': 'stop',
'status': 'off',
'msg': 'Machine is already off.'}
ret = query(droplet_id=data['id'],
command='actions',
args={'type': 'shutdown'},
http_method='post')
return {'success': True,
'action': ret['action']['type'],
'state': ret['action']['status']}
def _get_full_output(node, for_output=False):
'''
Helper function for _list_nodes to loop through all node information.
Returns a dictionary containing the full information of a node.
'''
ret = {}
for item in six.iterkeys(node):
value = node[item]
if value is not None and for_output:
value = six.text_type(value)
ret[item] = value
return ret
def _get_ips(networks):
'''
Helper function for list_nodes. Returns public and private ip lists based on a
given network dictionary.
'''
v4s = networks.get('v4')
v6s = networks.get('v6')
public_ips = []
private_ips = []
if v4s:
for item in v4s:
ip_type = item.get('type')
ip_address = item.get('ip_address')
if ip_type == 'public':
public_ips.append(ip_address)
if ip_type == 'private':
private_ips.append(ip_address)
if v6s:
for item in v6s:
ip_type = item.get('type')
ip_address = item.get('ip_address')
if ip_type == 'public':
public_ips.append(ip_address)
if ip_type == 'private':
private_ips.append(ip_address)
return public_ips, private_ips
|
saltstack/salt
|
salt/cloud/clouds/digitalocean.py
|
_list_nodes
|
python
|
def _list_nodes(full=False, for_output=False):
'''
Helper function to format and parse node data.
'''
fetch = True
page = 1
ret = {}
while fetch:
items = query(method='droplets',
command='?page=' + six.text_type(page) + '&per_page=200')
for node in items['droplets']:
name = node['name']
ret[name] = {}
if full:
ret[name] = _get_full_output(node, for_output=for_output)
else:
public_ips, private_ips = _get_ips(node['networks'])
ret[name] = {
'id': node['id'],
'image': node['image']['name'],
'name': name,
'private_ips': private_ips,
'public_ips': public_ips,
'size': node['size_slug'],
'state': six.text_type(node['status']),
}
page += 1
try:
fetch = 'next' in items['links']['pages']
except KeyError:
fetch = False
return ret
|
Helper function to format and parse node data.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/digitalocean.py#L1194-L1228
|
[
"def query(method='droplets', droplet_id=None, command=None, args=None, http_method='get'):\n '''\n Make a web call to DigitalOcean\n '''\n base_path = six.text_type(config.get_cloud_config_value(\n 'api_root',\n get_configured_provider(),\n __opts__,\n search_global=False,\n default='https://api.digitalocean.com/v2'\n ))\n\n path = '{0}/{1}/'.format(base_path, method)\n\n if droplet_id:\n path += '{0}/'.format(droplet_id)\n\n if command:\n path += command\n\n if not isinstance(args, dict):\n args = {}\n\n personal_access_token = config.get_cloud_config_value(\n 'personal_access_token', get_configured_provider(), __opts__, search_global=False\n )\n\n data = salt.utils.json.dumps(args)\n\n requester = getattr(requests, http_method)\n request = requester(path, data=data, headers={'Authorization': 'Bearer ' + personal_access_token, 'Content-Type': 'application/json'})\n if request.status_code > 299:\n raise SaltCloudSystemExit(\n 'An error occurred while querying DigitalOcean. HTTP Code: {0} '\n 'Error: \\'{1}\\''.format(\n request.status_code,\n # request.read()\n request.text\n )\n )\n\n log.debug(request.url)\n\n # success without data\n if request.status_code == 204:\n return True\n\n content = request.text\n\n result = salt.utils.json.loads(content)\n if result.get('status', '').lower() == 'error':\n raise SaltCloudSystemExit(\n pprint.pformat(result.get('error_message', {}))\n )\n\n return result\n",
"def _get_full_output(node, for_output=False):\n '''\n Helper function for _list_nodes to loop through all node information.\n Returns a dictionary containing the full information of a node.\n '''\n ret = {}\n for item in six.iterkeys(node):\n value = node[item]\n if value is not None and for_output:\n value = six.text_type(value)\n ret[item] = value\n return ret\n",
"def _get_ips(networks):\n '''\n Helper function for list_nodes. Returns public and private ip lists based on a\n given network dictionary.\n '''\n v4s = networks.get('v4')\n v6s = networks.get('v6')\n public_ips = []\n private_ips = []\n\n if v4s:\n for item in v4s:\n ip_type = item.get('type')\n ip_address = item.get('ip_address')\n if ip_type == 'public':\n public_ips.append(ip_address)\n if ip_type == 'private':\n private_ips.append(ip_address)\n\n if v6s:\n for item in v6s:\n ip_type = item.get('type')\n ip_address = item.get('ip_address')\n if ip_type == 'public':\n public_ips.append(ip_address)\n if ip_type == 'private':\n private_ips.append(ip_address)\n\n return public_ips, private_ips\n"
] |
# -*- coding: utf-8 -*-
'''
DigitalOcean Cloud Module
=========================
The DigitalOcean cloud module is used to control access to the DigitalOcean VPS system.
Use of this module requires a requires a ``personal_access_token``, an ``ssh_key_file``,
and at least one SSH key name in ``ssh_key_names``. More ``ssh_key_names`` can be added
by separating each key with a comma. The ``personal_access_token`` can be found in the
DigitalOcean web interface in the "Apps & API" section. The SSH key name can be found
under the "SSH Keys" section.
.. code-block:: yaml
# Note: This example is for /etc/salt/cloud.providers or any file in the
# /etc/salt/cloud.providers.d/ directory.
my-digital-ocean-config:
personal_access_token: xxx
ssh_key_file: /path/to/ssh/key/file
ssh_key_names: my-key-name,my-key-name-2
driver: digitalocean
:depends: requests
'''
# Import Python Libs
from __future__ import absolute_import, print_function, unicode_literals
import decimal
import logging
import os
import pprint
import time
# Import Salt Libs
import salt.utils.cloud
import salt.utils.files
import salt.utils.json
import salt.utils.stringutils
import salt.config as config
from salt.exceptions import (
SaltCloudConfigError,
SaltInvocationError,
SaltCloudNotFound,
SaltCloudSystemExit,
SaltCloudExecutionFailure,
SaltCloudExecutionTimeout
)
from salt.ext import six
from salt.ext.six.moves import zip
# Import Third Party Libs
try:
import requests
HAS_REQUESTS = True
except ImportError:
HAS_REQUESTS = False
# Get logging started
log = logging.getLogger(__name__)
__virtualname__ = 'digitalocean'
__virtual_aliases__ = ('digital_ocean', 'do')
# Only load in this module if the DIGITALOCEAN configurations are in place
def __virtual__():
'''
Check for DigitalOcean configurations
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
opts=__opts__,
provider=__active_provider_name__ or __virtualname__,
aliases=__virtual_aliases__,
required_keys=('personal_access_token',)
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'requests': HAS_REQUESTS}
)
def avail_locations(call=None):
'''
Return a dict of all available VM locations on the cloud provider with
relevant data
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
items = query(method='regions')
ret = {}
for region in items['regions']:
ret[region['name']] = {}
for item in six.iterkeys(region):
ret[region['name']][item] = six.text_type(region[item])
return ret
def avail_images(call=None):
'''
Return a list of the images that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
fetch = True
page = 1
ret = {}
while fetch:
items = query(method='images', command='?page=' + six.text_type(page) + '&per_page=200')
for image in items['images']:
ret[image['name']] = {}
for item in six.iterkeys(image):
ret[image['name']][item] = image[item]
page += 1
try:
fetch = 'next' in items['links']['pages']
except KeyError:
fetch = False
return ret
def avail_sizes(call=None):
'''
Return a list of the image sizes that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
items = query(method='sizes', command='?per_page=100')
ret = {}
for size in items['sizes']:
ret[size['slug']] = {}
for item in six.iterkeys(size):
ret[size['slug']][item] = six.text_type(size[item])
return ret
def list_nodes(call=None):
'''
Return a list of the VMs that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
return _list_nodes()
def list_nodes_full(call=None, for_output=True):
'''
Return a list of the VMs that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or --function.'
)
return _list_nodes(full=True, for_output=for_output)
def list_nodes_select(call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
return salt.utils.cloud.list_nodes_select(
list_nodes_full('function'), __opts__['query.selection'], call,
)
def get_image(vm_):
'''
Return the image object to use
'''
images = avail_images()
vm_image = config.get_cloud_config_value(
'image', vm_, __opts__, search_global=False
)
if not isinstance(vm_image, six.string_types):
vm_image = six.text_type(vm_image)
for image in images:
if vm_image in (images[image]['name'],
images[image]['slug'],
images[image]['id']):
if images[image]['slug'] is not None:
return images[image]['slug']
return int(images[image]['id'])
raise SaltCloudNotFound(
'The specified image, \'{0}\', could not be found.'.format(vm_image)
)
def get_size(vm_):
'''
Return the VM's size. Used by create_node().
'''
sizes = avail_sizes()
vm_size = six.text_type(config.get_cloud_config_value(
'size', vm_, __opts__, search_global=False
))
for size in sizes:
if vm_size.lower() == sizes[size]['slug']:
return sizes[size]['slug']
raise SaltCloudNotFound(
'The specified size, \'{0}\', could not be found.'.format(vm_size)
)
def get_location(vm_):
'''
Return the VM's location
'''
locations = avail_locations()
vm_location = six.text_type(config.get_cloud_config_value(
'location', vm_, __opts__, search_global=False
))
for location in locations:
if vm_location in (locations[location]['name'],
locations[location]['slug']):
return locations[location]['slug']
raise SaltCloudNotFound(
'The specified location, \'{0}\', could not be found.'.format(
vm_location
)
)
def create_node(args):
'''
Create a node
'''
node = query(method='droplets', args=args, http_method='post')
return node
def create(vm_):
'''
Create a single VM from a data dict
'''
try:
# Check for required profile parameters before sending any API calls.
if vm_['profile'] and config.is_profile_configured(__opts__,
__active_provider_name__ or 'digitalocean',
vm_['profile'],
vm_=vm_) is False:
return False
except AttributeError:
pass
__utils__['cloud.fire_event'](
'event',
'starting create',
'salt/cloud/{0}/creating'.format(vm_['name']),
args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Creating Cloud VM %s', vm_['name'])
kwargs = {
'name': vm_['name'],
'size': get_size(vm_),
'image': get_image(vm_),
'region': get_location(vm_),
'ssh_keys': [],
'tags': []
}
# backwards compat
ssh_key_name = config.get_cloud_config_value(
'ssh_key_name', vm_, __opts__, search_global=False
)
if ssh_key_name:
kwargs['ssh_keys'].append(get_keyid(ssh_key_name))
ssh_key_names = config.get_cloud_config_value(
'ssh_key_names', vm_, __opts__, search_global=False, default=False
)
if ssh_key_names:
for key in ssh_key_names.split(','):
kwargs['ssh_keys'].append(get_keyid(key))
key_filename = config.get_cloud_config_value(
'ssh_key_file', vm_, __opts__, search_global=False, default=None
)
if key_filename is not None and not os.path.isfile(key_filename):
raise SaltCloudConfigError(
'The defined key_filename \'{0}\' does not exist'.format(
key_filename
)
)
if not __opts__.get('ssh_agent', False) and key_filename is None:
raise SaltCloudConfigError(
'The DigitalOcean driver requires an ssh_key_file and an ssh_key_name '
'because it does not supply a root password upon building the server.'
)
ssh_interface = config.get_cloud_config_value(
'ssh_interface', vm_, __opts__, search_global=False, default='public'
)
if ssh_interface in ['private', 'public']:
log.info("ssh_interface: Setting interface for ssh to %s", ssh_interface)
kwargs['ssh_interface'] = ssh_interface
else:
raise SaltCloudConfigError(
"The DigitalOcean driver requires ssh_interface to be defined as 'public' or 'private'."
)
private_networking = config.get_cloud_config_value(
'private_networking', vm_, __opts__, search_global=False, default=None,
)
if private_networking is not None:
if not isinstance(private_networking, bool):
raise SaltCloudConfigError("'private_networking' should be a boolean value.")
kwargs['private_networking'] = private_networking
if not private_networking and ssh_interface == 'private':
raise SaltCloudConfigError(
"The DigitalOcean driver requires ssh_interface if defined as 'private' "
"then private_networking should be set as 'True'."
)
backups_enabled = config.get_cloud_config_value(
'backups_enabled', vm_, __opts__, search_global=False, default=None,
)
if backups_enabled is not None:
if not isinstance(backups_enabled, bool):
raise SaltCloudConfigError("'backups_enabled' should be a boolean value.")
kwargs['backups'] = backups_enabled
ipv6 = config.get_cloud_config_value(
'ipv6', vm_, __opts__, search_global=False, default=None,
)
if ipv6 is not None:
if not isinstance(ipv6, bool):
raise SaltCloudConfigError("'ipv6' should be a boolean value.")
kwargs['ipv6'] = ipv6
monitoring = config.get_cloud_config_value(
'monitoring', vm_, __opts__, search_global=False, default=None,
)
if monitoring is not None:
if not isinstance(monitoring, bool):
raise SaltCloudConfigError("'monitoring' should be a boolean value.")
kwargs['monitoring'] = monitoring
kwargs['tags'] = config.get_cloud_config_value(
'tags', vm_, __opts__, search_global=False, default=False
)
userdata_file = config.get_cloud_config_value(
'userdata_file', vm_, __opts__, search_global=False, default=None
)
if userdata_file is not None:
try:
with salt.utils.files.fopen(userdata_file, 'r') as fp_:
kwargs['user_data'] = salt.utils.cloud.userdata_template(
__opts__, vm_, salt.utils.stringutils.to_unicode(fp_.read())
)
except Exception as exc:
log.exception(
'Failed to read userdata from %s: %s', userdata_file, exc)
create_dns_record = config.get_cloud_config_value(
'create_dns_record', vm_, __opts__, search_global=False, default=None,
)
if create_dns_record:
log.info('create_dns_record: will attempt to write DNS records')
default_dns_domain = None
dns_domain_name = vm_['name'].split('.')
if len(dns_domain_name) > 2:
log.debug('create_dns_record: inferring default dns_hostname, dns_domain from minion name as FQDN')
default_dns_hostname = '.'.join(dns_domain_name[:-2])
default_dns_domain = '.'.join(dns_domain_name[-2:])
else:
log.debug("create_dns_record: can't infer dns_domain from %s", vm_['name'])
default_dns_hostname = dns_domain_name[0]
dns_hostname = config.get_cloud_config_value(
'dns_hostname', vm_, __opts__, search_global=False, default=default_dns_hostname,
)
dns_domain = config.get_cloud_config_value(
'dns_domain', vm_, __opts__, search_global=False, default=default_dns_domain,
)
if dns_hostname and dns_domain:
log.info('create_dns_record: using dns_hostname="%s", dns_domain="%s"', dns_hostname, dns_domain)
__add_dns_addr__ = lambda t, d: post_dns_record(dns_domain=dns_domain,
name=dns_hostname,
record_type=t,
record_data=d)
log.debug('create_dns_record: %s', __add_dns_addr__)
else:
log.error('create_dns_record: could not determine dns_hostname and/or dns_domain')
raise SaltCloudConfigError(
'\'create_dns_record\' must be a dict specifying "domain" '
'and "hostname" or the minion name must be an FQDN.'
)
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args=__utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
try:
ret = create_node(kwargs)
except Exception as exc:
log.error(
'Error creating %s on DIGITALOCEAN\n\n'
'The following exception was thrown when trying to '
'run the initial deployment: %s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
def __query_node_data(vm_name):
data = show_instance(vm_name, 'action')
if not data:
# Trigger an error in the wait_for_ip function
return False
if data['networks'].get('v4'):
for network in data['networks']['v4']:
if network['type'] == 'public':
return data
return False
try:
data = salt.utils.cloud.wait_for_ip(
__query_node_data,
update_args=(vm_['name'],),
timeout=config.get_cloud_config_value(
'wait_for_ip_timeout', vm_, __opts__, default=10 * 60),
interval=config.get_cloud_config_value(
'wait_for_ip_interval', vm_, __opts__, default=10),
)
except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc:
try:
# It might be already up, let's destroy it!
destroy(vm_['name'])
except SaltCloudSystemExit:
pass
finally:
raise SaltCloudSystemExit(six.text_type(exc))
if not vm_.get('ssh_host'):
vm_['ssh_host'] = None
# add DNS records, set ssh_host, default to first found IP, preferring IPv4 for ssh bootstrap script target
addr_families, dns_arec_types = (('v4', 'v6'), ('A', 'AAAA'))
arec_map = dict(list(zip(addr_families, dns_arec_types)))
for facing, addr_family, ip_address in [(net['type'], family, net['ip_address'])
for family in addr_families
for net in data['networks'][family]]:
log.info('found %s IP%s interface for "%s"', facing, addr_family, ip_address)
dns_rec_type = arec_map[addr_family]
if facing == 'public':
if create_dns_record:
__add_dns_addr__(dns_rec_type, ip_address)
if facing == ssh_interface:
if not vm_['ssh_host']:
vm_['ssh_host'] = ip_address
if vm_['ssh_host'] is None:
raise SaltCloudSystemExit(
'No suitable IP addresses found for ssh minion bootstrapping: {0}'.format(repr(data['networks']))
)
log.debug(
'Found public IP address to use for ssh minion bootstrapping: %s',
vm_['ssh_host']
)
vm_['key_filename'] = key_filename
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
ret.update(data)
log.info('Created Cloud VM \'%s\'', vm_['name'])
log.debug(
'\'%s\' VM creation details:\n%s',
vm_['name'], pprint.pformat(data)
)
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return ret
def query(method='droplets', droplet_id=None, command=None, args=None, http_method='get'):
'''
Make a web call to DigitalOcean
'''
base_path = six.text_type(config.get_cloud_config_value(
'api_root',
get_configured_provider(),
__opts__,
search_global=False,
default='https://api.digitalocean.com/v2'
))
path = '{0}/{1}/'.format(base_path, method)
if droplet_id:
path += '{0}/'.format(droplet_id)
if command:
path += command
if not isinstance(args, dict):
args = {}
personal_access_token = config.get_cloud_config_value(
'personal_access_token', get_configured_provider(), __opts__, search_global=False
)
data = salt.utils.json.dumps(args)
requester = getattr(requests, http_method)
request = requester(path, data=data, headers={'Authorization': 'Bearer ' + personal_access_token, 'Content-Type': 'application/json'})
if request.status_code > 299:
raise SaltCloudSystemExit(
'An error occurred while querying DigitalOcean. HTTP Code: {0} '
'Error: \'{1}\''.format(
request.status_code,
# request.read()
request.text
)
)
log.debug(request.url)
# success without data
if request.status_code == 204:
return True
content = request.text
result = salt.utils.json.loads(content)
if result.get('status', '').lower() == 'error':
raise SaltCloudSystemExit(
pprint.pformat(result.get('error_message', {}))
)
return result
def script(vm_):
'''
Return the script deployment object
'''
deploy_script = salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
return deploy_script
def show_instance(name, call=None):
'''
Show the details from DigitalOcean concerning a droplet
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
node = _get_node(name)
__utils__['cloud.cache_node'](node, __active_provider_name__, __opts__)
return node
def _get_node(name):
attempts = 10
while attempts >= 0:
try:
return list_nodes_full(for_output=False)[name]
except KeyError:
attempts -= 1
log.debug(
'Failed to get the data for node \'%s\'. Remaining '
'attempts: %s', name, attempts
)
# Just a little delay between attempts...
time.sleep(0.5)
return {}
def list_keypairs(call=None):
'''
Return a dict of all available VM locations on the cloud provider with
relevant data
'''
if call != 'function':
log.error(
'The list_keypairs function must be called with -f or --function.'
)
return False
fetch = True
page = 1
ret = {}
while fetch:
items = query(method='account/keys', command='?page=' + six.text_type(page) +
'&per_page=100')
for key_pair in items['ssh_keys']:
name = key_pair['name']
if name in ret:
raise SaltCloudSystemExit(
'A duplicate key pair name, \'{0}\', was found in DigitalOcean\'s '
'key pair list. Please change the key name stored by DigitalOcean. '
'Be sure to adjust the value of \'ssh_key_file\' in your cloud '
'profile or provider configuration, if necessary.'.format(
name
)
)
ret[name] = {}
for item in six.iterkeys(key_pair):
ret[name][item] = six.text_type(key_pair[item])
page += 1
try:
fetch = 'next' in items['links']['pages']
except KeyError:
fetch = False
return ret
def show_keypair(kwargs=None, call=None):
'''
Show the details of an SSH keypair
'''
if call != 'function':
log.error(
'The show_keypair function must be called with -f or --function.'
)
return False
if not kwargs:
kwargs = {}
if 'keyname' not in kwargs:
log.error('A keyname is required.')
return False
keypairs = list_keypairs(call='function')
keyid = keypairs[kwargs['keyname']]['id']
log.debug('Key ID is %s', keyid)
details = query(method='account/keys', command=keyid)
return details
def import_keypair(kwargs=None, call=None):
'''
Upload public key to cloud provider.
Similar to EC2 import_keypair.
.. versionadded:: 2016.11.0
kwargs
file(mandatory): public key file-name
keyname(mandatory): public key name in the provider
'''
with salt.utils.files.fopen(kwargs['file'], 'r') as public_key_filename:
public_key_content = salt.utils.stringutils.to_unicode(public_key_filename.read())
digitalocean_kwargs = {
'name': kwargs['keyname'],
'public_key': public_key_content
}
created_result = create_key(digitalocean_kwargs, call=call)
return created_result
def create_key(kwargs=None, call=None):
'''
Upload a public key
'''
if call != 'function':
log.error(
'The create_key function must be called with -f or --function.'
)
return False
try:
result = query(
method='account',
command='keys',
args={'name': kwargs['name'],
'public_key': kwargs['public_key']},
http_method='post'
)
except KeyError:
log.info('`name` and `public_key` arguments must be specified')
return False
return result
def remove_key(kwargs=None, call=None):
'''
Delete public key
'''
if call != 'function':
log.error(
'The create_key function must be called with -f or --function.'
)
return False
try:
result = query(
method='account',
command='keys/' + kwargs['id'],
http_method='delete'
)
except KeyError:
log.info('`id` argument must be specified')
return False
return result
def get_keyid(keyname):
'''
Return the ID of the keyname
'''
if not keyname:
return None
keypairs = list_keypairs(call='function')
keyid = keypairs[keyname]['id']
if keyid:
return keyid
raise SaltCloudNotFound('The specified ssh key could not be found.')
def destroy(name, call=None):
'''
Destroy a node. Will check termination protection and warn if enabled.
CLI Example:
.. code-block:: bash
salt-cloud --destroy mymachine
'''
if call == 'function':
raise SaltCloudSystemExit(
'The destroy action must be called with -d, --destroy, '
'-a or --action.'
)
__utils__['cloud.fire_event'](
'event',
'destroying instance',
'salt/cloud/{0}/destroying'.format(name),
args={'name': name},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
data = show_instance(name, call='action')
node = query(method='droplets', droplet_id=data['id'], http_method='delete')
## This is all terribly optomistic:
# vm_ = get_vm_config(name=name)
# delete_dns_record = config.get_cloud_config_value(
# 'delete_dns_record', vm_, __opts__, search_global=False, default=None,
# )
# TODO: when _vm config data can be made available, we should honor the configuration settings,
# but until then, we should assume stale DNS records are bad, and default behavior should be to
# delete them if we can. When this is resolved, also resolve the comments a couple of lines below.
delete_dns_record = True
if not isinstance(delete_dns_record, bool):
raise SaltCloudConfigError(
'\'delete_dns_record\' should be a boolean value.'
)
# When the "to do" a few lines up is resolved, remove these lines and use the if/else logic below.
log.debug('Deleting DNS records for %s.', name)
destroy_dns_records(name)
# Until the "to do" from line 754 is taken care of, we don't need this logic.
# if delete_dns_record:
# log.debug('Deleting DNS records for %s.', name)
# destroy_dns_records(name)
# else:
# log.debug('delete_dns_record : %s', delete_dns_record)
# for line in pprint.pformat(dir()).splitlines():
# log.debug('delete context: %s', line)
__utils__['cloud.fire_event'](
'event',
'destroyed instance',
'salt/cloud/{0}/destroyed'.format(name),
args={'name': name},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
if __opts__.get('update_cachedir', False) is True:
__utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__)
return node
def post_dns_record(**kwargs):
'''
Creates a DNS record for the given name if the domain is managed with DO.
'''
if 'kwargs' in kwargs: # flatten kwargs if called via salt-cloud -f
f_kwargs = kwargs['kwargs']
del kwargs['kwargs']
kwargs.update(f_kwargs)
mandatory_kwargs = ('dns_domain', 'name', 'record_type', 'record_data')
for i in mandatory_kwargs:
if kwargs[i]:
pass
else:
error = '{0}="{1}" ## all mandatory args must be provided: {2}'.format(i, kwargs[i], mandatory_kwargs)
raise SaltInvocationError(error)
domain = query(method='domains', droplet_id=kwargs['dns_domain'])
if domain:
result = query(
method='domains',
droplet_id=kwargs['dns_domain'],
command='records',
args={'type': kwargs['record_type'], 'name': kwargs['name'], 'data': kwargs['record_data']},
http_method='post'
)
return result
return False
def destroy_dns_records(fqdn):
'''
Deletes DNS records for the given hostname if the domain is managed with DO.
'''
domain = '.'.join(fqdn.split('.')[-2:])
hostname = '.'.join(fqdn.split('.')[:-2])
# TODO: remove this when the todo on 754 is available
try:
response = query(method='domains', droplet_id=domain, command='records')
except SaltCloudSystemExit:
log.debug('Failed to find domains.')
return False
log.debug("found DNS records: %s", pprint.pformat(response))
records = response['domain_records']
if records:
record_ids = [r['id'] for r in records if r['name'].decode() == hostname]
log.debug("deleting DNS record IDs: %s", record_ids)
for id_ in record_ids:
try:
log.info('deleting DNS record %s', id_)
ret = query(
method='domains',
droplet_id=domain,
command='records/{0}'.format(id_),
http_method='delete'
)
except SaltCloudSystemExit:
log.error('failed to delete DNS domain %s record ID %s.', domain, hostname)
log.debug('DNS deletion REST call returned: %s', pprint.pformat(ret))
return False
def show_pricing(kwargs=None, call=None):
'''
Show pricing for a particular profile. This is only an estimate, based on
unofficial pricing sources.
.. versionadded:: 2015.8.0
CLI Examples:
.. code-block:: bash
salt-cloud -f show_pricing my-digitalocean-config profile=my-profile
'''
profile = __opts__['profiles'].get(kwargs['profile'], {})
if not profile:
return {'Error': 'The requested profile was not found'}
# Make sure the profile belongs to DigitalOcean
provider = profile.get('provider', '0:0')
comps = provider.split(':')
if len(comps) < 2 or comps[1] != 'digitalocean':
return {'Error': 'The requested profile does not belong to DigitalOcean'}
raw = {}
ret = {}
sizes = avail_sizes()
ret['per_hour'] = decimal.Decimal(sizes[profile['size']]['price_hourly'])
ret['per_day'] = ret['per_hour'] * 24
ret['per_week'] = ret['per_day'] * 7
ret['per_month'] = decimal.Decimal(sizes[profile['size']]['price_monthly'])
ret['per_year'] = ret['per_week'] * 52
if kwargs.get('raw', False):
ret['_raw'] = raw
return {profile['profile']: ret}
def list_floating_ips(call=None):
'''
Return a list of the floating ips that are on the provider
.. versionadded:: 2016.3.0
CLI Examples:
.. code-block:: bash
salt-cloud -f list_floating_ips my-digitalocean-config
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_floating_ips function must be called with '
'-f or --function, or with the --list-floating-ips option'
)
fetch = True
page = 1
ret = {}
while fetch:
items = query(method='floating_ips',
command='?page=' + six.text_type(page) + '&per_page=200')
for floating_ip in items['floating_ips']:
ret[floating_ip['ip']] = {}
for item in six.iterkeys(floating_ip):
ret[floating_ip['ip']][item] = floating_ip[item]
page += 1
try:
fetch = 'next' in items['links']['pages']
except KeyError:
fetch = False
return ret
def show_floating_ip(kwargs=None, call=None):
'''
Show the details of a floating IP
.. versionadded:: 2016.3.0
CLI Examples:
.. code-block:: bash
salt-cloud -f show_floating_ip my-digitalocean-config floating_ip='45.55.96.47'
'''
if call != 'function':
log.error(
'The show_floating_ip function must be called with -f or --function.'
)
return False
if not kwargs:
kwargs = {}
if 'floating_ip' not in kwargs:
log.error('A floating IP is required.')
return False
floating_ip = kwargs['floating_ip']
log.debug('Floating ip is %s', floating_ip)
details = query(method='floating_ips', command=floating_ip)
return details
def create_floating_ip(kwargs=None, call=None):
'''
Create a new floating IP
.. versionadded:: 2016.3.0
CLI Examples:
.. code-block:: bash
salt-cloud -f create_floating_ip my-digitalocean-config region='NYC2'
salt-cloud -f create_floating_ip my-digitalocean-config droplet_id='1234567'
'''
if call != 'function':
log.error(
'The create_floating_ip function must be called with -f or --function.'
)
return False
if not kwargs:
kwargs = {}
if 'droplet_id' in kwargs:
result = query(method='floating_ips',
args={'droplet_id': kwargs['droplet_id']},
http_method='post')
return result
elif 'region' in kwargs:
result = query(method='floating_ips',
args={'region': kwargs['region']},
http_method='post')
return result
else:
log.error('A droplet_id or region is required.')
return False
def delete_floating_ip(kwargs=None, call=None):
'''
Delete a floating IP
.. versionadded:: 2016.3.0
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_floating_ip my-digitalocean-config floating_ip='45.55.96.47'
'''
if call != 'function':
log.error(
'The delete_floating_ip function must be called with -f or --function.'
)
return False
if not kwargs:
kwargs = {}
if 'floating_ip' not in kwargs:
log.error('A floating IP is required.')
return False
floating_ip = kwargs['floating_ip']
log.debug('Floating ip is %s', kwargs['floating_ip'])
result = query(method='floating_ips',
command=floating_ip,
http_method='delete')
return result
def assign_floating_ip(kwargs=None, call=None):
'''
Assign a floating IP
.. versionadded:: 2016.3.0
CLI Examples:
.. code-block:: bash
salt-cloud -f assign_floating_ip my-digitalocean-config droplet_id=1234567 floating_ip='45.55.96.47'
'''
if call != 'function':
log.error(
'The assign_floating_ip function must be called with -f or --function.'
)
return False
if not kwargs:
kwargs = {}
if 'floating_ip' and 'droplet_id' not in kwargs:
log.error('A floating IP and droplet_id is required.')
return False
result = query(method='floating_ips',
command=kwargs['floating_ip'] + '/actions',
args={'droplet_id': kwargs['droplet_id'], 'type': 'assign'},
http_method='post')
return result
def unassign_floating_ip(kwargs=None, call=None):
'''
Unassign a floating IP
.. versionadded:: 2016.3.0
CLI Examples:
.. code-block:: bash
salt-cloud -f unassign_floating_ip my-digitalocean-config floating_ip='45.55.96.47'
'''
if call != 'function':
log.error(
'The inassign_floating_ip function must be called with -f or --function.'
)
return False
if not kwargs:
kwargs = {}
if 'floating_ip' not in kwargs:
log.error('A floating IP is required.')
return False
result = query(method='floating_ips',
command=kwargs['floating_ip'] + '/actions',
args={'type': 'unassign'},
http_method='post')
return result
def reboot(name, call=None):
'''
Reboot a droplet in DigitalOcean.
.. versionadded:: 2015.8.8
name
The name of the droplet to restart.
CLI Example:
.. code-block:: bash
salt-cloud -a reboot droplet_name
'''
if call != 'action':
raise SaltCloudSystemExit(
'The restart action must be called with -a or --action.'
)
data = show_instance(name, call='action')
if data.get('status') == 'off':
return {'success': True,
'action': 'stop',
'status': 'off',
'msg': 'Machine is already off.'}
ret = query(droplet_id=data['id'],
command='actions',
args={'type': 'reboot'},
http_method='post')
return {'success': True,
'action': ret['action']['type'],
'state': ret['action']['status']}
def start(name, call=None):
'''
Start a droplet in DigitalOcean.
.. versionadded:: 2015.8.8
name
The name of the droplet to start.
CLI Example:
.. code-block:: bash
salt-cloud -a start droplet_name
'''
if call != 'action':
raise SaltCloudSystemExit(
'The start action must be called with -a or --action.'
)
data = show_instance(name, call='action')
if data.get('status') == 'active':
return {'success': True,
'action': 'start',
'status': 'active',
'msg': 'Machine is already running.'}
ret = query(droplet_id=data['id'],
command='actions',
args={'type': 'power_on'},
http_method='post')
return {'success': True,
'action': ret['action']['type'],
'state': ret['action']['status']}
def stop(name, call=None):
'''
Stop a droplet in DigitalOcean.
.. versionadded:: 2015.8.8
name
The name of the droplet to stop.
CLI Example:
.. code-block:: bash
salt-cloud -a stop droplet_name
'''
if call != 'action':
raise SaltCloudSystemExit(
'The stop action must be called with -a or --action.'
)
data = show_instance(name, call='action')
if data.get('status') == 'off':
return {'success': True,
'action': 'stop',
'status': 'off',
'msg': 'Machine is already off.'}
ret = query(droplet_id=data['id'],
command='actions',
args={'type': 'shutdown'},
http_method='post')
return {'success': True,
'action': ret['action']['type'],
'state': ret['action']['status']}
def _get_full_output(node, for_output=False):
'''
Helper function for _list_nodes to loop through all node information.
Returns a dictionary containing the full information of a node.
'''
ret = {}
for item in six.iterkeys(node):
value = node[item]
if value is not None and for_output:
value = six.text_type(value)
ret[item] = value
return ret
def _get_ips(networks):
'''
Helper function for list_nodes. Returns public and private ip lists based on a
given network dictionary.
'''
v4s = networks.get('v4')
v6s = networks.get('v6')
public_ips = []
private_ips = []
if v4s:
for item in v4s:
ip_type = item.get('type')
ip_address = item.get('ip_address')
if ip_type == 'public':
public_ips.append(ip_address)
if ip_type == 'private':
private_ips.append(ip_address)
if v6s:
for item in v6s:
ip_type = item.get('type')
ip_address = item.get('ip_address')
if ip_type == 'public':
public_ips.append(ip_address)
if ip_type == 'private':
private_ips.append(ip_address)
return public_ips, private_ips
|
saltstack/salt
|
salt/cloud/clouds/digitalocean.py
|
reboot
|
python
|
def reboot(name, call=None):
'''
Reboot a droplet in DigitalOcean.
.. versionadded:: 2015.8.8
name
The name of the droplet to restart.
CLI Example:
.. code-block:: bash
salt-cloud -a reboot droplet_name
'''
if call != 'action':
raise SaltCloudSystemExit(
'The restart action must be called with -a or --action.'
)
data = show_instance(name, call='action')
if data.get('status') == 'off':
return {'success': True,
'action': 'stop',
'status': 'off',
'msg': 'Machine is already off.'}
ret = query(droplet_id=data['id'],
command='actions',
args={'type': 'reboot'},
http_method='post')
return {'success': True,
'action': ret['action']['type'],
'state': ret['action']['status']}
|
Reboot a droplet in DigitalOcean.
.. versionadded:: 2015.8.8
name
The name of the droplet to restart.
CLI Example:
.. code-block:: bash
salt-cloud -a reboot droplet_name
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/digitalocean.py#L1231-L1265
|
[
"def query(method='droplets', droplet_id=None, command=None, args=None, http_method='get'):\n '''\n Make a web call to DigitalOcean\n '''\n base_path = six.text_type(config.get_cloud_config_value(\n 'api_root',\n get_configured_provider(),\n __opts__,\n search_global=False,\n default='https://api.digitalocean.com/v2'\n ))\n\n path = '{0}/{1}/'.format(base_path, method)\n\n if droplet_id:\n path += '{0}/'.format(droplet_id)\n\n if command:\n path += command\n\n if not isinstance(args, dict):\n args = {}\n\n personal_access_token = config.get_cloud_config_value(\n 'personal_access_token', get_configured_provider(), __opts__, search_global=False\n )\n\n data = salt.utils.json.dumps(args)\n\n requester = getattr(requests, http_method)\n request = requester(path, data=data, headers={'Authorization': 'Bearer ' + personal_access_token, 'Content-Type': 'application/json'})\n if request.status_code > 299:\n raise SaltCloudSystemExit(\n 'An error occurred while querying DigitalOcean. HTTP Code: {0} '\n 'Error: \\'{1}\\''.format(\n request.status_code,\n # request.read()\n request.text\n )\n )\n\n log.debug(request.url)\n\n # success without data\n if request.status_code == 204:\n return True\n\n content = request.text\n\n result = salt.utils.json.loads(content)\n if result.get('status', '').lower() == 'error':\n raise SaltCloudSystemExit(\n pprint.pformat(result.get('error_message', {}))\n )\n\n return result\n",
"def show_instance(name, call=None):\n '''\n Show the details from DigitalOcean concerning a droplet\n '''\n if call != 'action':\n raise SaltCloudSystemExit(\n 'The show_instance action must be called with -a or --action.'\n )\n node = _get_node(name)\n __utils__['cloud.cache_node'](node, __active_provider_name__, __opts__)\n return node\n"
] |
# -*- coding: utf-8 -*-
'''
DigitalOcean Cloud Module
=========================
The DigitalOcean cloud module is used to control access to the DigitalOcean VPS system.
Use of this module requires a requires a ``personal_access_token``, an ``ssh_key_file``,
and at least one SSH key name in ``ssh_key_names``. More ``ssh_key_names`` can be added
by separating each key with a comma. The ``personal_access_token`` can be found in the
DigitalOcean web interface in the "Apps & API" section. The SSH key name can be found
under the "SSH Keys" section.
.. code-block:: yaml
# Note: This example is for /etc/salt/cloud.providers or any file in the
# /etc/salt/cloud.providers.d/ directory.
my-digital-ocean-config:
personal_access_token: xxx
ssh_key_file: /path/to/ssh/key/file
ssh_key_names: my-key-name,my-key-name-2
driver: digitalocean
:depends: requests
'''
# Import Python Libs
from __future__ import absolute_import, print_function, unicode_literals
import decimal
import logging
import os
import pprint
import time
# Import Salt Libs
import salt.utils.cloud
import salt.utils.files
import salt.utils.json
import salt.utils.stringutils
import salt.config as config
from salt.exceptions import (
SaltCloudConfigError,
SaltInvocationError,
SaltCloudNotFound,
SaltCloudSystemExit,
SaltCloudExecutionFailure,
SaltCloudExecutionTimeout
)
from salt.ext import six
from salt.ext.six.moves import zip
# Import Third Party Libs
try:
import requests
HAS_REQUESTS = True
except ImportError:
HAS_REQUESTS = False
# Get logging started
log = logging.getLogger(__name__)
__virtualname__ = 'digitalocean'
__virtual_aliases__ = ('digital_ocean', 'do')
# Only load in this module if the DIGITALOCEAN configurations are in place
def __virtual__():
'''
Check for DigitalOcean configurations
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
opts=__opts__,
provider=__active_provider_name__ or __virtualname__,
aliases=__virtual_aliases__,
required_keys=('personal_access_token',)
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'requests': HAS_REQUESTS}
)
def avail_locations(call=None):
'''
Return a dict of all available VM locations on the cloud provider with
relevant data
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
items = query(method='regions')
ret = {}
for region in items['regions']:
ret[region['name']] = {}
for item in six.iterkeys(region):
ret[region['name']][item] = six.text_type(region[item])
return ret
def avail_images(call=None):
'''
Return a list of the images that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
fetch = True
page = 1
ret = {}
while fetch:
items = query(method='images', command='?page=' + six.text_type(page) + '&per_page=200')
for image in items['images']:
ret[image['name']] = {}
for item in six.iterkeys(image):
ret[image['name']][item] = image[item]
page += 1
try:
fetch = 'next' in items['links']['pages']
except KeyError:
fetch = False
return ret
def avail_sizes(call=None):
'''
Return a list of the image sizes that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
items = query(method='sizes', command='?per_page=100')
ret = {}
for size in items['sizes']:
ret[size['slug']] = {}
for item in six.iterkeys(size):
ret[size['slug']][item] = six.text_type(size[item])
return ret
def list_nodes(call=None):
'''
Return a list of the VMs that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
return _list_nodes()
def list_nodes_full(call=None, for_output=True):
'''
Return a list of the VMs that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or --function.'
)
return _list_nodes(full=True, for_output=for_output)
def list_nodes_select(call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
return salt.utils.cloud.list_nodes_select(
list_nodes_full('function'), __opts__['query.selection'], call,
)
def get_image(vm_):
'''
Return the image object to use
'''
images = avail_images()
vm_image = config.get_cloud_config_value(
'image', vm_, __opts__, search_global=False
)
if not isinstance(vm_image, six.string_types):
vm_image = six.text_type(vm_image)
for image in images:
if vm_image in (images[image]['name'],
images[image]['slug'],
images[image]['id']):
if images[image]['slug'] is not None:
return images[image]['slug']
return int(images[image]['id'])
raise SaltCloudNotFound(
'The specified image, \'{0}\', could not be found.'.format(vm_image)
)
def get_size(vm_):
'''
Return the VM's size. Used by create_node().
'''
sizes = avail_sizes()
vm_size = six.text_type(config.get_cloud_config_value(
'size', vm_, __opts__, search_global=False
))
for size in sizes:
if vm_size.lower() == sizes[size]['slug']:
return sizes[size]['slug']
raise SaltCloudNotFound(
'The specified size, \'{0}\', could not be found.'.format(vm_size)
)
def get_location(vm_):
'''
Return the VM's location
'''
locations = avail_locations()
vm_location = six.text_type(config.get_cloud_config_value(
'location', vm_, __opts__, search_global=False
))
for location in locations:
if vm_location in (locations[location]['name'],
locations[location]['slug']):
return locations[location]['slug']
raise SaltCloudNotFound(
'The specified location, \'{0}\', could not be found.'.format(
vm_location
)
)
def create_node(args):
'''
Create a node
'''
node = query(method='droplets', args=args, http_method='post')
return node
def create(vm_):
'''
Create a single VM from a data dict
'''
try:
# Check for required profile parameters before sending any API calls.
if vm_['profile'] and config.is_profile_configured(__opts__,
__active_provider_name__ or 'digitalocean',
vm_['profile'],
vm_=vm_) is False:
return False
except AttributeError:
pass
__utils__['cloud.fire_event'](
'event',
'starting create',
'salt/cloud/{0}/creating'.format(vm_['name']),
args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Creating Cloud VM %s', vm_['name'])
kwargs = {
'name': vm_['name'],
'size': get_size(vm_),
'image': get_image(vm_),
'region': get_location(vm_),
'ssh_keys': [],
'tags': []
}
# backwards compat
ssh_key_name = config.get_cloud_config_value(
'ssh_key_name', vm_, __opts__, search_global=False
)
if ssh_key_name:
kwargs['ssh_keys'].append(get_keyid(ssh_key_name))
ssh_key_names = config.get_cloud_config_value(
'ssh_key_names', vm_, __opts__, search_global=False, default=False
)
if ssh_key_names:
for key in ssh_key_names.split(','):
kwargs['ssh_keys'].append(get_keyid(key))
key_filename = config.get_cloud_config_value(
'ssh_key_file', vm_, __opts__, search_global=False, default=None
)
if key_filename is not None and not os.path.isfile(key_filename):
raise SaltCloudConfigError(
'The defined key_filename \'{0}\' does not exist'.format(
key_filename
)
)
if not __opts__.get('ssh_agent', False) and key_filename is None:
raise SaltCloudConfigError(
'The DigitalOcean driver requires an ssh_key_file and an ssh_key_name '
'because it does not supply a root password upon building the server.'
)
ssh_interface = config.get_cloud_config_value(
'ssh_interface', vm_, __opts__, search_global=False, default='public'
)
if ssh_interface in ['private', 'public']:
log.info("ssh_interface: Setting interface for ssh to %s", ssh_interface)
kwargs['ssh_interface'] = ssh_interface
else:
raise SaltCloudConfigError(
"The DigitalOcean driver requires ssh_interface to be defined as 'public' or 'private'."
)
private_networking = config.get_cloud_config_value(
'private_networking', vm_, __opts__, search_global=False, default=None,
)
if private_networking is not None:
if not isinstance(private_networking, bool):
raise SaltCloudConfigError("'private_networking' should be a boolean value.")
kwargs['private_networking'] = private_networking
if not private_networking and ssh_interface == 'private':
raise SaltCloudConfigError(
"The DigitalOcean driver requires ssh_interface if defined as 'private' "
"then private_networking should be set as 'True'."
)
backups_enabled = config.get_cloud_config_value(
'backups_enabled', vm_, __opts__, search_global=False, default=None,
)
if backups_enabled is not None:
if not isinstance(backups_enabled, bool):
raise SaltCloudConfigError("'backups_enabled' should be a boolean value.")
kwargs['backups'] = backups_enabled
ipv6 = config.get_cloud_config_value(
'ipv6', vm_, __opts__, search_global=False, default=None,
)
if ipv6 is not None:
if not isinstance(ipv6, bool):
raise SaltCloudConfigError("'ipv6' should be a boolean value.")
kwargs['ipv6'] = ipv6
monitoring = config.get_cloud_config_value(
'monitoring', vm_, __opts__, search_global=False, default=None,
)
if monitoring is not None:
if not isinstance(monitoring, bool):
raise SaltCloudConfigError("'monitoring' should be a boolean value.")
kwargs['monitoring'] = monitoring
kwargs['tags'] = config.get_cloud_config_value(
'tags', vm_, __opts__, search_global=False, default=False
)
userdata_file = config.get_cloud_config_value(
'userdata_file', vm_, __opts__, search_global=False, default=None
)
if userdata_file is not None:
try:
with salt.utils.files.fopen(userdata_file, 'r') as fp_:
kwargs['user_data'] = salt.utils.cloud.userdata_template(
__opts__, vm_, salt.utils.stringutils.to_unicode(fp_.read())
)
except Exception as exc:
log.exception(
'Failed to read userdata from %s: %s', userdata_file, exc)
create_dns_record = config.get_cloud_config_value(
'create_dns_record', vm_, __opts__, search_global=False, default=None,
)
if create_dns_record:
log.info('create_dns_record: will attempt to write DNS records')
default_dns_domain = None
dns_domain_name = vm_['name'].split('.')
if len(dns_domain_name) > 2:
log.debug('create_dns_record: inferring default dns_hostname, dns_domain from minion name as FQDN')
default_dns_hostname = '.'.join(dns_domain_name[:-2])
default_dns_domain = '.'.join(dns_domain_name[-2:])
else:
log.debug("create_dns_record: can't infer dns_domain from %s", vm_['name'])
default_dns_hostname = dns_domain_name[0]
dns_hostname = config.get_cloud_config_value(
'dns_hostname', vm_, __opts__, search_global=False, default=default_dns_hostname,
)
dns_domain = config.get_cloud_config_value(
'dns_domain', vm_, __opts__, search_global=False, default=default_dns_domain,
)
if dns_hostname and dns_domain:
log.info('create_dns_record: using dns_hostname="%s", dns_domain="%s"', dns_hostname, dns_domain)
__add_dns_addr__ = lambda t, d: post_dns_record(dns_domain=dns_domain,
name=dns_hostname,
record_type=t,
record_data=d)
log.debug('create_dns_record: %s', __add_dns_addr__)
else:
log.error('create_dns_record: could not determine dns_hostname and/or dns_domain')
raise SaltCloudConfigError(
'\'create_dns_record\' must be a dict specifying "domain" '
'and "hostname" or the minion name must be an FQDN.'
)
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args=__utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
try:
ret = create_node(kwargs)
except Exception as exc:
log.error(
'Error creating %s on DIGITALOCEAN\n\n'
'The following exception was thrown when trying to '
'run the initial deployment: %s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
def __query_node_data(vm_name):
data = show_instance(vm_name, 'action')
if not data:
# Trigger an error in the wait_for_ip function
return False
if data['networks'].get('v4'):
for network in data['networks']['v4']:
if network['type'] == 'public':
return data
return False
try:
data = salt.utils.cloud.wait_for_ip(
__query_node_data,
update_args=(vm_['name'],),
timeout=config.get_cloud_config_value(
'wait_for_ip_timeout', vm_, __opts__, default=10 * 60),
interval=config.get_cloud_config_value(
'wait_for_ip_interval', vm_, __opts__, default=10),
)
except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc:
try:
# It might be already up, let's destroy it!
destroy(vm_['name'])
except SaltCloudSystemExit:
pass
finally:
raise SaltCloudSystemExit(six.text_type(exc))
if not vm_.get('ssh_host'):
vm_['ssh_host'] = None
# add DNS records, set ssh_host, default to first found IP, preferring IPv4 for ssh bootstrap script target
addr_families, dns_arec_types = (('v4', 'v6'), ('A', 'AAAA'))
arec_map = dict(list(zip(addr_families, dns_arec_types)))
for facing, addr_family, ip_address in [(net['type'], family, net['ip_address'])
for family in addr_families
for net in data['networks'][family]]:
log.info('found %s IP%s interface for "%s"', facing, addr_family, ip_address)
dns_rec_type = arec_map[addr_family]
if facing == 'public':
if create_dns_record:
__add_dns_addr__(dns_rec_type, ip_address)
if facing == ssh_interface:
if not vm_['ssh_host']:
vm_['ssh_host'] = ip_address
if vm_['ssh_host'] is None:
raise SaltCloudSystemExit(
'No suitable IP addresses found for ssh minion bootstrapping: {0}'.format(repr(data['networks']))
)
log.debug(
'Found public IP address to use for ssh minion bootstrapping: %s',
vm_['ssh_host']
)
vm_['key_filename'] = key_filename
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
ret.update(data)
log.info('Created Cloud VM \'%s\'', vm_['name'])
log.debug(
'\'%s\' VM creation details:\n%s',
vm_['name'], pprint.pformat(data)
)
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return ret
def query(method='droplets', droplet_id=None, command=None, args=None, http_method='get'):
'''
Make a web call to DigitalOcean
'''
base_path = six.text_type(config.get_cloud_config_value(
'api_root',
get_configured_provider(),
__opts__,
search_global=False,
default='https://api.digitalocean.com/v2'
))
path = '{0}/{1}/'.format(base_path, method)
if droplet_id:
path += '{0}/'.format(droplet_id)
if command:
path += command
if not isinstance(args, dict):
args = {}
personal_access_token = config.get_cloud_config_value(
'personal_access_token', get_configured_provider(), __opts__, search_global=False
)
data = salt.utils.json.dumps(args)
requester = getattr(requests, http_method)
request = requester(path, data=data, headers={'Authorization': 'Bearer ' + personal_access_token, 'Content-Type': 'application/json'})
if request.status_code > 299:
raise SaltCloudSystemExit(
'An error occurred while querying DigitalOcean. HTTP Code: {0} '
'Error: \'{1}\''.format(
request.status_code,
# request.read()
request.text
)
)
log.debug(request.url)
# success without data
if request.status_code == 204:
return True
content = request.text
result = salt.utils.json.loads(content)
if result.get('status', '').lower() == 'error':
raise SaltCloudSystemExit(
pprint.pformat(result.get('error_message', {}))
)
return result
def script(vm_):
'''
Return the script deployment object
'''
deploy_script = salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
return deploy_script
def show_instance(name, call=None):
'''
Show the details from DigitalOcean concerning a droplet
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
node = _get_node(name)
__utils__['cloud.cache_node'](node, __active_provider_name__, __opts__)
return node
def _get_node(name):
attempts = 10
while attempts >= 0:
try:
return list_nodes_full(for_output=False)[name]
except KeyError:
attempts -= 1
log.debug(
'Failed to get the data for node \'%s\'. Remaining '
'attempts: %s', name, attempts
)
# Just a little delay between attempts...
time.sleep(0.5)
return {}
def list_keypairs(call=None):
'''
Return a dict of all available VM locations on the cloud provider with
relevant data
'''
if call != 'function':
log.error(
'The list_keypairs function must be called with -f or --function.'
)
return False
fetch = True
page = 1
ret = {}
while fetch:
items = query(method='account/keys', command='?page=' + six.text_type(page) +
'&per_page=100')
for key_pair in items['ssh_keys']:
name = key_pair['name']
if name in ret:
raise SaltCloudSystemExit(
'A duplicate key pair name, \'{0}\', was found in DigitalOcean\'s '
'key pair list. Please change the key name stored by DigitalOcean. '
'Be sure to adjust the value of \'ssh_key_file\' in your cloud '
'profile or provider configuration, if necessary.'.format(
name
)
)
ret[name] = {}
for item in six.iterkeys(key_pair):
ret[name][item] = six.text_type(key_pair[item])
page += 1
try:
fetch = 'next' in items['links']['pages']
except KeyError:
fetch = False
return ret
def show_keypair(kwargs=None, call=None):
'''
Show the details of an SSH keypair
'''
if call != 'function':
log.error(
'The show_keypair function must be called with -f or --function.'
)
return False
if not kwargs:
kwargs = {}
if 'keyname' not in kwargs:
log.error('A keyname is required.')
return False
keypairs = list_keypairs(call='function')
keyid = keypairs[kwargs['keyname']]['id']
log.debug('Key ID is %s', keyid)
details = query(method='account/keys', command=keyid)
return details
def import_keypair(kwargs=None, call=None):
'''
Upload public key to cloud provider.
Similar to EC2 import_keypair.
.. versionadded:: 2016.11.0
kwargs
file(mandatory): public key file-name
keyname(mandatory): public key name in the provider
'''
with salt.utils.files.fopen(kwargs['file'], 'r') as public_key_filename:
public_key_content = salt.utils.stringutils.to_unicode(public_key_filename.read())
digitalocean_kwargs = {
'name': kwargs['keyname'],
'public_key': public_key_content
}
created_result = create_key(digitalocean_kwargs, call=call)
return created_result
def create_key(kwargs=None, call=None):
'''
Upload a public key
'''
if call != 'function':
log.error(
'The create_key function must be called with -f or --function.'
)
return False
try:
result = query(
method='account',
command='keys',
args={'name': kwargs['name'],
'public_key': kwargs['public_key']},
http_method='post'
)
except KeyError:
log.info('`name` and `public_key` arguments must be specified')
return False
return result
def remove_key(kwargs=None, call=None):
'''
Delete public key
'''
if call != 'function':
log.error(
'The create_key function must be called with -f or --function.'
)
return False
try:
result = query(
method='account',
command='keys/' + kwargs['id'],
http_method='delete'
)
except KeyError:
log.info('`id` argument must be specified')
return False
return result
def get_keyid(keyname):
'''
Return the ID of the keyname
'''
if not keyname:
return None
keypairs = list_keypairs(call='function')
keyid = keypairs[keyname]['id']
if keyid:
return keyid
raise SaltCloudNotFound('The specified ssh key could not be found.')
def destroy(name, call=None):
'''
Destroy a node. Will check termination protection and warn if enabled.
CLI Example:
.. code-block:: bash
salt-cloud --destroy mymachine
'''
if call == 'function':
raise SaltCloudSystemExit(
'The destroy action must be called with -d, --destroy, '
'-a or --action.'
)
__utils__['cloud.fire_event'](
'event',
'destroying instance',
'salt/cloud/{0}/destroying'.format(name),
args={'name': name},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
data = show_instance(name, call='action')
node = query(method='droplets', droplet_id=data['id'], http_method='delete')
## This is all terribly optomistic:
# vm_ = get_vm_config(name=name)
# delete_dns_record = config.get_cloud_config_value(
# 'delete_dns_record', vm_, __opts__, search_global=False, default=None,
# )
# TODO: when _vm config data can be made available, we should honor the configuration settings,
# but until then, we should assume stale DNS records are bad, and default behavior should be to
# delete them if we can. When this is resolved, also resolve the comments a couple of lines below.
delete_dns_record = True
if not isinstance(delete_dns_record, bool):
raise SaltCloudConfigError(
'\'delete_dns_record\' should be a boolean value.'
)
# When the "to do" a few lines up is resolved, remove these lines and use the if/else logic below.
log.debug('Deleting DNS records for %s.', name)
destroy_dns_records(name)
# Until the "to do" from line 754 is taken care of, we don't need this logic.
# if delete_dns_record:
# log.debug('Deleting DNS records for %s.', name)
# destroy_dns_records(name)
# else:
# log.debug('delete_dns_record : %s', delete_dns_record)
# for line in pprint.pformat(dir()).splitlines():
# log.debug('delete context: %s', line)
__utils__['cloud.fire_event'](
'event',
'destroyed instance',
'salt/cloud/{0}/destroyed'.format(name),
args={'name': name},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
if __opts__.get('update_cachedir', False) is True:
__utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__)
return node
def post_dns_record(**kwargs):
'''
Creates a DNS record for the given name if the domain is managed with DO.
'''
if 'kwargs' in kwargs: # flatten kwargs if called via salt-cloud -f
f_kwargs = kwargs['kwargs']
del kwargs['kwargs']
kwargs.update(f_kwargs)
mandatory_kwargs = ('dns_domain', 'name', 'record_type', 'record_data')
for i in mandatory_kwargs:
if kwargs[i]:
pass
else:
error = '{0}="{1}" ## all mandatory args must be provided: {2}'.format(i, kwargs[i], mandatory_kwargs)
raise SaltInvocationError(error)
domain = query(method='domains', droplet_id=kwargs['dns_domain'])
if domain:
result = query(
method='domains',
droplet_id=kwargs['dns_domain'],
command='records',
args={'type': kwargs['record_type'], 'name': kwargs['name'], 'data': kwargs['record_data']},
http_method='post'
)
return result
return False
def destroy_dns_records(fqdn):
'''
Deletes DNS records for the given hostname if the domain is managed with DO.
'''
domain = '.'.join(fqdn.split('.')[-2:])
hostname = '.'.join(fqdn.split('.')[:-2])
# TODO: remove this when the todo on 754 is available
try:
response = query(method='domains', droplet_id=domain, command='records')
except SaltCloudSystemExit:
log.debug('Failed to find domains.')
return False
log.debug("found DNS records: %s", pprint.pformat(response))
records = response['domain_records']
if records:
record_ids = [r['id'] for r in records if r['name'].decode() == hostname]
log.debug("deleting DNS record IDs: %s", record_ids)
for id_ in record_ids:
try:
log.info('deleting DNS record %s', id_)
ret = query(
method='domains',
droplet_id=domain,
command='records/{0}'.format(id_),
http_method='delete'
)
except SaltCloudSystemExit:
log.error('failed to delete DNS domain %s record ID %s.', domain, hostname)
log.debug('DNS deletion REST call returned: %s', pprint.pformat(ret))
return False
def show_pricing(kwargs=None, call=None):
'''
Show pricing for a particular profile. This is only an estimate, based on
unofficial pricing sources.
.. versionadded:: 2015.8.0
CLI Examples:
.. code-block:: bash
salt-cloud -f show_pricing my-digitalocean-config profile=my-profile
'''
profile = __opts__['profiles'].get(kwargs['profile'], {})
if not profile:
return {'Error': 'The requested profile was not found'}
# Make sure the profile belongs to DigitalOcean
provider = profile.get('provider', '0:0')
comps = provider.split(':')
if len(comps) < 2 or comps[1] != 'digitalocean':
return {'Error': 'The requested profile does not belong to DigitalOcean'}
raw = {}
ret = {}
sizes = avail_sizes()
ret['per_hour'] = decimal.Decimal(sizes[profile['size']]['price_hourly'])
ret['per_day'] = ret['per_hour'] * 24
ret['per_week'] = ret['per_day'] * 7
ret['per_month'] = decimal.Decimal(sizes[profile['size']]['price_monthly'])
ret['per_year'] = ret['per_week'] * 52
if kwargs.get('raw', False):
ret['_raw'] = raw
return {profile['profile']: ret}
def list_floating_ips(call=None):
'''
Return a list of the floating ips that are on the provider
.. versionadded:: 2016.3.0
CLI Examples:
.. code-block:: bash
salt-cloud -f list_floating_ips my-digitalocean-config
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_floating_ips function must be called with '
'-f or --function, or with the --list-floating-ips option'
)
fetch = True
page = 1
ret = {}
while fetch:
items = query(method='floating_ips',
command='?page=' + six.text_type(page) + '&per_page=200')
for floating_ip in items['floating_ips']:
ret[floating_ip['ip']] = {}
for item in six.iterkeys(floating_ip):
ret[floating_ip['ip']][item] = floating_ip[item]
page += 1
try:
fetch = 'next' in items['links']['pages']
except KeyError:
fetch = False
return ret
def show_floating_ip(kwargs=None, call=None):
'''
Show the details of a floating IP
.. versionadded:: 2016.3.0
CLI Examples:
.. code-block:: bash
salt-cloud -f show_floating_ip my-digitalocean-config floating_ip='45.55.96.47'
'''
if call != 'function':
log.error(
'The show_floating_ip function must be called with -f or --function.'
)
return False
if not kwargs:
kwargs = {}
if 'floating_ip' not in kwargs:
log.error('A floating IP is required.')
return False
floating_ip = kwargs['floating_ip']
log.debug('Floating ip is %s', floating_ip)
details = query(method='floating_ips', command=floating_ip)
return details
def create_floating_ip(kwargs=None, call=None):
'''
Create a new floating IP
.. versionadded:: 2016.3.0
CLI Examples:
.. code-block:: bash
salt-cloud -f create_floating_ip my-digitalocean-config region='NYC2'
salt-cloud -f create_floating_ip my-digitalocean-config droplet_id='1234567'
'''
if call != 'function':
log.error(
'The create_floating_ip function must be called with -f or --function.'
)
return False
if not kwargs:
kwargs = {}
if 'droplet_id' in kwargs:
result = query(method='floating_ips',
args={'droplet_id': kwargs['droplet_id']},
http_method='post')
return result
elif 'region' in kwargs:
result = query(method='floating_ips',
args={'region': kwargs['region']},
http_method='post')
return result
else:
log.error('A droplet_id or region is required.')
return False
def delete_floating_ip(kwargs=None, call=None):
'''
Delete a floating IP
.. versionadded:: 2016.3.0
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_floating_ip my-digitalocean-config floating_ip='45.55.96.47'
'''
if call != 'function':
log.error(
'The delete_floating_ip function must be called with -f or --function.'
)
return False
if not kwargs:
kwargs = {}
if 'floating_ip' not in kwargs:
log.error('A floating IP is required.')
return False
floating_ip = kwargs['floating_ip']
log.debug('Floating ip is %s', kwargs['floating_ip'])
result = query(method='floating_ips',
command=floating_ip,
http_method='delete')
return result
def assign_floating_ip(kwargs=None, call=None):
'''
Assign a floating IP
.. versionadded:: 2016.3.0
CLI Examples:
.. code-block:: bash
salt-cloud -f assign_floating_ip my-digitalocean-config droplet_id=1234567 floating_ip='45.55.96.47'
'''
if call != 'function':
log.error(
'The assign_floating_ip function must be called with -f or --function.'
)
return False
if not kwargs:
kwargs = {}
if 'floating_ip' and 'droplet_id' not in kwargs:
log.error('A floating IP and droplet_id is required.')
return False
result = query(method='floating_ips',
command=kwargs['floating_ip'] + '/actions',
args={'droplet_id': kwargs['droplet_id'], 'type': 'assign'},
http_method='post')
return result
def unassign_floating_ip(kwargs=None, call=None):
'''
Unassign a floating IP
.. versionadded:: 2016.3.0
CLI Examples:
.. code-block:: bash
salt-cloud -f unassign_floating_ip my-digitalocean-config floating_ip='45.55.96.47'
'''
if call != 'function':
log.error(
'The inassign_floating_ip function must be called with -f or --function.'
)
return False
if not kwargs:
kwargs = {}
if 'floating_ip' not in kwargs:
log.error('A floating IP is required.')
return False
result = query(method='floating_ips',
command=kwargs['floating_ip'] + '/actions',
args={'type': 'unassign'},
http_method='post')
return result
def _list_nodes(full=False, for_output=False):
'''
Helper function to format and parse node data.
'''
fetch = True
page = 1
ret = {}
while fetch:
items = query(method='droplets',
command='?page=' + six.text_type(page) + '&per_page=200')
for node in items['droplets']:
name = node['name']
ret[name] = {}
if full:
ret[name] = _get_full_output(node, for_output=for_output)
else:
public_ips, private_ips = _get_ips(node['networks'])
ret[name] = {
'id': node['id'],
'image': node['image']['name'],
'name': name,
'private_ips': private_ips,
'public_ips': public_ips,
'size': node['size_slug'],
'state': six.text_type(node['status']),
}
page += 1
try:
fetch = 'next' in items['links']['pages']
except KeyError:
fetch = False
return ret
def start(name, call=None):
'''
Start a droplet in DigitalOcean.
.. versionadded:: 2015.8.8
name
The name of the droplet to start.
CLI Example:
.. code-block:: bash
salt-cloud -a start droplet_name
'''
if call != 'action':
raise SaltCloudSystemExit(
'The start action must be called with -a or --action.'
)
data = show_instance(name, call='action')
if data.get('status') == 'active':
return {'success': True,
'action': 'start',
'status': 'active',
'msg': 'Machine is already running.'}
ret = query(droplet_id=data['id'],
command='actions',
args={'type': 'power_on'},
http_method='post')
return {'success': True,
'action': ret['action']['type'],
'state': ret['action']['status']}
def stop(name, call=None):
'''
Stop a droplet in DigitalOcean.
.. versionadded:: 2015.8.8
name
The name of the droplet to stop.
CLI Example:
.. code-block:: bash
salt-cloud -a stop droplet_name
'''
if call != 'action':
raise SaltCloudSystemExit(
'The stop action must be called with -a or --action.'
)
data = show_instance(name, call='action')
if data.get('status') == 'off':
return {'success': True,
'action': 'stop',
'status': 'off',
'msg': 'Machine is already off.'}
ret = query(droplet_id=data['id'],
command='actions',
args={'type': 'shutdown'},
http_method='post')
return {'success': True,
'action': ret['action']['type'],
'state': ret['action']['status']}
def _get_full_output(node, for_output=False):
'''
Helper function for _list_nodes to loop through all node information.
Returns a dictionary containing the full information of a node.
'''
ret = {}
for item in six.iterkeys(node):
value = node[item]
if value is not None and for_output:
value = six.text_type(value)
ret[item] = value
return ret
def _get_ips(networks):
'''
Helper function for list_nodes. Returns public and private ip lists based on a
given network dictionary.
'''
v4s = networks.get('v4')
v6s = networks.get('v6')
public_ips = []
private_ips = []
if v4s:
for item in v4s:
ip_type = item.get('type')
ip_address = item.get('ip_address')
if ip_type == 'public':
public_ips.append(ip_address)
if ip_type == 'private':
private_ips.append(ip_address)
if v6s:
for item in v6s:
ip_type = item.get('type')
ip_address = item.get('ip_address')
if ip_type == 'public':
public_ips.append(ip_address)
if ip_type == 'private':
private_ips.append(ip_address)
return public_ips, private_ips
|
saltstack/salt
|
salt/cloud/clouds/digitalocean.py
|
_get_full_output
|
python
|
def _get_full_output(node, for_output=False):
'''
Helper function for _list_nodes to loop through all node information.
Returns a dictionary containing the full information of a node.
'''
ret = {}
for item in six.iterkeys(node):
value = node[item]
if value is not None and for_output:
value = six.text_type(value)
ret[item] = value
return ret
|
Helper function for _list_nodes to loop through all node information.
Returns a dictionary containing the full information of a node.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/digitalocean.py#L1342-L1353
| null |
# -*- coding: utf-8 -*-
'''
DigitalOcean Cloud Module
=========================
The DigitalOcean cloud module is used to control access to the DigitalOcean VPS system.
Use of this module requires a requires a ``personal_access_token``, an ``ssh_key_file``,
and at least one SSH key name in ``ssh_key_names``. More ``ssh_key_names`` can be added
by separating each key with a comma. The ``personal_access_token`` can be found in the
DigitalOcean web interface in the "Apps & API" section. The SSH key name can be found
under the "SSH Keys" section.
.. code-block:: yaml
# Note: This example is for /etc/salt/cloud.providers or any file in the
# /etc/salt/cloud.providers.d/ directory.
my-digital-ocean-config:
personal_access_token: xxx
ssh_key_file: /path/to/ssh/key/file
ssh_key_names: my-key-name,my-key-name-2
driver: digitalocean
:depends: requests
'''
# Import Python Libs
from __future__ import absolute_import, print_function, unicode_literals
import decimal
import logging
import os
import pprint
import time
# Import Salt Libs
import salt.utils.cloud
import salt.utils.files
import salt.utils.json
import salt.utils.stringutils
import salt.config as config
from salt.exceptions import (
SaltCloudConfigError,
SaltInvocationError,
SaltCloudNotFound,
SaltCloudSystemExit,
SaltCloudExecutionFailure,
SaltCloudExecutionTimeout
)
from salt.ext import six
from salt.ext.six.moves import zip
# Import Third Party Libs
try:
import requests
HAS_REQUESTS = True
except ImportError:
HAS_REQUESTS = False
# Get logging started
log = logging.getLogger(__name__)
__virtualname__ = 'digitalocean'
__virtual_aliases__ = ('digital_ocean', 'do')
# Only load in this module if the DIGITALOCEAN configurations are in place
def __virtual__():
'''
Check for DigitalOcean configurations
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
opts=__opts__,
provider=__active_provider_name__ or __virtualname__,
aliases=__virtual_aliases__,
required_keys=('personal_access_token',)
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'requests': HAS_REQUESTS}
)
def avail_locations(call=None):
'''
Return a dict of all available VM locations on the cloud provider with
relevant data
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
items = query(method='regions')
ret = {}
for region in items['regions']:
ret[region['name']] = {}
for item in six.iterkeys(region):
ret[region['name']][item] = six.text_type(region[item])
return ret
def avail_images(call=None):
'''
Return a list of the images that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
fetch = True
page = 1
ret = {}
while fetch:
items = query(method='images', command='?page=' + six.text_type(page) + '&per_page=200')
for image in items['images']:
ret[image['name']] = {}
for item in six.iterkeys(image):
ret[image['name']][item] = image[item]
page += 1
try:
fetch = 'next' in items['links']['pages']
except KeyError:
fetch = False
return ret
def avail_sizes(call=None):
'''
Return a list of the image sizes that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
items = query(method='sizes', command='?per_page=100')
ret = {}
for size in items['sizes']:
ret[size['slug']] = {}
for item in six.iterkeys(size):
ret[size['slug']][item] = six.text_type(size[item])
return ret
def list_nodes(call=None):
'''
Return a list of the VMs that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
return _list_nodes()
def list_nodes_full(call=None, for_output=True):
'''
Return a list of the VMs that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or --function.'
)
return _list_nodes(full=True, for_output=for_output)
def list_nodes_select(call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
return salt.utils.cloud.list_nodes_select(
list_nodes_full('function'), __opts__['query.selection'], call,
)
def get_image(vm_):
'''
Return the image object to use
'''
images = avail_images()
vm_image = config.get_cloud_config_value(
'image', vm_, __opts__, search_global=False
)
if not isinstance(vm_image, six.string_types):
vm_image = six.text_type(vm_image)
for image in images:
if vm_image in (images[image]['name'],
images[image]['slug'],
images[image]['id']):
if images[image]['slug'] is not None:
return images[image]['slug']
return int(images[image]['id'])
raise SaltCloudNotFound(
'The specified image, \'{0}\', could not be found.'.format(vm_image)
)
def get_size(vm_):
'''
Return the VM's size. Used by create_node().
'''
sizes = avail_sizes()
vm_size = six.text_type(config.get_cloud_config_value(
'size', vm_, __opts__, search_global=False
))
for size in sizes:
if vm_size.lower() == sizes[size]['slug']:
return sizes[size]['slug']
raise SaltCloudNotFound(
'The specified size, \'{0}\', could not be found.'.format(vm_size)
)
def get_location(vm_):
'''
Return the VM's location
'''
locations = avail_locations()
vm_location = six.text_type(config.get_cloud_config_value(
'location', vm_, __opts__, search_global=False
))
for location in locations:
if vm_location in (locations[location]['name'],
locations[location]['slug']):
return locations[location]['slug']
raise SaltCloudNotFound(
'The specified location, \'{0}\', could not be found.'.format(
vm_location
)
)
def create_node(args):
'''
Create a node
'''
node = query(method='droplets', args=args, http_method='post')
return node
def create(vm_):
'''
Create a single VM from a data dict
'''
try:
# Check for required profile parameters before sending any API calls.
if vm_['profile'] and config.is_profile_configured(__opts__,
__active_provider_name__ or 'digitalocean',
vm_['profile'],
vm_=vm_) is False:
return False
except AttributeError:
pass
__utils__['cloud.fire_event'](
'event',
'starting create',
'salt/cloud/{0}/creating'.format(vm_['name']),
args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Creating Cloud VM %s', vm_['name'])
kwargs = {
'name': vm_['name'],
'size': get_size(vm_),
'image': get_image(vm_),
'region': get_location(vm_),
'ssh_keys': [],
'tags': []
}
# backwards compat
ssh_key_name = config.get_cloud_config_value(
'ssh_key_name', vm_, __opts__, search_global=False
)
if ssh_key_name:
kwargs['ssh_keys'].append(get_keyid(ssh_key_name))
ssh_key_names = config.get_cloud_config_value(
'ssh_key_names', vm_, __opts__, search_global=False, default=False
)
if ssh_key_names:
for key in ssh_key_names.split(','):
kwargs['ssh_keys'].append(get_keyid(key))
key_filename = config.get_cloud_config_value(
'ssh_key_file', vm_, __opts__, search_global=False, default=None
)
if key_filename is not None and not os.path.isfile(key_filename):
raise SaltCloudConfigError(
'The defined key_filename \'{0}\' does not exist'.format(
key_filename
)
)
if not __opts__.get('ssh_agent', False) and key_filename is None:
raise SaltCloudConfigError(
'The DigitalOcean driver requires an ssh_key_file and an ssh_key_name '
'because it does not supply a root password upon building the server.'
)
ssh_interface = config.get_cloud_config_value(
'ssh_interface', vm_, __opts__, search_global=False, default='public'
)
if ssh_interface in ['private', 'public']:
log.info("ssh_interface: Setting interface for ssh to %s", ssh_interface)
kwargs['ssh_interface'] = ssh_interface
else:
raise SaltCloudConfigError(
"The DigitalOcean driver requires ssh_interface to be defined as 'public' or 'private'."
)
private_networking = config.get_cloud_config_value(
'private_networking', vm_, __opts__, search_global=False, default=None,
)
if private_networking is not None:
if not isinstance(private_networking, bool):
raise SaltCloudConfigError("'private_networking' should be a boolean value.")
kwargs['private_networking'] = private_networking
if not private_networking and ssh_interface == 'private':
raise SaltCloudConfigError(
"The DigitalOcean driver requires ssh_interface if defined as 'private' "
"then private_networking should be set as 'True'."
)
backups_enabled = config.get_cloud_config_value(
'backups_enabled', vm_, __opts__, search_global=False, default=None,
)
if backups_enabled is not None:
if not isinstance(backups_enabled, bool):
raise SaltCloudConfigError("'backups_enabled' should be a boolean value.")
kwargs['backups'] = backups_enabled
ipv6 = config.get_cloud_config_value(
'ipv6', vm_, __opts__, search_global=False, default=None,
)
if ipv6 is not None:
if not isinstance(ipv6, bool):
raise SaltCloudConfigError("'ipv6' should be a boolean value.")
kwargs['ipv6'] = ipv6
monitoring = config.get_cloud_config_value(
'monitoring', vm_, __opts__, search_global=False, default=None,
)
if monitoring is not None:
if not isinstance(monitoring, bool):
raise SaltCloudConfigError("'monitoring' should be a boolean value.")
kwargs['monitoring'] = monitoring
kwargs['tags'] = config.get_cloud_config_value(
'tags', vm_, __opts__, search_global=False, default=False
)
userdata_file = config.get_cloud_config_value(
'userdata_file', vm_, __opts__, search_global=False, default=None
)
if userdata_file is not None:
try:
with salt.utils.files.fopen(userdata_file, 'r') as fp_:
kwargs['user_data'] = salt.utils.cloud.userdata_template(
__opts__, vm_, salt.utils.stringutils.to_unicode(fp_.read())
)
except Exception as exc:
log.exception(
'Failed to read userdata from %s: %s', userdata_file, exc)
create_dns_record = config.get_cloud_config_value(
'create_dns_record', vm_, __opts__, search_global=False, default=None,
)
if create_dns_record:
log.info('create_dns_record: will attempt to write DNS records')
default_dns_domain = None
dns_domain_name = vm_['name'].split('.')
if len(dns_domain_name) > 2:
log.debug('create_dns_record: inferring default dns_hostname, dns_domain from minion name as FQDN')
default_dns_hostname = '.'.join(dns_domain_name[:-2])
default_dns_domain = '.'.join(dns_domain_name[-2:])
else:
log.debug("create_dns_record: can't infer dns_domain from %s", vm_['name'])
default_dns_hostname = dns_domain_name[0]
dns_hostname = config.get_cloud_config_value(
'dns_hostname', vm_, __opts__, search_global=False, default=default_dns_hostname,
)
dns_domain = config.get_cloud_config_value(
'dns_domain', vm_, __opts__, search_global=False, default=default_dns_domain,
)
if dns_hostname and dns_domain:
log.info('create_dns_record: using dns_hostname="%s", dns_domain="%s"', dns_hostname, dns_domain)
__add_dns_addr__ = lambda t, d: post_dns_record(dns_domain=dns_domain,
name=dns_hostname,
record_type=t,
record_data=d)
log.debug('create_dns_record: %s', __add_dns_addr__)
else:
log.error('create_dns_record: could not determine dns_hostname and/or dns_domain')
raise SaltCloudConfigError(
'\'create_dns_record\' must be a dict specifying "domain" '
'and "hostname" or the minion name must be an FQDN.'
)
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args=__utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
try:
ret = create_node(kwargs)
except Exception as exc:
log.error(
'Error creating %s on DIGITALOCEAN\n\n'
'The following exception was thrown when trying to '
'run the initial deployment: %s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
def __query_node_data(vm_name):
data = show_instance(vm_name, 'action')
if not data:
# Trigger an error in the wait_for_ip function
return False
if data['networks'].get('v4'):
for network in data['networks']['v4']:
if network['type'] == 'public':
return data
return False
try:
data = salt.utils.cloud.wait_for_ip(
__query_node_data,
update_args=(vm_['name'],),
timeout=config.get_cloud_config_value(
'wait_for_ip_timeout', vm_, __opts__, default=10 * 60),
interval=config.get_cloud_config_value(
'wait_for_ip_interval', vm_, __opts__, default=10),
)
except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc:
try:
# It might be already up, let's destroy it!
destroy(vm_['name'])
except SaltCloudSystemExit:
pass
finally:
raise SaltCloudSystemExit(six.text_type(exc))
if not vm_.get('ssh_host'):
vm_['ssh_host'] = None
# add DNS records, set ssh_host, default to first found IP, preferring IPv4 for ssh bootstrap script target
addr_families, dns_arec_types = (('v4', 'v6'), ('A', 'AAAA'))
arec_map = dict(list(zip(addr_families, dns_arec_types)))
for facing, addr_family, ip_address in [(net['type'], family, net['ip_address'])
for family in addr_families
for net in data['networks'][family]]:
log.info('found %s IP%s interface for "%s"', facing, addr_family, ip_address)
dns_rec_type = arec_map[addr_family]
if facing == 'public':
if create_dns_record:
__add_dns_addr__(dns_rec_type, ip_address)
if facing == ssh_interface:
if not vm_['ssh_host']:
vm_['ssh_host'] = ip_address
if vm_['ssh_host'] is None:
raise SaltCloudSystemExit(
'No suitable IP addresses found for ssh minion bootstrapping: {0}'.format(repr(data['networks']))
)
log.debug(
'Found public IP address to use for ssh minion bootstrapping: %s',
vm_['ssh_host']
)
vm_['key_filename'] = key_filename
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
ret.update(data)
log.info('Created Cloud VM \'%s\'', vm_['name'])
log.debug(
'\'%s\' VM creation details:\n%s',
vm_['name'], pprint.pformat(data)
)
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return ret
def query(method='droplets', droplet_id=None, command=None, args=None, http_method='get'):
'''
Make a web call to DigitalOcean
'''
base_path = six.text_type(config.get_cloud_config_value(
'api_root',
get_configured_provider(),
__opts__,
search_global=False,
default='https://api.digitalocean.com/v2'
))
path = '{0}/{1}/'.format(base_path, method)
if droplet_id:
path += '{0}/'.format(droplet_id)
if command:
path += command
if not isinstance(args, dict):
args = {}
personal_access_token = config.get_cloud_config_value(
'personal_access_token', get_configured_provider(), __opts__, search_global=False
)
data = salt.utils.json.dumps(args)
requester = getattr(requests, http_method)
request = requester(path, data=data, headers={'Authorization': 'Bearer ' + personal_access_token, 'Content-Type': 'application/json'})
if request.status_code > 299:
raise SaltCloudSystemExit(
'An error occurred while querying DigitalOcean. HTTP Code: {0} '
'Error: \'{1}\''.format(
request.status_code,
# request.read()
request.text
)
)
log.debug(request.url)
# success without data
if request.status_code == 204:
return True
content = request.text
result = salt.utils.json.loads(content)
if result.get('status', '').lower() == 'error':
raise SaltCloudSystemExit(
pprint.pformat(result.get('error_message', {}))
)
return result
def script(vm_):
'''
Return the script deployment object
'''
deploy_script = salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
return deploy_script
def show_instance(name, call=None):
'''
Show the details from DigitalOcean concerning a droplet
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
node = _get_node(name)
__utils__['cloud.cache_node'](node, __active_provider_name__, __opts__)
return node
def _get_node(name):
attempts = 10
while attempts >= 0:
try:
return list_nodes_full(for_output=False)[name]
except KeyError:
attempts -= 1
log.debug(
'Failed to get the data for node \'%s\'. Remaining '
'attempts: %s', name, attempts
)
# Just a little delay between attempts...
time.sleep(0.5)
return {}
def list_keypairs(call=None):
'''
Return a dict of all available VM locations on the cloud provider with
relevant data
'''
if call != 'function':
log.error(
'The list_keypairs function must be called with -f or --function.'
)
return False
fetch = True
page = 1
ret = {}
while fetch:
items = query(method='account/keys', command='?page=' + six.text_type(page) +
'&per_page=100')
for key_pair in items['ssh_keys']:
name = key_pair['name']
if name in ret:
raise SaltCloudSystemExit(
'A duplicate key pair name, \'{0}\', was found in DigitalOcean\'s '
'key pair list. Please change the key name stored by DigitalOcean. '
'Be sure to adjust the value of \'ssh_key_file\' in your cloud '
'profile or provider configuration, if necessary.'.format(
name
)
)
ret[name] = {}
for item in six.iterkeys(key_pair):
ret[name][item] = six.text_type(key_pair[item])
page += 1
try:
fetch = 'next' in items['links']['pages']
except KeyError:
fetch = False
return ret
def show_keypair(kwargs=None, call=None):
'''
Show the details of an SSH keypair
'''
if call != 'function':
log.error(
'The show_keypair function must be called with -f or --function.'
)
return False
if not kwargs:
kwargs = {}
if 'keyname' not in kwargs:
log.error('A keyname is required.')
return False
keypairs = list_keypairs(call='function')
keyid = keypairs[kwargs['keyname']]['id']
log.debug('Key ID is %s', keyid)
details = query(method='account/keys', command=keyid)
return details
def import_keypair(kwargs=None, call=None):
'''
Upload public key to cloud provider.
Similar to EC2 import_keypair.
.. versionadded:: 2016.11.0
kwargs
file(mandatory): public key file-name
keyname(mandatory): public key name in the provider
'''
with salt.utils.files.fopen(kwargs['file'], 'r') as public_key_filename:
public_key_content = salt.utils.stringutils.to_unicode(public_key_filename.read())
digitalocean_kwargs = {
'name': kwargs['keyname'],
'public_key': public_key_content
}
created_result = create_key(digitalocean_kwargs, call=call)
return created_result
def create_key(kwargs=None, call=None):
'''
Upload a public key
'''
if call != 'function':
log.error(
'The create_key function must be called with -f or --function.'
)
return False
try:
result = query(
method='account',
command='keys',
args={'name': kwargs['name'],
'public_key': kwargs['public_key']},
http_method='post'
)
except KeyError:
log.info('`name` and `public_key` arguments must be specified')
return False
return result
def remove_key(kwargs=None, call=None):
'''
Delete public key
'''
if call != 'function':
log.error(
'The create_key function must be called with -f or --function.'
)
return False
try:
result = query(
method='account',
command='keys/' + kwargs['id'],
http_method='delete'
)
except KeyError:
log.info('`id` argument must be specified')
return False
return result
def get_keyid(keyname):
'''
Return the ID of the keyname
'''
if not keyname:
return None
keypairs = list_keypairs(call='function')
keyid = keypairs[keyname]['id']
if keyid:
return keyid
raise SaltCloudNotFound('The specified ssh key could not be found.')
def destroy(name, call=None):
'''
Destroy a node. Will check termination protection and warn if enabled.
CLI Example:
.. code-block:: bash
salt-cloud --destroy mymachine
'''
if call == 'function':
raise SaltCloudSystemExit(
'The destroy action must be called with -d, --destroy, '
'-a or --action.'
)
__utils__['cloud.fire_event'](
'event',
'destroying instance',
'salt/cloud/{0}/destroying'.format(name),
args={'name': name},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
data = show_instance(name, call='action')
node = query(method='droplets', droplet_id=data['id'], http_method='delete')
## This is all terribly optomistic:
# vm_ = get_vm_config(name=name)
# delete_dns_record = config.get_cloud_config_value(
# 'delete_dns_record', vm_, __opts__, search_global=False, default=None,
# )
# TODO: when _vm config data can be made available, we should honor the configuration settings,
# but until then, we should assume stale DNS records are bad, and default behavior should be to
# delete them if we can. When this is resolved, also resolve the comments a couple of lines below.
delete_dns_record = True
if not isinstance(delete_dns_record, bool):
raise SaltCloudConfigError(
'\'delete_dns_record\' should be a boolean value.'
)
# When the "to do" a few lines up is resolved, remove these lines and use the if/else logic below.
log.debug('Deleting DNS records for %s.', name)
destroy_dns_records(name)
# Until the "to do" from line 754 is taken care of, we don't need this logic.
# if delete_dns_record:
# log.debug('Deleting DNS records for %s.', name)
# destroy_dns_records(name)
# else:
# log.debug('delete_dns_record : %s', delete_dns_record)
# for line in pprint.pformat(dir()).splitlines():
# log.debug('delete context: %s', line)
__utils__['cloud.fire_event'](
'event',
'destroyed instance',
'salt/cloud/{0}/destroyed'.format(name),
args={'name': name},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
if __opts__.get('update_cachedir', False) is True:
__utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__)
return node
def post_dns_record(**kwargs):
'''
Creates a DNS record for the given name if the domain is managed with DO.
'''
if 'kwargs' in kwargs: # flatten kwargs if called via salt-cloud -f
f_kwargs = kwargs['kwargs']
del kwargs['kwargs']
kwargs.update(f_kwargs)
mandatory_kwargs = ('dns_domain', 'name', 'record_type', 'record_data')
for i in mandatory_kwargs:
if kwargs[i]:
pass
else:
error = '{0}="{1}" ## all mandatory args must be provided: {2}'.format(i, kwargs[i], mandatory_kwargs)
raise SaltInvocationError(error)
domain = query(method='domains', droplet_id=kwargs['dns_domain'])
if domain:
result = query(
method='domains',
droplet_id=kwargs['dns_domain'],
command='records',
args={'type': kwargs['record_type'], 'name': kwargs['name'], 'data': kwargs['record_data']},
http_method='post'
)
return result
return False
def destroy_dns_records(fqdn):
'''
Deletes DNS records for the given hostname if the domain is managed with DO.
'''
domain = '.'.join(fqdn.split('.')[-2:])
hostname = '.'.join(fqdn.split('.')[:-2])
# TODO: remove this when the todo on 754 is available
try:
response = query(method='domains', droplet_id=domain, command='records')
except SaltCloudSystemExit:
log.debug('Failed to find domains.')
return False
log.debug("found DNS records: %s", pprint.pformat(response))
records = response['domain_records']
if records:
record_ids = [r['id'] for r in records if r['name'].decode() == hostname]
log.debug("deleting DNS record IDs: %s", record_ids)
for id_ in record_ids:
try:
log.info('deleting DNS record %s', id_)
ret = query(
method='domains',
droplet_id=domain,
command='records/{0}'.format(id_),
http_method='delete'
)
except SaltCloudSystemExit:
log.error('failed to delete DNS domain %s record ID %s.', domain, hostname)
log.debug('DNS deletion REST call returned: %s', pprint.pformat(ret))
return False
def show_pricing(kwargs=None, call=None):
'''
Show pricing for a particular profile. This is only an estimate, based on
unofficial pricing sources.
.. versionadded:: 2015.8.0
CLI Examples:
.. code-block:: bash
salt-cloud -f show_pricing my-digitalocean-config profile=my-profile
'''
profile = __opts__['profiles'].get(kwargs['profile'], {})
if not profile:
return {'Error': 'The requested profile was not found'}
# Make sure the profile belongs to DigitalOcean
provider = profile.get('provider', '0:0')
comps = provider.split(':')
if len(comps) < 2 or comps[1] != 'digitalocean':
return {'Error': 'The requested profile does not belong to DigitalOcean'}
raw = {}
ret = {}
sizes = avail_sizes()
ret['per_hour'] = decimal.Decimal(sizes[profile['size']]['price_hourly'])
ret['per_day'] = ret['per_hour'] * 24
ret['per_week'] = ret['per_day'] * 7
ret['per_month'] = decimal.Decimal(sizes[profile['size']]['price_monthly'])
ret['per_year'] = ret['per_week'] * 52
if kwargs.get('raw', False):
ret['_raw'] = raw
return {profile['profile']: ret}
def list_floating_ips(call=None):
'''
Return a list of the floating ips that are on the provider
.. versionadded:: 2016.3.0
CLI Examples:
.. code-block:: bash
salt-cloud -f list_floating_ips my-digitalocean-config
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_floating_ips function must be called with '
'-f or --function, or with the --list-floating-ips option'
)
fetch = True
page = 1
ret = {}
while fetch:
items = query(method='floating_ips',
command='?page=' + six.text_type(page) + '&per_page=200')
for floating_ip in items['floating_ips']:
ret[floating_ip['ip']] = {}
for item in six.iterkeys(floating_ip):
ret[floating_ip['ip']][item] = floating_ip[item]
page += 1
try:
fetch = 'next' in items['links']['pages']
except KeyError:
fetch = False
return ret
def show_floating_ip(kwargs=None, call=None):
'''
Show the details of a floating IP
.. versionadded:: 2016.3.0
CLI Examples:
.. code-block:: bash
salt-cloud -f show_floating_ip my-digitalocean-config floating_ip='45.55.96.47'
'''
if call != 'function':
log.error(
'The show_floating_ip function must be called with -f or --function.'
)
return False
if not kwargs:
kwargs = {}
if 'floating_ip' not in kwargs:
log.error('A floating IP is required.')
return False
floating_ip = kwargs['floating_ip']
log.debug('Floating ip is %s', floating_ip)
details = query(method='floating_ips', command=floating_ip)
return details
def create_floating_ip(kwargs=None, call=None):
'''
Create a new floating IP
.. versionadded:: 2016.3.0
CLI Examples:
.. code-block:: bash
salt-cloud -f create_floating_ip my-digitalocean-config region='NYC2'
salt-cloud -f create_floating_ip my-digitalocean-config droplet_id='1234567'
'''
if call != 'function':
log.error(
'The create_floating_ip function must be called with -f or --function.'
)
return False
if not kwargs:
kwargs = {}
if 'droplet_id' in kwargs:
result = query(method='floating_ips',
args={'droplet_id': kwargs['droplet_id']},
http_method='post')
return result
elif 'region' in kwargs:
result = query(method='floating_ips',
args={'region': kwargs['region']},
http_method='post')
return result
else:
log.error('A droplet_id or region is required.')
return False
def delete_floating_ip(kwargs=None, call=None):
'''
Delete a floating IP
.. versionadded:: 2016.3.0
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_floating_ip my-digitalocean-config floating_ip='45.55.96.47'
'''
if call != 'function':
log.error(
'The delete_floating_ip function must be called with -f or --function.'
)
return False
if not kwargs:
kwargs = {}
if 'floating_ip' not in kwargs:
log.error('A floating IP is required.')
return False
floating_ip = kwargs['floating_ip']
log.debug('Floating ip is %s', kwargs['floating_ip'])
result = query(method='floating_ips',
command=floating_ip,
http_method='delete')
return result
def assign_floating_ip(kwargs=None, call=None):
'''
Assign a floating IP
.. versionadded:: 2016.3.0
CLI Examples:
.. code-block:: bash
salt-cloud -f assign_floating_ip my-digitalocean-config droplet_id=1234567 floating_ip='45.55.96.47'
'''
if call != 'function':
log.error(
'The assign_floating_ip function must be called with -f or --function.'
)
return False
if not kwargs:
kwargs = {}
if 'floating_ip' and 'droplet_id' not in kwargs:
log.error('A floating IP and droplet_id is required.')
return False
result = query(method='floating_ips',
command=kwargs['floating_ip'] + '/actions',
args={'droplet_id': kwargs['droplet_id'], 'type': 'assign'},
http_method='post')
return result
def unassign_floating_ip(kwargs=None, call=None):
'''
Unassign a floating IP
.. versionadded:: 2016.3.0
CLI Examples:
.. code-block:: bash
salt-cloud -f unassign_floating_ip my-digitalocean-config floating_ip='45.55.96.47'
'''
if call != 'function':
log.error(
'The inassign_floating_ip function must be called with -f or --function.'
)
return False
if not kwargs:
kwargs = {}
if 'floating_ip' not in kwargs:
log.error('A floating IP is required.')
return False
result = query(method='floating_ips',
command=kwargs['floating_ip'] + '/actions',
args={'type': 'unassign'},
http_method='post')
return result
def _list_nodes(full=False, for_output=False):
'''
Helper function to format and parse node data.
'''
fetch = True
page = 1
ret = {}
while fetch:
items = query(method='droplets',
command='?page=' + six.text_type(page) + '&per_page=200')
for node in items['droplets']:
name = node['name']
ret[name] = {}
if full:
ret[name] = _get_full_output(node, for_output=for_output)
else:
public_ips, private_ips = _get_ips(node['networks'])
ret[name] = {
'id': node['id'],
'image': node['image']['name'],
'name': name,
'private_ips': private_ips,
'public_ips': public_ips,
'size': node['size_slug'],
'state': six.text_type(node['status']),
}
page += 1
try:
fetch = 'next' in items['links']['pages']
except KeyError:
fetch = False
return ret
def reboot(name, call=None):
'''
Reboot a droplet in DigitalOcean.
.. versionadded:: 2015.8.8
name
The name of the droplet to restart.
CLI Example:
.. code-block:: bash
salt-cloud -a reboot droplet_name
'''
if call != 'action':
raise SaltCloudSystemExit(
'The restart action must be called with -a or --action.'
)
data = show_instance(name, call='action')
if data.get('status') == 'off':
return {'success': True,
'action': 'stop',
'status': 'off',
'msg': 'Machine is already off.'}
ret = query(droplet_id=data['id'],
command='actions',
args={'type': 'reboot'},
http_method='post')
return {'success': True,
'action': ret['action']['type'],
'state': ret['action']['status']}
def start(name, call=None):
'''
Start a droplet in DigitalOcean.
.. versionadded:: 2015.8.8
name
The name of the droplet to start.
CLI Example:
.. code-block:: bash
salt-cloud -a start droplet_name
'''
if call != 'action':
raise SaltCloudSystemExit(
'The start action must be called with -a or --action.'
)
data = show_instance(name, call='action')
if data.get('status') == 'active':
return {'success': True,
'action': 'start',
'status': 'active',
'msg': 'Machine is already running.'}
ret = query(droplet_id=data['id'],
command='actions',
args={'type': 'power_on'},
http_method='post')
return {'success': True,
'action': ret['action']['type'],
'state': ret['action']['status']}
def stop(name, call=None):
'''
Stop a droplet in DigitalOcean.
.. versionadded:: 2015.8.8
name
The name of the droplet to stop.
CLI Example:
.. code-block:: bash
salt-cloud -a stop droplet_name
'''
if call != 'action':
raise SaltCloudSystemExit(
'The stop action must be called with -a or --action.'
)
data = show_instance(name, call='action')
if data.get('status') == 'off':
return {'success': True,
'action': 'stop',
'status': 'off',
'msg': 'Machine is already off.'}
ret = query(droplet_id=data['id'],
command='actions',
args={'type': 'shutdown'},
http_method='post')
return {'success': True,
'action': ret['action']['type'],
'state': ret['action']['status']}
def _get_ips(networks):
'''
Helper function for list_nodes. Returns public and private ip lists based on a
given network dictionary.
'''
v4s = networks.get('v4')
v6s = networks.get('v6')
public_ips = []
private_ips = []
if v4s:
for item in v4s:
ip_type = item.get('type')
ip_address = item.get('ip_address')
if ip_type == 'public':
public_ips.append(ip_address)
if ip_type == 'private':
private_ips.append(ip_address)
if v6s:
for item in v6s:
ip_type = item.get('type')
ip_address = item.get('ip_address')
if ip_type == 'public':
public_ips.append(ip_address)
if ip_type == 'private':
private_ips.append(ip_address)
return public_ips, private_ips
|
saltstack/salt
|
salt/cloud/clouds/digitalocean.py
|
_get_ips
|
python
|
def _get_ips(networks):
'''
Helper function for list_nodes. Returns public and private ip lists based on a
given network dictionary.
'''
v4s = networks.get('v4')
v6s = networks.get('v6')
public_ips = []
private_ips = []
if v4s:
for item in v4s:
ip_type = item.get('type')
ip_address = item.get('ip_address')
if ip_type == 'public':
public_ips.append(ip_address)
if ip_type == 'private':
private_ips.append(ip_address)
if v6s:
for item in v6s:
ip_type = item.get('type')
ip_address = item.get('ip_address')
if ip_type == 'public':
public_ips.append(ip_address)
if ip_type == 'private':
private_ips.append(ip_address)
return public_ips, private_ips
|
Helper function for list_nodes. Returns public and private ip lists based on a
given network dictionary.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/digitalocean.py#L1356-L1384
| null |
# -*- coding: utf-8 -*-
'''
DigitalOcean Cloud Module
=========================
The DigitalOcean cloud module is used to control access to the DigitalOcean VPS system.
Use of this module requires a requires a ``personal_access_token``, an ``ssh_key_file``,
and at least one SSH key name in ``ssh_key_names``. More ``ssh_key_names`` can be added
by separating each key with a comma. The ``personal_access_token`` can be found in the
DigitalOcean web interface in the "Apps & API" section. The SSH key name can be found
under the "SSH Keys" section.
.. code-block:: yaml
# Note: This example is for /etc/salt/cloud.providers or any file in the
# /etc/salt/cloud.providers.d/ directory.
my-digital-ocean-config:
personal_access_token: xxx
ssh_key_file: /path/to/ssh/key/file
ssh_key_names: my-key-name,my-key-name-2
driver: digitalocean
:depends: requests
'''
# Import Python Libs
from __future__ import absolute_import, print_function, unicode_literals
import decimal
import logging
import os
import pprint
import time
# Import Salt Libs
import salt.utils.cloud
import salt.utils.files
import salt.utils.json
import salt.utils.stringutils
import salt.config as config
from salt.exceptions import (
SaltCloudConfigError,
SaltInvocationError,
SaltCloudNotFound,
SaltCloudSystemExit,
SaltCloudExecutionFailure,
SaltCloudExecutionTimeout
)
from salt.ext import six
from salt.ext.six.moves import zip
# Import Third Party Libs
try:
import requests
HAS_REQUESTS = True
except ImportError:
HAS_REQUESTS = False
# Get logging started
log = logging.getLogger(__name__)
__virtualname__ = 'digitalocean'
__virtual_aliases__ = ('digital_ocean', 'do')
# Only load in this module if the DIGITALOCEAN configurations are in place
def __virtual__():
'''
Check for DigitalOcean configurations
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
opts=__opts__,
provider=__active_provider_name__ or __virtualname__,
aliases=__virtual_aliases__,
required_keys=('personal_access_token',)
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'requests': HAS_REQUESTS}
)
def avail_locations(call=None):
'''
Return a dict of all available VM locations on the cloud provider with
relevant data
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
items = query(method='regions')
ret = {}
for region in items['regions']:
ret[region['name']] = {}
for item in six.iterkeys(region):
ret[region['name']][item] = six.text_type(region[item])
return ret
def avail_images(call=None):
'''
Return a list of the images that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
fetch = True
page = 1
ret = {}
while fetch:
items = query(method='images', command='?page=' + six.text_type(page) + '&per_page=200')
for image in items['images']:
ret[image['name']] = {}
for item in six.iterkeys(image):
ret[image['name']][item] = image[item]
page += 1
try:
fetch = 'next' in items['links']['pages']
except KeyError:
fetch = False
return ret
def avail_sizes(call=None):
'''
Return a list of the image sizes that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
items = query(method='sizes', command='?per_page=100')
ret = {}
for size in items['sizes']:
ret[size['slug']] = {}
for item in six.iterkeys(size):
ret[size['slug']][item] = six.text_type(size[item])
return ret
def list_nodes(call=None):
'''
Return a list of the VMs that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
return _list_nodes()
def list_nodes_full(call=None, for_output=True):
'''
Return a list of the VMs that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or --function.'
)
return _list_nodes(full=True, for_output=for_output)
def list_nodes_select(call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
return salt.utils.cloud.list_nodes_select(
list_nodes_full('function'), __opts__['query.selection'], call,
)
def get_image(vm_):
'''
Return the image object to use
'''
images = avail_images()
vm_image = config.get_cloud_config_value(
'image', vm_, __opts__, search_global=False
)
if not isinstance(vm_image, six.string_types):
vm_image = six.text_type(vm_image)
for image in images:
if vm_image in (images[image]['name'],
images[image]['slug'],
images[image]['id']):
if images[image]['slug'] is not None:
return images[image]['slug']
return int(images[image]['id'])
raise SaltCloudNotFound(
'The specified image, \'{0}\', could not be found.'.format(vm_image)
)
def get_size(vm_):
'''
Return the VM's size. Used by create_node().
'''
sizes = avail_sizes()
vm_size = six.text_type(config.get_cloud_config_value(
'size', vm_, __opts__, search_global=False
))
for size in sizes:
if vm_size.lower() == sizes[size]['slug']:
return sizes[size]['slug']
raise SaltCloudNotFound(
'The specified size, \'{0}\', could not be found.'.format(vm_size)
)
def get_location(vm_):
'''
Return the VM's location
'''
locations = avail_locations()
vm_location = six.text_type(config.get_cloud_config_value(
'location', vm_, __opts__, search_global=False
))
for location in locations:
if vm_location in (locations[location]['name'],
locations[location]['slug']):
return locations[location]['slug']
raise SaltCloudNotFound(
'The specified location, \'{0}\', could not be found.'.format(
vm_location
)
)
def create_node(args):
'''
Create a node
'''
node = query(method='droplets', args=args, http_method='post')
return node
def create(vm_):
'''
Create a single VM from a data dict
'''
try:
# Check for required profile parameters before sending any API calls.
if vm_['profile'] and config.is_profile_configured(__opts__,
__active_provider_name__ or 'digitalocean',
vm_['profile'],
vm_=vm_) is False:
return False
except AttributeError:
pass
__utils__['cloud.fire_event'](
'event',
'starting create',
'salt/cloud/{0}/creating'.format(vm_['name']),
args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Creating Cloud VM %s', vm_['name'])
kwargs = {
'name': vm_['name'],
'size': get_size(vm_),
'image': get_image(vm_),
'region': get_location(vm_),
'ssh_keys': [],
'tags': []
}
# backwards compat
ssh_key_name = config.get_cloud_config_value(
'ssh_key_name', vm_, __opts__, search_global=False
)
if ssh_key_name:
kwargs['ssh_keys'].append(get_keyid(ssh_key_name))
ssh_key_names = config.get_cloud_config_value(
'ssh_key_names', vm_, __opts__, search_global=False, default=False
)
if ssh_key_names:
for key in ssh_key_names.split(','):
kwargs['ssh_keys'].append(get_keyid(key))
key_filename = config.get_cloud_config_value(
'ssh_key_file', vm_, __opts__, search_global=False, default=None
)
if key_filename is not None and not os.path.isfile(key_filename):
raise SaltCloudConfigError(
'The defined key_filename \'{0}\' does not exist'.format(
key_filename
)
)
if not __opts__.get('ssh_agent', False) and key_filename is None:
raise SaltCloudConfigError(
'The DigitalOcean driver requires an ssh_key_file and an ssh_key_name '
'because it does not supply a root password upon building the server.'
)
ssh_interface = config.get_cloud_config_value(
'ssh_interface', vm_, __opts__, search_global=False, default='public'
)
if ssh_interface in ['private', 'public']:
log.info("ssh_interface: Setting interface for ssh to %s", ssh_interface)
kwargs['ssh_interface'] = ssh_interface
else:
raise SaltCloudConfigError(
"The DigitalOcean driver requires ssh_interface to be defined as 'public' or 'private'."
)
private_networking = config.get_cloud_config_value(
'private_networking', vm_, __opts__, search_global=False, default=None,
)
if private_networking is not None:
if not isinstance(private_networking, bool):
raise SaltCloudConfigError("'private_networking' should be a boolean value.")
kwargs['private_networking'] = private_networking
if not private_networking and ssh_interface == 'private':
raise SaltCloudConfigError(
"The DigitalOcean driver requires ssh_interface if defined as 'private' "
"then private_networking should be set as 'True'."
)
backups_enabled = config.get_cloud_config_value(
'backups_enabled', vm_, __opts__, search_global=False, default=None,
)
if backups_enabled is not None:
if not isinstance(backups_enabled, bool):
raise SaltCloudConfigError("'backups_enabled' should be a boolean value.")
kwargs['backups'] = backups_enabled
ipv6 = config.get_cloud_config_value(
'ipv6', vm_, __opts__, search_global=False, default=None,
)
if ipv6 is not None:
if not isinstance(ipv6, bool):
raise SaltCloudConfigError("'ipv6' should be a boolean value.")
kwargs['ipv6'] = ipv6
monitoring = config.get_cloud_config_value(
'monitoring', vm_, __opts__, search_global=False, default=None,
)
if monitoring is not None:
if not isinstance(monitoring, bool):
raise SaltCloudConfigError("'monitoring' should be a boolean value.")
kwargs['monitoring'] = monitoring
kwargs['tags'] = config.get_cloud_config_value(
'tags', vm_, __opts__, search_global=False, default=False
)
userdata_file = config.get_cloud_config_value(
'userdata_file', vm_, __opts__, search_global=False, default=None
)
if userdata_file is not None:
try:
with salt.utils.files.fopen(userdata_file, 'r') as fp_:
kwargs['user_data'] = salt.utils.cloud.userdata_template(
__opts__, vm_, salt.utils.stringutils.to_unicode(fp_.read())
)
except Exception as exc:
log.exception(
'Failed to read userdata from %s: %s', userdata_file, exc)
create_dns_record = config.get_cloud_config_value(
'create_dns_record', vm_, __opts__, search_global=False, default=None,
)
if create_dns_record:
log.info('create_dns_record: will attempt to write DNS records')
default_dns_domain = None
dns_domain_name = vm_['name'].split('.')
if len(dns_domain_name) > 2:
log.debug('create_dns_record: inferring default dns_hostname, dns_domain from minion name as FQDN')
default_dns_hostname = '.'.join(dns_domain_name[:-2])
default_dns_domain = '.'.join(dns_domain_name[-2:])
else:
log.debug("create_dns_record: can't infer dns_domain from %s", vm_['name'])
default_dns_hostname = dns_domain_name[0]
dns_hostname = config.get_cloud_config_value(
'dns_hostname', vm_, __opts__, search_global=False, default=default_dns_hostname,
)
dns_domain = config.get_cloud_config_value(
'dns_domain', vm_, __opts__, search_global=False, default=default_dns_domain,
)
if dns_hostname and dns_domain:
log.info('create_dns_record: using dns_hostname="%s", dns_domain="%s"', dns_hostname, dns_domain)
__add_dns_addr__ = lambda t, d: post_dns_record(dns_domain=dns_domain,
name=dns_hostname,
record_type=t,
record_data=d)
log.debug('create_dns_record: %s', __add_dns_addr__)
else:
log.error('create_dns_record: could not determine dns_hostname and/or dns_domain')
raise SaltCloudConfigError(
'\'create_dns_record\' must be a dict specifying "domain" '
'and "hostname" or the minion name must be an FQDN.'
)
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args=__utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
try:
ret = create_node(kwargs)
except Exception as exc:
log.error(
'Error creating %s on DIGITALOCEAN\n\n'
'The following exception was thrown when trying to '
'run the initial deployment: %s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
def __query_node_data(vm_name):
data = show_instance(vm_name, 'action')
if not data:
# Trigger an error in the wait_for_ip function
return False
if data['networks'].get('v4'):
for network in data['networks']['v4']:
if network['type'] == 'public':
return data
return False
try:
data = salt.utils.cloud.wait_for_ip(
__query_node_data,
update_args=(vm_['name'],),
timeout=config.get_cloud_config_value(
'wait_for_ip_timeout', vm_, __opts__, default=10 * 60),
interval=config.get_cloud_config_value(
'wait_for_ip_interval', vm_, __opts__, default=10),
)
except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc:
try:
# It might be already up, let's destroy it!
destroy(vm_['name'])
except SaltCloudSystemExit:
pass
finally:
raise SaltCloudSystemExit(six.text_type(exc))
if not vm_.get('ssh_host'):
vm_['ssh_host'] = None
# add DNS records, set ssh_host, default to first found IP, preferring IPv4 for ssh bootstrap script target
addr_families, dns_arec_types = (('v4', 'v6'), ('A', 'AAAA'))
arec_map = dict(list(zip(addr_families, dns_arec_types)))
for facing, addr_family, ip_address in [(net['type'], family, net['ip_address'])
for family in addr_families
for net in data['networks'][family]]:
log.info('found %s IP%s interface for "%s"', facing, addr_family, ip_address)
dns_rec_type = arec_map[addr_family]
if facing == 'public':
if create_dns_record:
__add_dns_addr__(dns_rec_type, ip_address)
if facing == ssh_interface:
if not vm_['ssh_host']:
vm_['ssh_host'] = ip_address
if vm_['ssh_host'] is None:
raise SaltCloudSystemExit(
'No suitable IP addresses found for ssh minion bootstrapping: {0}'.format(repr(data['networks']))
)
log.debug(
'Found public IP address to use for ssh minion bootstrapping: %s',
vm_['ssh_host']
)
vm_['key_filename'] = key_filename
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
ret.update(data)
log.info('Created Cloud VM \'%s\'', vm_['name'])
log.debug(
'\'%s\' VM creation details:\n%s',
vm_['name'], pprint.pformat(data)
)
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return ret
def query(method='droplets', droplet_id=None, command=None, args=None, http_method='get'):
'''
Make a web call to DigitalOcean
'''
base_path = six.text_type(config.get_cloud_config_value(
'api_root',
get_configured_provider(),
__opts__,
search_global=False,
default='https://api.digitalocean.com/v2'
))
path = '{0}/{1}/'.format(base_path, method)
if droplet_id:
path += '{0}/'.format(droplet_id)
if command:
path += command
if not isinstance(args, dict):
args = {}
personal_access_token = config.get_cloud_config_value(
'personal_access_token', get_configured_provider(), __opts__, search_global=False
)
data = salt.utils.json.dumps(args)
requester = getattr(requests, http_method)
request = requester(path, data=data, headers={'Authorization': 'Bearer ' + personal_access_token, 'Content-Type': 'application/json'})
if request.status_code > 299:
raise SaltCloudSystemExit(
'An error occurred while querying DigitalOcean. HTTP Code: {0} '
'Error: \'{1}\''.format(
request.status_code,
# request.read()
request.text
)
)
log.debug(request.url)
# success without data
if request.status_code == 204:
return True
content = request.text
result = salt.utils.json.loads(content)
if result.get('status', '').lower() == 'error':
raise SaltCloudSystemExit(
pprint.pformat(result.get('error_message', {}))
)
return result
def script(vm_):
'''
Return the script deployment object
'''
deploy_script = salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
return deploy_script
def show_instance(name, call=None):
'''
Show the details from DigitalOcean concerning a droplet
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
node = _get_node(name)
__utils__['cloud.cache_node'](node, __active_provider_name__, __opts__)
return node
def _get_node(name):
attempts = 10
while attempts >= 0:
try:
return list_nodes_full(for_output=False)[name]
except KeyError:
attempts -= 1
log.debug(
'Failed to get the data for node \'%s\'. Remaining '
'attempts: %s', name, attempts
)
# Just a little delay between attempts...
time.sleep(0.5)
return {}
def list_keypairs(call=None):
'''
Return a dict of all available VM locations on the cloud provider with
relevant data
'''
if call != 'function':
log.error(
'The list_keypairs function must be called with -f or --function.'
)
return False
fetch = True
page = 1
ret = {}
while fetch:
items = query(method='account/keys', command='?page=' + six.text_type(page) +
'&per_page=100')
for key_pair in items['ssh_keys']:
name = key_pair['name']
if name in ret:
raise SaltCloudSystemExit(
'A duplicate key pair name, \'{0}\', was found in DigitalOcean\'s '
'key pair list. Please change the key name stored by DigitalOcean. '
'Be sure to adjust the value of \'ssh_key_file\' in your cloud '
'profile or provider configuration, if necessary.'.format(
name
)
)
ret[name] = {}
for item in six.iterkeys(key_pair):
ret[name][item] = six.text_type(key_pair[item])
page += 1
try:
fetch = 'next' in items['links']['pages']
except KeyError:
fetch = False
return ret
def show_keypair(kwargs=None, call=None):
'''
Show the details of an SSH keypair
'''
if call != 'function':
log.error(
'The show_keypair function must be called with -f or --function.'
)
return False
if not kwargs:
kwargs = {}
if 'keyname' not in kwargs:
log.error('A keyname is required.')
return False
keypairs = list_keypairs(call='function')
keyid = keypairs[kwargs['keyname']]['id']
log.debug('Key ID is %s', keyid)
details = query(method='account/keys', command=keyid)
return details
def import_keypair(kwargs=None, call=None):
'''
Upload public key to cloud provider.
Similar to EC2 import_keypair.
.. versionadded:: 2016.11.0
kwargs
file(mandatory): public key file-name
keyname(mandatory): public key name in the provider
'''
with salt.utils.files.fopen(kwargs['file'], 'r') as public_key_filename:
public_key_content = salt.utils.stringutils.to_unicode(public_key_filename.read())
digitalocean_kwargs = {
'name': kwargs['keyname'],
'public_key': public_key_content
}
created_result = create_key(digitalocean_kwargs, call=call)
return created_result
def create_key(kwargs=None, call=None):
'''
Upload a public key
'''
if call != 'function':
log.error(
'The create_key function must be called with -f or --function.'
)
return False
try:
result = query(
method='account',
command='keys',
args={'name': kwargs['name'],
'public_key': kwargs['public_key']},
http_method='post'
)
except KeyError:
log.info('`name` and `public_key` arguments must be specified')
return False
return result
def remove_key(kwargs=None, call=None):
'''
Delete public key
'''
if call != 'function':
log.error(
'The create_key function must be called with -f or --function.'
)
return False
try:
result = query(
method='account',
command='keys/' + kwargs['id'],
http_method='delete'
)
except KeyError:
log.info('`id` argument must be specified')
return False
return result
def get_keyid(keyname):
'''
Return the ID of the keyname
'''
if not keyname:
return None
keypairs = list_keypairs(call='function')
keyid = keypairs[keyname]['id']
if keyid:
return keyid
raise SaltCloudNotFound('The specified ssh key could not be found.')
def destroy(name, call=None):
'''
Destroy a node. Will check termination protection and warn if enabled.
CLI Example:
.. code-block:: bash
salt-cloud --destroy mymachine
'''
if call == 'function':
raise SaltCloudSystemExit(
'The destroy action must be called with -d, --destroy, '
'-a or --action.'
)
__utils__['cloud.fire_event'](
'event',
'destroying instance',
'salt/cloud/{0}/destroying'.format(name),
args={'name': name},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
data = show_instance(name, call='action')
node = query(method='droplets', droplet_id=data['id'], http_method='delete')
## This is all terribly optomistic:
# vm_ = get_vm_config(name=name)
# delete_dns_record = config.get_cloud_config_value(
# 'delete_dns_record', vm_, __opts__, search_global=False, default=None,
# )
# TODO: when _vm config data can be made available, we should honor the configuration settings,
# but until then, we should assume stale DNS records are bad, and default behavior should be to
# delete them if we can. When this is resolved, also resolve the comments a couple of lines below.
delete_dns_record = True
if not isinstance(delete_dns_record, bool):
raise SaltCloudConfigError(
'\'delete_dns_record\' should be a boolean value.'
)
# When the "to do" a few lines up is resolved, remove these lines and use the if/else logic below.
log.debug('Deleting DNS records for %s.', name)
destroy_dns_records(name)
# Until the "to do" from line 754 is taken care of, we don't need this logic.
# if delete_dns_record:
# log.debug('Deleting DNS records for %s.', name)
# destroy_dns_records(name)
# else:
# log.debug('delete_dns_record : %s', delete_dns_record)
# for line in pprint.pformat(dir()).splitlines():
# log.debug('delete context: %s', line)
__utils__['cloud.fire_event'](
'event',
'destroyed instance',
'salt/cloud/{0}/destroyed'.format(name),
args={'name': name},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
if __opts__.get('update_cachedir', False) is True:
__utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__)
return node
def post_dns_record(**kwargs):
'''
Creates a DNS record for the given name if the domain is managed with DO.
'''
if 'kwargs' in kwargs: # flatten kwargs if called via salt-cloud -f
f_kwargs = kwargs['kwargs']
del kwargs['kwargs']
kwargs.update(f_kwargs)
mandatory_kwargs = ('dns_domain', 'name', 'record_type', 'record_data')
for i in mandatory_kwargs:
if kwargs[i]:
pass
else:
error = '{0}="{1}" ## all mandatory args must be provided: {2}'.format(i, kwargs[i], mandatory_kwargs)
raise SaltInvocationError(error)
domain = query(method='domains', droplet_id=kwargs['dns_domain'])
if domain:
result = query(
method='domains',
droplet_id=kwargs['dns_domain'],
command='records',
args={'type': kwargs['record_type'], 'name': kwargs['name'], 'data': kwargs['record_data']},
http_method='post'
)
return result
return False
def destroy_dns_records(fqdn):
'''
Deletes DNS records for the given hostname if the domain is managed with DO.
'''
domain = '.'.join(fqdn.split('.')[-2:])
hostname = '.'.join(fqdn.split('.')[:-2])
# TODO: remove this when the todo on 754 is available
try:
response = query(method='domains', droplet_id=domain, command='records')
except SaltCloudSystemExit:
log.debug('Failed to find domains.')
return False
log.debug("found DNS records: %s", pprint.pformat(response))
records = response['domain_records']
if records:
record_ids = [r['id'] for r in records if r['name'].decode() == hostname]
log.debug("deleting DNS record IDs: %s", record_ids)
for id_ in record_ids:
try:
log.info('deleting DNS record %s', id_)
ret = query(
method='domains',
droplet_id=domain,
command='records/{0}'.format(id_),
http_method='delete'
)
except SaltCloudSystemExit:
log.error('failed to delete DNS domain %s record ID %s.', domain, hostname)
log.debug('DNS deletion REST call returned: %s', pprint.pformat(ret))
return False
def show_pricing(kwargs=None, call=None):
'''
Show pricing for a particular profile. This is only an estimate, based on
unofficial pricing sources.
.. versionadded:: 2015.8.0
CLI Examples:
.. code-block:: bash
salt-cloud -f show_pricing my-digitalocean-config profile=my-profile
'''
profile = __opts__['profiles'].get(kwargs['profile'], {})
if not profile:
return {'Error': 'The requested profile was not found'}
# Make sure the profile belongs to DigitalOcean
provider = profile.get('provider', '0:0')
comps = provider.split(':')
if len(comps) < 2 or comps[1] != 'digitalocean':
return {'Error': 'The requested profile does not belong to DigitalOcean'}
raw = {}
ret = {}
sizes = avail_sizes()
ret['per_hour'] = decimal.Decimal(sizes[profile['size']]['price_hourly'])
ret['per_day'] = ret['per_hour'] * 24
ret['per_week'] = ret['per_day'] * 7
ret['per_month'] = decimal.Decimal(sizes[profile['size']]['price_monthly'])
ret['per_year'] = ret['per_week'] * 52
if kwargs.get('raw', False):
ret['_raw'] = raw
return {profile['profile']: ret}
def list_floating_ips(call=None):
'''
Return a list of the floating ips that are on the provider
.. versionadded:: 2016.3.0
CLI Examples:
.. code-block:: bash
salt-cloud -f list_floating_ips my-digitalocean-config
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_floating_ips function must be called with '
'-f or --function, or with the --list-floating-ips option'
)
fetch = True
page = 1
ret = {}
while fetch:
items = query(method='floating_ips',
command='?page=' + six.text_type(page) + '&per_page=200')
for floating_ip in items['floating_ips']:
ret[floating_ip['ip']] = {}
for item in six.iterkeys(floating_ip):
ret[floating_ip['ip']][item] = floating_ip[item]
page += 1
try:
fetch = 'next' in items['links']['pages']
except KeyError:
fetch = False
return ret
def show_floating_ip(kwargs=None, call=None):
'''
Show the details of a floating IP
.. versionadded:: 2016.3.0
CLI Examples:
.. code-block:: bash
salt-cloud -f show_floating_ip my-digitalocean-config floating_ip='45.55.96.47'
'''
if call != 'function':
log.error(
'The show_floating_ip function must be called with -f or --function.'
)
return False
if not kwargs:
kwargs = {}
if 'floating_ip' not in kwargs:
log.error('A floating IP is required.')
return False
floating_ip = kwargs['floating_ip']
log.debug('Floating ip is %s', floating_ip)
details = query(method='floating_ips', command=floating_ip)
return details
def create_floating_ip(kwargs=None, call=None):
'''
Create a new floating IP
.. versionadded:: 2016.3.0
CLI Examples:
.. code-block:: bash
salt-cloud -f create_floating_ip my-digitalocean-config region='NYC2'
salt-cloud -f create_floating_ip my-digitalocean-config droplet_id='1234567'
'''
if call != 'function':
log.error(
'The create_floating_ip function must be called with -f or --function.'
)
return False
if not kwargs:
kwargs = {}
if 'droplet_id' in kwargs:
result = query(method='floating_ips',
args={'droplet_id': kwargs['droplet_id']},
http_method='post')
return result
elif 'region' in kwargs:
result = query(method='floating_ips',
args={'region': kwargs['region']},
http_method='post')
return result
else:
log.error('A droplet_id or region is required.')
return False
def delete_floating_ip(kwargs=None, call=None):
'''
Delete a floating IP
.. versionadded:: 2016.3.0
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_floating_ip my-digitalocean-config floating_ip='45.55.96.47'
'''
if call != 'function':
log.error(
'The delete_floating_ip function must be called with -f or --function.'
)
return False
if not kwargs:
kwargs = {}
if 'floating_ip' not in kwargs:
log.error('A floating IP is required.')
return False
floating_ip = kwargs['floating_ip']
log.debug('Floating ip is %s', kwargs['floating_ip'])
result = query(method='floating_ips',
command=floating_ip,
http_method='delete')
return result
def assign_floating_ip(kwargs=None, call=None):
'''
Assign a floating IP
.. versionadded:: 2016.3.0
CLI Examples:
.. code-block:: bash
salt-cloud -f assign_floating_ip my-digitalocean-config droplet_id=1234567 floating_ip='45.55.96.47'
'''
if call != 'function':
log.error(
'The assign_floating_ip function must be called with -f or --function.'
)
return False
if not kwargs:
kwargs = {}
if 'floating_ip' and 'droplet_id' not in kwargs:
log.error('A floating IP and droplet_id is required.')
return False
result = query(method='floating_ips',
command=kwargs['floating_ip'] + '/actions',
args={'droplet_id': kwargs['droplet_id'], 'type': 'assign'},
http_method='post')
return result
def unassign_floating_ip(kwargs=None, call=None):
'''
Unassign a floating IP
.. versionadded:: 2016.3.0
CLI Examples:
.. code-block:: bash
salt-cloud -f unassign_floating_ip my-digitalocean-config floating_ip='45.55.96.47'
'''
if call != 'function':
log.error(
'The inassign_floating_ip function must be called with -f or --function.'
)
return False
if not kwargs:
kwargs = {}
if 'floating_ip' not in kwargs:
log.error('A floating IP is required.')
return False
result = query(method='floating_ips',
command=kwargs['floating_ip'] + '/actions',
args={'type': 'unassign'},
http_method='post')
return result
def _list_nodes(full=False, for_output=False):
'''
Helper function to format and parse node data.
'''
fetch = True
page = 1
ret = {}
while fetch:
items = query(method='droplets',
command='?page=' + six.text_type(page) + '&per_page=200')
for node in items['droplets']:
name = node['name']
ret[name] = {}
if full:
ret[name] = _get_full_output(node, for_output=for_output)
else:
public_ips, private_ips = _get_ips(node['networks'])
ret[name] = {
'id': node['id'],
'image': node['image']['name'],
'name': name,
'private_ips': private_ips,
'public_ips': public_ips,
'size': node['size_slug'],
'state': six.text_type(node['status']),
}
page += 1
try:
fetch = 'next' in items['links']['pages']
except KeyError:
fetch = False
return ret
def reboot(name, call=None):
'''
Reboot a droplet in DigitalOcean.
.. versionadded:: 2015.8.8
name
The name of the droplet to restart.
CLI Example:
.. code-block:: bash
salt-cloud -a reboot droplet_name
'''
if call != 'action':
raise SaltCloudSystemExit(
'The restart action must be called with -a or --action.'
)
data = show_instance(name, call='action')
if data.get('status') == 'off':
return {'success': True,
'action': 'stop',
'status': 'off',
'msg': 'Machine is already off.'}
ret = query(droplet_id=data['id'],
command='actions',
args={'type': 'reboot'},
http_method='post')
return {'success': True,
'action': ret['action']['type'],
'state': ret['action']['status']}
def start(name, call=None):
'''
Start a droplet in DigitalOcean.
.. versionadded:: 2015.8.8
name
The name of the droplet to start.
CLI Example:
.. code-block:: bash
salt-cloud -a start droplet_name
'''
if call != 'action':
raise SaltCloudSystemExit(
'The start action must be called with -a or --action.'
)
data = show_instance(name, call='action')
if data.get('status') == 'active':
return {'success': True,
'action': 'start',
'status': 'active',
'msg': 'Machine is already running.'}
ret = query(droplet_id=data['id'],
command='actions',
args={'type': 'power_on'},
http_method='post')
return {'success': True,
'action': ret['action']['type'],
'state': ret['action']['status']}
def stop(name, call=None):
'''
Stop a droplet in DigitalOcean.
.. versionadded:: 2015.8.8
name
The name of the droplet to stop.
CLI Example:
.. code-block:: bash
salt-cloud -a stop droplet_name
'''
if call != 'action':
raise SaltCloudSystemExit(
'The stop action must be called with -a or --action.'
)
data = show_instance(name, call='action')
if data.get('status') == 'off':
return {'success': True,
'action': 'stop',
'status': 'off',
'msg': 'Machine is already off.'}
ret = query(droplet_id=data['id'],
command='actions',
args={'type': 'shutdown'},
http_method='post')
return {'success': True,
'action': ret['action']['type'],
'state': ret['action']['status']}
def _get_full_output(node, for_output=False):
'''
Helper function for _list_nodes to loop through all node information.
Returns a dictionary containing the full information of a node.
'''
ret = {}
for item in six.iterkeys(node):
value = node[item]
if value is not None and for_output:
value = six.text_type(value)
ret[item] = value
return ret
|
saltstack/salt
|
salt/modules/deb_postgres.py
|
cluster_create
|
python
|
def cluster_create(version,
name='main',
port=None,
locale=None,
encoding=None,
datadir=None,
allow_group_access=None,
data_checksums=None,
wal_segsize=None):
'''
Adds a cluster to the Postgres server.
.. warning:
Only works for debian family distros so far.
CLI Example:
.. code-block:: bash
salt '*' postgres.cluster_create '9.3'
salt '*' postgres.cluster_create '9.3' 'main'
salt '*' postgres.cluster_create '9.3' locale='fr_FR'
salt '*' postgres.cluster_create '11' data_checksums=True wal_segsize='32'
'''
cmd = [salt.utils.path.which('pg_createcluster')]
if port:
cmd += ['--port', six.text_type(port)]
if locale:
cmd += ['--locale', locale]
if encoding:
cmd += ['--encoding', encoding]
if datadir:
cmd += ['--datadir', datadir]
cmd += [version, name]
# initdb-specific options are passed after '--'
if allow_group_access or data_checksums or wal_segsize:
cmd += ['--']
if allow_group_access is True:
cmd += ['--allow-group-access']
if data_checksums is True:
cmd += ['--data-checksums']
if wal_segsize:
cmd += ['--wal-segsize', wal_segsize]
cmdstr = ' '.join([pipes.quote(c) for c in cmd])
ret = __salt__['cmd.run_all'](cmdstr, python_shell=False)
if ret.get('retcode', 0) != 0:
log.error('Error creating a Postgresql cluster %s/%s', version, name)
return False
return ret
|
Adds a cluster to the Postgres server.
.. warning:
Only works for debian family distros so far.
CLI Example:
.. code-block:: bash
salt '*' postgres.cluster_create '9.3'
salt '*' postgres.cluster_create '9.3' 'main'
salt '*' postgres.cluster_create '9.3' locale='fr_FR'
salt '*' postgres.cluster_create '11' data_checksums=True wal_segsize='32'
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/deb_postgres.py#L32-L85
| null |
# -*- coding: utf-8 -*-
'''
Module to provide Postgres compatibility to salt for debian family specific tools.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import pipes
# Import salt libs
import salt.utils.path
from salt.ext import six
# Import 3rd-party libs
log = logging.getLogger(__name__)
__virtualname__ = 'postgres'
def __virtual__():
'''
Only load this module if the pg_createcluster bin exists
'''
if salt.utils.path.which('pg_createcluster'):
return __virtualname__
return (False, 'postgres execution module not loaded: pg_createcluste command not found.')
def cluster_list(verbose=False):
'''
Return a list of cluster of Postgres server (tuples of version and name).
CLI Example:
.. code-block:: bash
salt '*' postgres.cluster_list
salt '*' postgres.cluster_list verbose=True
'''
cmd = [salt.utils.path.which('pg_lsclusters'), '--no-header']
ret = __salt__['cmd.run_all'](' '.join([pipes.quote(c) for c in cmd]))
if ret.get('retcode', 0) != 0:
log.error('Error listing clusters')
cluster_dict = _parse_pg_lscluster(ret['stdout'])
if verbose:
return cluster_dict
return cluster_dict.keys()
def cluster_exists(version,
name='main'):
'''
Checks if a given version and name of a cluster exists.
CLI Example:
.. code-block:: bash
salt '*' postgres.cluster_exists '9.3'
salt '*' postgres.cluster_exists '9.3' 'main'
'''
return '{0}/{1}'.format(version, name) in cluster_list()
def cluster_remove(version,
name='main',
stop=False):
'''
Remove a cluster on a Postgres server. By default it doesn't try
to stop the cluster.
CLI Example:
.. code-block:: bash
salt '*' postgres.cluster_remove '9.3'
salt '*' postgres.cluster_remove '9.3' 'main'
salt '*' postgres.cluster_remove '9.3' 'main' stop=True
'''
cmd = [salt.utils.path.which('pg_dropcluster')]
if stop:
cmd += ['--stop']
cmd += [version, name]
cmdstr = ' '.join([pipes.quote(c) for c in cmd])
ret = __salt__['cmd.run_all'](cmdstr, python_shell=False)
# FIXME - return Boolean ?
if ret.get('retcode', 0) != 0:
log.error('Error removing a Postgresql cluster %s/%s', version, name)
else:
ret['changes'] = ('Successfully removed'
' cluster {0}/{1}').format(version, name)
return ret
def _parse_pg_lscluster(output):
'''
Helper function to parse the output of pg_lscluster
'''
cluster_dict = {}
for line in output.splitlines():
version, name, port, status, user, datadir, log = (
line.split())
cluster_dict['{0}/{1}'.format(version, name)] = {
'port': int(port),
'status': status,
'user': user,
'datadir': datadir,
'log': log}
return cluster_dict
|
saltstack/salt
|
salt/modules/deb_postgres.py
|
cluster_list
|
python
|
def cluster_list(verbose=False):
'''
Return a list of cluster of Postgres server (tuples of version and name).
CLI Example:
.. code-block:: bash
salt '*' postgres.cluster_list
salt '*' postgres.cluster_list verbose=True
'''
cmd = [salt.utils.path.which('pg_lsclusters'), '--no-header']
ret = __salt__['cmd.run_all'](' '.join([pipes.quote(c) for c in cmd]))
if ret.get('retcode', 0) != 0:
log.error('Error listing clusters')
cluster_dict = _parse_pg_lscluster(ret['stdout'])
if verbose:
return cluster_dict
return cluster_dict.keys()
|
Return a list of cluster of Postgres server (tuples of version and name).
CLI Example:
.. code-block:: bash
salt '*' postgres.cluster_list
salt '*' postgres.cluster_list verbose=True
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/deb_postgres.py#L88-L107
|
[
"def _parse_pg_lscluster(output):\n '''\n Helper function to parse the output of pg_lscluster\n '''\n cluster_dict = {}\n for line in output.splitlines():\n version, name, port, status, user, datadir, log = (\n line.split())\n cluster_dict['{0}/{1}'.format(version, name)] = {\n 'port': int(port),\n 'status': status,\n 'user': user,\n 'datadir': datadir,\n 'log': log}\n return cluster_dict\n"
] |
# -*- coding: utf-8 -*-
'''
Module to provide Postgres compatibility to salt for debian family specific tools.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import pipes
# Import salt libs
import salt.utils.path
from salt.ext import six
# Import 3rd-party libs
log = logging.getLogger(__name__)
__virtualname__ = 'postgres'
def __virtual__():
'''
Only load this module if the pg_createcluster bin exists
'''
if salt.utils.path.which('pg_createcluster'):
return __virtualname__
return (False, 'postgres execution module not loaded: pg_createcluste command not found.')
def cluster_create(version,
name='main',
port=None,
locale=None,
encoding=None,
datadir=None,
allow_group_access=None,
data_checksums=None,
wal_segsize=None):
'''
Adds a cluster to the Postgres server.
.. warning:
Only works for debian family distros so far.
CLI Example:
.. code-block:: bash
salt '*' postgres.cluster_create '9.3'
salt '*' postgres.cluster_create '9.3' 'main'
salt '*' postgres.cluster_create '9.3' locale='fr_FR'
salt '*' postgres.cluster_create '11' data_checksums=True wal_segsize='32'
'''
cmd = [salt.utils.path.which('pg_createcluster')]
if port:
cmd += ['--port', six.text_type(port)]
if locale:
cmd += ['--locale', locale]
if encoding:
cmd += ['--encoding', encoding]
if datadir:
cmd += ['--datadir', datadir]
cmd += [version, name]
# initdb-specific options are passed after '--'
if allow_group_access or data_checksums or wal_segsize:
cmd += ['--']
if allow_group_access is True:
cmd += ['--allow-group-access']
if data_checksums is True:
cmd += ['--data-checksums']
if wal_segsize:
cmd += ['--wal-segsize', wal_segsize]
cmdstr = ' '.join([pipes.quote(c) for c in cmd])
ret = __salt__['cmd.run_all'](cmdstr, python_shell=False)
if ret.get('retcode', 0) != 0:
log.error('Error creating a Postgresql cluster %s/%s', version, name)
return False
return ret
def cluster_exists(version,
name='main'):
'''
Checks if a given version and name of a cluster exists.
CLI Example:
.. code-block:: bash
salt '*' postgres.cluster_exists '9.3'
salt '*' postgres.cluster_exists '9.3' 'main'
'''
return '{0}/{1}'.format(version, name) in cluster_list()
def cluster_remove(version,
name='main',
stop=False):
'''
Remove a cluster on a Postgres server. By default it doesn't try
to stop the cluster.
CLI Example:
.. code-block:: bash
salt '*' postgres.cluster_remove '9.3'
salt '*' postgres.cluster_remove '9.3' 'main'
salt '*' postgres.cluster_remove '9.3' 'main' stop=True
'''
cmd = [salt.utils.path.which('pg_dropcluster')]
if stop:
cmd += ['--stop']
cmd += [version, name]
cmdstr = ' '.join([pipes.quote(c) for c in cmd])
ret = __salt__['cmd.run_all'](cmdstr, python_shell=False)
# FIXME - return Boolean ?
if ret.get('retcode', 0) != 0:
log.error('Error removing a Postgresql cluster %s/%s', version, name)
else:
ret['changes'] = ('Successfully removed'
' cluster {0}/{1}').format(version, name)
return ret
def _parse_pg_lscluster(output):
'''
Helper function to parse the output of pg_lscluster
'''
cluster_dict = {}
for line in output.splitlines():
version, name, port, status, user, datadir, log = (
line.split())
cluster_dict['{0}/{1}'.format(version, name)] = {
'port': int(port),
'status': status,
'user': user,
'datadir': datadir,
'log': log}
return cluster_dict
|
saltstack/salt
|
salt/modules/deb_postgres.py
|
cluster_remove
|
python
|
def cluster_remove(version,
name='main',
stop=False):
'''
Remove a cluster on a Postgres server. By default it doesn't try
to stop the cluster.
CLI Example:
.. code-block:: bash
salt '*' postgres.cluster_remove '9.3'
salt '*' postgres.cluster_remove '9.3' 'main'
salt '*' postgres.cluster_remove '9.3' 'main' stop=True
'''
cmd = [salt.utils.path.which('pg_dropcluster')]
if stop:
cmd += ['--stop']
cmd += [version, name]
cmdstr = ' '.join([pipes.quote(c) for c in cmd])
ret = __salt__['cmd.run_all'](cmdstr, python_shell=False)
# FIXME - return Boolean ?
if ret.get('retcode', 0) != 0:
log.error('Error removing a Postgresql cluster %s/%s', version, name)
else:
ret['changes'] = ('Successfully removed'
' cluster {0}/{1}').format(version, name)
return ret
|
Remove a cluster on a Postgres server. By default it doesn't try
to stop the cluster.
CLI Example:
.. code-block:: bash
salt '*' postgres.cluster_remove '9.3'
salt '*' postgres.cluster_remove '9.3' 'main'
salt '*' postgres.cluster_remove '9.3' 'main' stop=True
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/deb_postgres.py#L126-L156
| null |
# -*- coding: utf-8 -*-
'''
Module to provide Postgres compatibility to salt for debian family specific tools.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import pipes
# Import salt libs
import salt.utils.path
from salt.ext import six
# Import 3rd-party libs
log = logging.getLogger(__name__)
__virtualname__ = 'postgres'
def __virtual__():
'''
Only load this module if the pg_createcluster bin exists
'''
if salt.utils.path.which('pg_createcluster'):
return __virtualname__
return (False, 'postgres execution module not loaded: pg_createcluste command not found.')
def cluster_create(version,
name='main',
port=None,
locale=None,
encoding=None,
datadir=None,
allow_group_access=None,
data_checksums=None,
wal_segsize=None):
'''
Adds a cluster to the Postgres server.
.. warning:
Only works for debian family distros so far.
CLI Example:
.. code-block:: bash
salt '*' postgres.cluster_create '9.3'
salt '*' postgres.cluster_create '9.3' 'main'
salt '*' postgres.cluster_create '9.3' locale='fr_FR'
salt '*' postgres.cluster_create '11' data_checksums=True wal_segsize='32'
'''
cmd = [salt.utils.path.which('pg_createcluster')]
if port:
cmd += ['--port', six.text_type(port)]
if locale:
cmd += ['--locale', locale]
if encoding:
cmd += ['--encoding', encoding]
if datadir:
cmd += ['--datadir', datadir]
cmd += [version, name]
# initdb-specific options are passed after '--'
if allow_group_access or data_checksums or wal_segsize:
cmd += ['--']
if allow_group_access is True:
cmd += ['--allow-group-access']
if data_checksums is True:
cmd += ['--data-checksums']
if wal_segsize:
cmd += ['--wal-segsize', wal_segsize]
cmdstr = ' '.join([pipes.quote(c) for c in cmd])
ret = __salt__['cmd.run_all'](cmdstr, python_shell=False)
if ret.get('retcode', 0) != 0:
log.error('Error creating a Postgresql cluster %s/%s', version, name)
return False
return ret
def cluster_list(verbose=False):
'''
Return a list of cluster of Postgres server (tuples of version and name).
CLI Example:
.. code-block:: bash
salt '*' postgres.cluster_list
salt '*' postgres.cluster_list verbose=True
'''
cmd = [salt.utils.path.which('pg_lsclusters'), '--no-header']
ret = __salt__['cmd.run_all'](' '.join([pipes.quote(c) for c in cmd]))
if ret.get('retcode', 0) != 0:
log.error('Error listing clusters')
cluster_dict = _parse_pg_lscluster(ret['stdout'])
if verbose:
return cluster_dict
return cluster_dict.keys()
def cluster_exists(version,
name='main'):
'''
Checks if a given version and name of a cluster exists.
CLI Example:
.. code-block:: bash
salt '*' postgres.cluster_exists '9.3'
salt '*' postgres.cluster_exists '9.3' 'main'
'''
return '{0}/{1}'.format(version, name) in cluster_list()
def _parse_pg_lscluster(output):
'''
Helper function to parse the output of pg_lscluster
'''
cluster_dict = {}
for line in output.splitlines():
version, name, port, status, user, datadir, log = (
line.split())
cluster_dict['{0}/{1}'.format(version, name)] = {
'port': int(port),
'status': status,
'user': user,
'datadir': datadir,
'log': log}
return cluster_dict
|
saltstack/salt
|
salt/modules/deb_postgres.py
|
_parse_pg_lscluster
|
python
|
def _parse_pg_lscluster(output):
'''
Helper function to parse the output of pg_lscluster
'''
cluster_dict = {}
for line in output.splitlines():
version, name, port, status, user, datadir, log = (
line.split())
cluster_dict['{0}/{1}'.format(version, name)] = {
'port': int(port),
'status': status,
'user': user,
'datadir': datadir,
'log': log}
return cluster_dict
|
Helper function to parse the output of pg_lscluster
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/deb_postgres.py#L159-L173
| null |
# -*- coding: utf-8 -*-
'''
Module to provide Postgres compatibility to salt for debian family specific tools.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import pipes
# Import salt libs
import salt.utils.path
from salt.ext import six
# Import 3rd-party libs
log = logging.getLogger(__name__)
__virtualname__ = 'postgres'
def __virtual__():
'''
Only load this module if the pg_createcluster bin exists
'''
if salt.utils.path.which('pg_createcluster'):
return __virtualname__
return (False, 'postgres execution module not loaded: pg_createcluste command not found.')
def cluster_create(version,
name='main',
port=None,
locale=None,
encoding=None,
datadir=None,
allow_group_access=None,
data_checksums=None,
wal_segsize=None):
'''
Adds a cluster to the Postgres server.
.. warning:
Only works for debian family distros so far.
CLI Example:
.. code-block:: bash
salt '*' postgres.cluster_create '9.3'
salt '*' postgres.cluster_create '9.3' 'main'
salt '*' postgres.cluster_create '9.3' locale='fr_FR'
salt '*' postgres.cluster_create '11' data_checksums=True wal_segsize='32'
'''
cmd = [salt.utils.path.which('pg_createcluster')]
if port:
cmd += ['--port', six.text_type(port)]
if locale:
cmd += ['--locale', locale]
if encoding:
cmd += ['--encoding', encoding]
if datadir:
cmd += ['--datadir', datadir]
cmd += [version, name]
# initdb-specific options are passed after '--'
if allow_group_access or data_checksums or wal_segsize:
cmd += ['--']
if allow_group_access is True:
cmd += ['--allow-group-access']
if data_checksums is True:
cmd += ['--data-checksums']
if wal_segsize:
cmd += ['--wal-segsize', wal_segsize]
cmdstr = ' '.join([pipes.quote(c) for c in cmd])
ret = __salt__['cmd.run_all'](cmdstr, python_shell=False)
if ret.get('retcode', 0) != 0:
log.error('Error creating a Postgresql cluster %s/%s', version, name)
return False
return ret
def cluster_list(verbose=False):
'''
Return a list of cluster of Postgres server (tuples of version and name).
CLI Example:
.. code-block:: bash
salt '*' postgres.cluster_list
salt '*' postgres.cluster_list verbose=True
'''
cmd = [salt.utils.path.which('pg_lsclusters'), '--no-header']
ret = __salt__['cmd.run_all'](' '.join([pipes.quote(c) for c in cmd]))
if ret.get('retcode', 0) != 0:
log.error('Error listing clusters')
cluster_dict = _parse_pg_lscluster(ret['stdout'])
if verbose:
return cluster_dict
return cluster_dict.keys()
def cluster_exists(version,
name='main'):
'''
Checks if a given version and name of a cluster exists.
CLI Example:
.. code-block:: bash
salt '*' postgres.cluster_exists '9.3'
salt '*' postgres.cluster_exists '9.3' 'main'
'''
return '{0}/{1}'.format(version, name) in cluster_list()
def cluster_remove(version,
name='main',
stop=False):
'''
Remove a cluster on a Postgres server. By default it doesn't try
to stop the cluster.
CLI Example:
.. code-block:: bash
salt '*' postgres.cluster_remove '9.3'
salt '*' postgres.cluster_remove '9.3' 'main'
salt '*' postgres.cluster_remove '9.3' 'main' stop=True
'''
cmd = [salt.utils.path.which('pg_dropcluster')]
if stop:
cmd += ['--stop']
cmd += [version, name]
cmdstr = ' '.join([pipes.quote(c) for c in cmd])
ret = __salt__['cmd.run_all'](cmdstr, python_shell=False)
# FIXME - return Boolean ?
if ret.get('retcode', 0) != 0:
log.error('Error removing a Postgresql cluster %s/%s', version, name)
else:
ret['changes'] = ('Successfully removed'
' cluster {0}/{1}').format(version, name)
return ret
|
saltstack/salt
|
salt/grains/esxi.py
|
_find_credentials
|
python
|
def _find_credentials(host):
'''
Cycle through all the possible credentials and return the first one that
works.
'''
user_names = [__pillar__['proxy'].get('username', 'root')]
passwords = __pillar__['proxy']['passwords']
for user in user_names:
for password in passwords:
try:
# Try to authenticate with the given user/password combination
ret = salt.modules.vsphere.system_info(host=host,
username=user,
password=password)
except SaltSystemExit:
# If we can't authenticate, continue on to try the next password.
continue
# If we have data returned from above, we've successfully authenticated.
if ret:
return user, password
# We've reached the end of the list without successfully authenticating.
raise SaltSystemExit('Cannot complete login due to an incorrect user name or password.')
|
Cycle through all the possible credentials and return the first one that
works.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/grains/esxi.py#L59-L80
| null |
# -*- coding: utf-8 -*-
'''
Generate baseline proxy minion grains for ESXi hosts.
.. versionadded:: 2015.8.4
'''
# Import Python Libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import Salt Libs
from salt.exceptions import SaltSystemExit
import salt.utils.platform
import salt.modules.vsphere
__proxyenabled__ = ['esxi']
__virtualname__ = 'esxi'
log = logging.getLogger(__file__)
GRAINS_CACHE = {}
def __virtual__():
try:
if salt.utils.platform.is_proxy() and __opts__['proxy']['proxytype'] == 'esxi':
return __virtualname__
except KeyError:
pass
return False
def esxi():
return _grains()
def kernel():
return {'kernel': 'proxy'}
def os():
if not GRAINS_CACHE:
GRAINS_CACHE.update(_grains())
try:
return {'os': GRAINS_CACHE.get('fullName')}
except AttributeError:
return {'os': 'Unknown'}
def os_family():
return {'os_family': 'proxy'}
def _grains():
'''
Get the grains from the proxied device.
'''
try:
host = __pillar__['proxy']['host']
if host:
username, password = _find_credentials(host)
protocol = __pillar__['proxy'].get('protocol')
port = __pillar__['proxy'].get('port')
ret = salt.modules.vsphere.system_info(host=host,
username=username,
password=password,
protocol=protocol,
port=port)
GRAINS_CACHE.update(ret)
except KeyError:
pass
return GRAINS_CACHE
|
saltstack/salt
|
salt/grains/esxi.py
|
_grains
|
python
|
def _grains():
'''
Get the grains from the proxied device.
'''
try:
host = __pillar__['proxy']['host']
if host:
username, password = _find_credentials(host)
protocol = __pillar__['proxy'].get('protocol')
port = __pillar__['proxy'].get('port')
ret = salt.modules.vsphere.system_info(host=host,
username=username,
password=password,
protocol=protocol,
port=port)
GRAINS_CACHE.update(ret)
except KeyError:
pass
return GRAINS_CACHE
|
Get the grains from the proxied device.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/grains/esxi.py#L83-L102
|
[
"def _find_credentials(host):\n '''\n Cycle through all the possible credentials and return the first one that\n works.\n '''\n user_names = [__pillar__['proxy'].get('username', 'root')]\n passwords = __pillar__['proxy']['passwords']\n for user in user_names:\n for password in passwords:\n try:\n # Try to authenticate with the given user/password combination\n ret = salt.modules.vsphere.system_info(host=host,\n username=user,\n password=password)\n except SaltSystemExit:\n # If we can't authenticate, continue on to try the next password.\n continue\n # If we have data returned from above, we've successfully authenticated.\n if ret:\n return user, password\n # We've reached the end of the list without successfully authenticating.\n raise SaltSystemExit('Cannot complete login due to an incorrect user name or password.')\n"
] |
# -*- coding: utf-8 -*-
'''
Generate baseline proxy minion grains for ESXi hosts.
.. versionadded:: 2015.8.4
'''
# Import Python Libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import Salt Libs
from salt.exceptions import SaltSystemExit
import salt.utils.platform
import salt.modules.vsphere
__proxyenabled__ = ['esxi']
__virtualname__ = 'esxi'
log = logging.getLogger(__file__)
GRAINS_CACHE = {}
def __virtual__():
try:
if salt.utils.platform.is_proxy() and __opts__['proxy']['proxytype'] == 'esxi':
return __virtualname__
except KeyError:
pass
return False
def esxi():
return _grains()
def kernel():
return {'kernel': 'proxy'}
def os():
if not GRAINS_CACHE:
GRAINS_CACHE.update(_grains())
try:
return {'os': GRAINS_CACHE.get('fullName')}
except AttributeError:
return {'os': 'Unknown'}
def os_family():
return {'os_family': 'proxy'}
def _find_credentials(host):
'''
Cycle through all the possible credentials and return the first one that
works.
'''
user_names = [__pillar__['proxy'].get('username', 'root')]
passwords = __pillar__['proxy']['passwords']
for user in user_names:
for password in passwords:
try:
# Try to authenticate with the given user/password combination
ret = salt.modules.vsphere.system_info(host=host,
username=user,
password=password)
except SaltSystemExit:
# If we can't authenticate, continue on to try the next password.
continue
# If we have data returned from above, we've successfully authenticated.
if ret:
return user, password
# We've reached the end of the list without successfully authenticating.
raise SaltSystemExit('Cannot complete login due to an incorrect user name or password.')
|
saltstack/salt
|
salt/pillar/etcd_pillar.py
|
ext_pillar
|
python
|
def ext_pillar(minion_id,
pillar, # pylint: disable=W0613
conf):
'''
Check etcd for all data
'''
comps = conf.split()
profile = None
if comps[0]:
profile = comps[0]
client = salt.utils.etcd_util.get_conn(__opts__, profile)
path = '/'
if len(comps) > 1 and comps[1].startswith('root='):
path = comps[1].replace('root=', '')
# put the minion's ID in the path if necessary
path %= {
'minion_id': minion_id
}
try:
pillar = salt.utils.etcd_util.tree(client, path)
except KeyError:
log.error('No such key in etcd profile %s: %s', profile, path)
pillar = {}
return pillar
|
Check etcd for all data
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/pillar/etcd_pillar.py#L86-L114
|
[
"def tree(client, path):\n return client.tree(path)\n",
"def get_conn(opts, profile=None, **kwargs):\n client = EtcdClient(opts, profile, **kwargs)\n return client\n"
] |
# -*- coding: utf-8 -*-
'''
Use etcd data as a Pillar source
.. versionadded:: 2014.7.0
:depends: - python-etcd
In order to use an etcd server, a profile must be created in the master
configuration file:
.. code-block:: yaml
my_etcd_config:
etcd.host: 127.0.0.1
etcd.port: 4001
After the profile is created, configure the external pillar system to use it.
Optionally, a root may be specified.
.. code-block:: yaml
ext_pillar:
- etcd: my_etcd_config
ext_pillar:
- etcd: my_etcd_config root=/salt
Using these configuration profiles, multiple etcd sources may also be used:
.. code-block:: yaml
ext_pillar:
- etcd: my_etcd_config
- etcd: my_other_etcd_config
The ``minion_id`` may be used in the ``root`` path to expose minion-specific
information stored in etcd.
.. code-block:: yaml
ext_pillar:
- etcd: my_etcd_config root=/salt/%(minion_id)s
Minion-specific values may override shared values when the minion-specific root
appears after the shared root:
.. code-block:: yaml
ext_pillar:
- etcd: my_etcd_config root=/salt-shared
- etcd: my_other_etcd_config root=/salt-private/%(minion_id)s
Using the configuration above, the following commands could be used to share a
key with all minions but override its value for a specific minion::
etcdctl set /salt-shared/mykey my_value
etcdctl set /salt-private/special_minion_id/mykey my_other_value
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import logging
# Import third party libs
try:
import salt.utils.etcd_util
HAS_LIBS = True
except ImportError:
HAS_LIBS = False
__virtualname__ = 'etcd'
# Set up logging
log = logging.getLogger(__name__)
def __virtual__():
'''
Only return if python-etcd is installed
'''
return __virtualname__ if HAS_LIBS else False
|
saltstack/salt
|
salt/states/csf.py
|
rule_absent
|
python
|
def rule_absent(name,
method,
port=None,
proto='tcp',
direction='in',
port_origin='d',
ip_origin='s',
ttl=None,
reload=False):
'''
Ensure iptable is not present.
name
The ip address or CIDR for the rule.
method
The type of rule. Either 'allow' or 'deny'.
port
Optional port to be open or closed for the
iptables rule.
proto
The protocol. Either 'tcp', 'udp'.
Only applicable if port is specified.
direction
The diretion of traffic to apply the rule to.
Either 'in', or 'out'. Only applicable if
port is specified.
port_origin
Specifies either the source or destination
port is relevant for this rule. Only applicable
if port is specified. Either 's', or 'd'.
ip_origin
Specifies whether the ip in this rule refers to
the source or destination ip. Either 's', or
'd'. Only applicable if port is specified.
ttl
How long the rule should exist. If supplied,
`csf.tempallow()` or csf.tempdeny()` are used.
reload
Reload the csf service after applying this rule.
Default false.
'''
ip = name
ret = {'name': name,
'changes': {},
'result': True,
'comment': 'Rule not present.'}
exists = __salt__['csf.exists'](method,
ip,
port=port,
proto=proto,
direction=direction,
port_origin=port_origin,
ip_origin=ip_origin,
ttl=ttl)
if not exists:
return ret
else:
rule = __salt__['csf.remove_rule'](method=method,
ip=ip,
port=port,
proto=proto,
direction=direction,
port_origin=port_origin,
ip_origin=ip_origin,
comment='',
ttl=ttl)
if rule:
comment = 'Rule has been removed.'
if reload:
if __salt__['csf.reload']():
comment += ' Csf reloaded.'
else:
comment += 'Csf unable to be reloaded.'
ret['comment'] = comment
ret['changes']['Rule'] = 'Removed'
return ret
|
Ensure iptable is not present.
name
The ip address or CIDR for the rule.
method
The type of rule. Either 'allow' or 'deny'.
port
Optional port to be open or closed for the
iptables rule.
proto
The protocol. Either 'tcp', 'udp'.
Only applicable if port is specified.
direction
The diretion of traffic to apply the rule to.
Either 'in', or 'out'. Only applicable if
port is specified.
port_origin
Specifies either the source or destination
port is relevant for this rule. Only applicable
if port is specified. Either 's', or 'd'.
ip_origin
Specifies whether the ip in this rule refers to
the source or destination ip. Either 's', or
'd'. Only applicable if port is specified.
ttl
How long the rule should exist. If supplied,
`csf.tempallow()` or csf.tempdeny()` are used.
reload
Reload the csf service after applying this rule.
Default false.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/csf.py#L131-L217
| null |
# -*- coding: utf-8 -*-
'''
CSF Ip tables management
========================
:depends: - csf utility
:configuration: See http://download.configserver.com/csf/install.txt
for setup instructions.
.. code-block:: yaml
Simply allow/deny rules:
csf.rule_present:
ip: 1.2.3.4
method: allow
''' # pylint: disable=W0105
# Import Python Libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import Salt Libs
from salt.ext import six
log = logging.getLogger(__name__)
def __virtual__():
return 'csf'
def rule_present(name,
method,
port=None,
proto='tcp',
direction='in',
port_origin='d',
ip_origin='s',
ttl=None,
comment='',
reload=False):
'''
Ensure iptable rule exists.
name
The ip address or CIDR for the rule.
method
The type of rule. Either 'allow' or 'deny'.
port
Optional port to be open or closed for the
iptables rule.
proto
The protocol. Either 'tcp', or 'udp'.
Only applicable if port is specified.
direction
The diretion of traffic to apply the rule to.
Either 'in', or 'out'. Only applicable if
port is specified.
port_origin
Specifies either the source or destination
port is relevant for this rule. Only applicable
if port is specified. Either 's', or 'd'.
ip_origin
Specifies whether the ip in this rule refers to
the source or destination ip. Either 's', or
'd'. Only applicable if port is specified.
ttl
How long the rule should exist. If supplied,
`csf.tempallow()` or csf.tempdeny()` are used.
comment
An optional comment to appear after the rule
as a #comment .
reload
Reload the csf service after applying this rule.
Default false.
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': 'Rule already exists.'}
ip = name
# Check if rule is already present
exists = __salt__['csf.exists'](method=method,
ip=ip,
port=port,
proto=proto,
direction=direction,
port_origin=port_origin,
ip_origin=ip_origin,
ttl=ttl,
comment=comment)
if exists:
return ret
else:
if ttl:
method = 'temp{0}'.format(method)
func = __salt__['csf.{0}'.format(method)]
rule = func(ip,
port=port,
proto=proto,
direction=direction,
port_origin=port_origin,
ip_origin=ip_origin,
ttl=ttl,
comment=comment)
if rule:
comment = 'Rule has been added.'
if reload:
if __salt__['csf.reload']():
comment += ' Csf reloaded.'
else:
comment += ' Unable to reload csf.'
ret['result'] = False
ret['comment'] = comment
ret['changes']['Rule'] = 'Created'
return ret
def ports_open(name, ports, proto='tcp', direction='in'):
'''
Ensure ports are open for a protocol, in a direction.
e.g. - proto='tcp', direction='in' would set the values
for TCP_IN in the csf.conf file.
ports
A list of ports that should be open.
proto
The protocol. May be one of 'tcp', 'udp',
'tcp6', or 'udp6'.
direction
Choose 'in', 'out', or both to indicate the port
should be opened for inbound traffic, outbound
traffic, or both.
'''
ports = list(six.moves.map(six.text_type, ports))
diff = False
ret = {'name': ','.join(ports),
'changes': {},
'result': True,
'comment': 'Ports open.'}
current_ports = __salt__['csf.get_ports'](proto=proto, direction=direction)
direction = direction.upper()
directions = __salt__['csf.build_directions'](direction)
for direction in directions:
log.trace('current_ports[direction]: %s', current_ports[direction])
log.trace('ports: %s', ports)
if current_ports[direction] != ports:
diff = True
if diff:
result = __salt__['csf.allow_ports'](ports, proto=proto, direction=direction)
ret['changes']['Ports'] = 'Changed'
ret['comment'] = result
return ret
def nics_skip(name, nics, ipv6):
'''
Alias for :mod:`csf.nics_skipped <salt.states.csf.nics_skipped>`
'''
return nics_skipped(name, nics=nics, ipv6=ipv6)
def nics_skipped(name, nics, ipv6=False):
'''
name
Meaningless arg, but required for state.
nics
A list of nics to skip.
ipv6
Boolean. Set to true if you want to skip
the ipv6 interface. Default false (ipv4).
'''
ret = {'name': ','.join(nics),
'changes': {},
'result': True,
'comment': 'NICs skipped.'}
current_skipped_nics = __salt__['csf.get_skipped_nics'](ipv6=ipv6)
if nics == current_skipped_nics:
return ret
result = __salt__['csf.skip_nics'](nics, ipv6=ipv6)
ret['changes']['Skipped NICs'] = 'Changed'
return ret
def testing_on(name, reload=False):
'''
Ensure testing mode is enabled in csf.
reload
Reload CSF after changing the testing status.
Default false.
'''
ret = {'name': 'testing mode',
'changes': {},
'result': True,
'comment': 'Testing mode already ON.'}
result = {}
testing = __salt__['csf.get_testing_status']()
if int(testing) == 1:
return ret
enable = __salt__['csf.enable_testing_mode']()
if enable:
comment = 'Csf testing mode enabled'
if reload:
if __salt__['csf.reload']():
comment += ' and csf reloaded.'
ret['changes']['Testing Mode'] = 'on'
ret['comment'] = result
return ret
def testing_off(name, reload=False):
'''
Ensure testing mode is enabled in csf.
reload
Reload CSF after changing the testing status.
Default false.
'''
ret = {'name': 'testing mode',
'changes': {},
'result': True,
'comment': 'Testing mode already OFF.'}
result = {}
testing = __salt__['csf.get_testing_status']()
if int(testing) == 0:
return ret
disable = __salt__['csf.disable_testing_mode']()
if disable:
comment = 'Csf testing mode disabled'
if reload:
if __salt__['csf.reload']():
comment += ' and csf reloaded.'
ret['changes']['Testing Mode'] = 'off'
ret['comment'] = comment
return ret
def option_present(name, value, reload=False):
'''
Ensure the state of a particular option/setting in csf.
name
The option name in csf.conf
value
The value it should be set to.
reload
Boolean. If set to true, csf will be reloaded after.
'''
ret = {'name': 'testing mode',
'changes': {},
'result': True,
'comment': 'Option already present.'}
option = name
current_option = __salt__['csf.get_option'](option)
if current_option:
l = __salt__['csf.split_option'](current_option)
option_value = l[1]
if '"{0}"'.format(value) == option_value:
return ret
else:
result = __salt__['csf.set_option'](option, value)
ret['comment'] = 'Option modified.'
ret['changes']['Option'] = 'Changed'
else:
result = __salt__['file.append']('/etc/csf/csf.conf',
args='{0} = "{1}"'.format(option, value))
ret['comment'] = 'Option not present. Appended to csf.conf'
ret['changes']['Option'] = 'Changed.'
if reload:
if __salt__['csf.reload']():
ret['comment'] += '. Csf reloaded.'
else:
ret['comment'] += '. Csf failed to reload.'
ret['result'] = False
return ret
|
saltstack/salt
|
salt/states/csf.py
|
ports_open
|
python
|
def ports_open(name, ports, proto='tcp', direction='in'):
'''
Ensure ports are open for a protocol, in a direction.
e.g. - proto='tcp', direction='in' would set the values
for TCP_IN in the csf.conf file.
ports
A list of ports that should be open.
proto
The protocol. May be one of 'tcp', 'udp',
'tcp6', or 'udp6'.
direction
Choose 'in', 'out', or both to indicate the port
should be opened for inbound traffic, outbound
traffic, or both.
'''
ports = list(six.moves.map(six.text_type, ports))
diff = False
ret = {'name': ','.join(ports),
'changes': {},
'result': True,
'comment': 'Ports open.'}
current_ports = __salt__['csf.get_ports'](proto=proto, direction=direction)
direction = direction.upper()
directions = __salt__['csf.build_directions'](direction)
for direction in directions:
log.trace('current_ports[direction]: %s', current_ports[direction])
log.trace('ports: %s', ports)
if current_ports[direction] != ports:
diff = True
if diff:
result = __salt__['csf.allow_ports'](ports, proto=proto, direction=direction)
ret['changes']['Ports'] = 'Changed'
ret['comment'] = result
return ret
|
Ensure ports are open for a protocol, in a direction.
e.g. - proto='tcp', direction='in' would set the values
for TCP_IN in the csf.conf file.
ports
A list of ports that should be open.
proto
The protocol. May be one of 'tcp', 'udp',
'tcp6', or 'udp6'.
direction
Choose 'in', 'out', or both to indicate the port
should be opened for inbound traffic, outbound
traffic, or both.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/csf.py#L220-L258
| null |
# -*- coding: utf-8 -*-
'''
CSF Ip tables management
========================
:depends: - csf utility
:configuration: See http://download.configserver.com/csf/install.txt
for setup instructions.
.. code-block:: yaml
Simply allow/deny rules:
csf.rule_present:
ip: 1.2.3.4
method: allow
''' # pylint: disable=W0105
# Import Python Libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import Salt Libs
from salt.ext import six
log = logging.getLogger(__name__)
def __virtual__():
return 'csf'
def rule_present(name,
method,
port=None,
proto='tcp',
direction='in',
port_origin='d',
ip_origin='s',
ttl=None,
comment='',
reload=False):
'''
Ensure iptable rule exists.
name
The ip address or CIDR for the rule.
method
The type of rule. Either 'allow' or 'deny'.
port
Optional port to be open or closed for the
iptables rule.
proto
The protocol. Either 'tcp', or 'udp'.
Only applicable if port is specified.
direction
The diretion of traffic to apply the rule to.
Either 'in', or 'out'. Only applicable if
port is specified.
port_origin
Specifies either the source or destination
port is relevant for this rule. Only applicable
if port is specified. Either 's', or 'd'.
ip_origin
Specifies whether the ip in this rule refers to
the source or destination ip. Either 's', or
'd'. Only applicable if port is specified.
ttl
How long the rule should exist. If supplied,
`csf.tempallow()` or csf.tempdeny()` are used.
comment
An optional comment to appear after the rule
as a #comment .
reload
Reload the csf service after applying this rule.
Default false.
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': 'Rule already exists.'}
ip = name
# Check if rule is already present
exists = __salt__['csf.exists'](method=method,
ip=ip,
port=port,
proto=proto,
direction=direction,
port_origin=port_origin,
ip_origin=ip_origin,
ttl=ttl,
comment=comment)
if exists:
return ret
else:
if ttl:
method = 'temp{0}'.format(method)
func = __salt__['csf.{0}'.format(method)]
rule = func(ip,
port=port,
proto=proto,
direction=direction,
port_origin=port_origin,
ip_origin=ip_origin,
ttl=ttl,
comment=comment)
if rule:
comment = 'Rule has been added.'
if reload:
if __salt__['csf.reload']():
comment += ' Csf reloaded.'
else:
comment += ' Unable to reload csf.'
ret['result'] = False
ret['comment'] = comment
ret['changes']['Rule'] = 'Created'
return ret
def rule_absent(name,
method,
port=None,
proto='tcp',
direction='in',
port_origin='d',
ip_origin='s',
ttl=None,
reload=False):
'''
Ensure iptable is not present.
name
The ip address or CIDR for the rule.
method
The type of rule. Either 'allow' or 'deny'.
port
Optional port to be open or closed for the
iptables rule.
proto
The protocol. Either 'tcp', 'udp'.
Only applicable if port is specified.
direction
The diretion of traffic to apply the rule to.
Either 'in', or 'out'. Only applicable if
port is specified.
port_origin
Specifies either the source or destination
port is relevant for this rule. Only applicable
if port is specified. Either 's', or 'd'.
ip_origin
Specifies whether the ip in this rule refers to
the source or destination ip. Either 's', or
'd'. Only applicable if port is specified.
ttl
How long the rule should exist. If supplied,
`csf.tempallow()` or csf.tempdeny()` are used.
reload
Reload the csf service after applying this rule.
Default false.
'''
ip = name
ret = {'name': name,
'changes': {},
'result': True,
'comment': 'Rule not present.'}
exists = __salt__['csf.exists'](method,
ip,
port=port,
proto=proto,
direction=direction,
port_origin=port_origin,
ip_origin=ip_origin,
ttl=ttl)
if not exists:
return ret
else:
rule = __salt__['csf.remove_rule'](method=method,
ip=ip,
port=port,
proto=proto,
direction=direction,
port_origin=port_origin,
ip_origin=ip_origin,
comment='',
ttl=ttl)
if rule:
comment = 'Rule has been removed.'
if reload:
if __salt__['csf.reload']():
comment += ' Csf reloaded.'
else:
comment += 'Csf unable to be reloaded.'
ret['comment'] = comment
ret['changes']['Rule'] = 'Removed'
return ret
def nics_skip(name, nics, ipv6):
'''
Alias for :mod:`csf.nics_skipped <salt.states.csf.nics_skipped>`
'''
return nics_skipped(name, nics=nics, ipv6=ipv6)
def nics_skipped(name, nics, ipv6=False):
'''
name
Meaningless arg, but required for state.
nics
A list of nics to skip.
ipv6
Boolean. Set to true if you want to skip
the ipv6 interface. Default false (ipv4).
'''
ret = {'name': ','.join(nics),
'changes': {},
'result': True,
'comment': 'NICs skipped.'}
current_skipped_nics = __salt__['csf.get_skipped_nics'](ipv6=ipv6)
if nics == current_skipped_nics:
return ret
result = __salt__['csf.skip_nics'](nics, ipv6=ipv6)
ret['changes']['Skipped NICs'] = 'Changed'
return ret
def testing_on(name, reload=False):
'''
Ensure testing mode is enabled in csf.
reload
Reload CSF after changing the testing status.
Default false.
'''
ret = {'name': 'testing mode',
'changes': {},
'result': True,
'comment': 'Testing mode already ON.'}
result = {}
testing = __salt__['csf.get_testing_status']()
if int(testing) == 1:
return ret
enable = __salt__['csf.enable_testing_mode']()
if enable:
comment = 'Csf testing mode enabled'
if reload:
if __salt__['csf.reload']():
comment += ' and csf reloaded.'
ret['changes']['Testing Mode'] = 'on'
ret['comment'] = result
return ret
def testing_off(name, reload=False):
'''
Ensure testing mode is enabled in csf.
reload
Reload CSF after changing the testing status.
Default false.
'''
ret = {'name': 'testing mode',
'changes': {},
'result': True,
'comment': 'Testing mode already OFF.'}
result = {}
testing = __salt__['csf.get_testing_status']()
if int(testing) == 0:
return ret
disable = __salt__['csf.disable_testing_mode']()
if disable:
comment = 'Csf testing mode disabled'
if reload:
if __salt__['csf.reload']():
comment += ' and csf reloaded.'
ret['changes']['Testing Mode'] = 'off'
ret['comment'] = comment
return ret
def option_present(name, value, reload=False):
'''
Ensure the state of a particular option/setting in csf.
name
The option name in csf.conf
value
The value it should be set to.
reload
Boolean. If set to true, csf will be reloaded after.
'''
ret = {'name': 'testing mode',
'changes': {},
'result': True,
'comment': 'Option already present.'}
option = name
current_option = __salt__['csf.get_option'](option)
if current_option:
l = __salt__['csf.split_option'](current_option)
option_value = l[1]
if '"{0}"'.format(value) == option_value:
return ret
else:
result = __salt__['csf.set_option'](option, value)
ret['comment'] = 'Option modified.'
ret['changes']['Option'] = 'Changed'
else:
result = __salt__['file.append']('/etc/csf/csf.conf',
args='{0} = "{1}"'.format(option, value))
ret['comment'] = 'Option not present. Appended to csf.conf'
ret['changes']['Option'] = 'Changed.'
if reload:
if __salt__['csf.reload']():
ret['comment'] += '. Csf reloaded.'
else:
ret['comment'] += '. Csf failed to reload.'
ret['result'] = False
return ret
|
saltstack/salt
|
salt/states/csf.py
|
nics_skip
|
python
|
def nics_skip(name, nics, ipv6):
'''
Alias for :mod:`csf.nics_skipped <salt.states.csf.nics_skipped>`
'''
return nics_skipped(name, nics=nics, ipv6=ipv6)
|
Alias for :mod:`csf.nics_skipped <salt.states.csf.nics_skipped>`
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/csf.py#L261-L265
|
[
"def nics_skipped(name, nics, ipv6=False):\n '''\n name\n Meaningless arg, but required for state.\n\n nics\n A list of nics to skip.\n\n ipv6\n Boolean. Set to true if you want to skip\n the ipv6 interface. Default false (ipv4).\n '''\n ret = {'name': ','.join(nics),\n 'changes': {},\n 'result': True,\n 'comment': 'NICs skipped.'}\n\n current_skipped_nics = __salt__['csf.get_skipped_nics'](ipv6=ipv6)\n if nics == current_skipped_nics:\n return ret\n result = __salt__['csf.skip_nics'](nics, ipv6=ipv6)\n ret['changes']['Skipped NICs'] = 'Changed'\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
CSF Ip tables management
========================
:depends: - csf utility
:configuration: See http://download.configserver.com/csf/install.txt
for setup instructions.
.. code-block:: yaml
Simply allow/deny rules:
csf.rule_present:
ip: 1.2.3.4
method: allow
''' # pylint: disable=W0105
# Import Python Libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import Salt Libs
from salt.ext import six
log = logging.getLogger(__name__)
def __virtual__():
return 'csf'
def rule_present(name,
method,
port=None,
proto='tcp',
direction='in',
port_origin='d',
ip_origin='s',
ttl=None,
comment='',
reload=False):
'''
Ensure iptable rule exists.
name
The ip address or CIDR for the rule.
method
The type of rule. Either 'allow' or 'deny'.
port
Optional port to be open or closed for the
iptables rule.
proto
The protocol. Either 'tcp', or 'udp'.
Only applicable if port is specified.
direction
The diretion of traffic to apply the rule to.
Either 'in', or 'out'. Only applicable if
port is specified.
port_origin
Specifies either the source or destination
port is relevant for this rule. Only applicable
if port is specified. Either 's', or 'd'.
ip_origin
Specifies whether the ip in this rule refers to
the source or destination ip. Either 's', or
'd'. Only applicable if port is specified.
ttl
How long the rule should exist. If supplied,
`csf.tempallow()` or csf.tempdeny()` are used.
comment
An optional comment to appear after the rule
as a #comment .
reload
Reload the csf service after applying this rule.
Default false.
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': 'Rule already exists.'}
ip = name
# Check if rule is already present
exists = __salt__['csf.exists'](method=method,
ip=ip,
port=port,
proto=proto,
direction=direction,
port_origin=port_origin,
ip_origin=ip_origin,
ttl=ttl,
comment=comment)
if exists:
return ret
else:
if ttl:
method = 'temp{0}'.format(method)
func = __salt__['csf.{0}'.format(method)]
rule = func(ip,
port=port,
proto=proto,
direction=direction,
port_origin=port_origin,
ip_origin=ip_origin,
ttl=ttl,
comment=comment)
if rule:
comment = 'Rule has been added.'
if reload:
if __salt__['csf.reload']():
comment += ' Csf reloaded.'
else:
comment += ' Unable to reload csf.'
ret['result'] = False
ret['comment'] = comment
ret['changes']['Rule'] = 'Created'
return ret
def rule_absent(name,
method,
port=None,
proto='tcp',
direction='in',
port_origin='d',
ip_origin='s',
ttl=None,
reload=False):
'''
Ensure iptable is not present.
name
The ip address or CIDR for the rule.
method
The type of rule. Either 'allow' or 'deny'.
port
Optional port to be open or closed for the
iptables rule.
proto
The protocol. Either 'tcp', 'udp'.
Only applicable if port is specified.
direction
The diretion of traffic to apply the rule to.
Either 'in', or 'out'. Only applicable if
port is specified.
port_origin
Specifies either the source or destination
port is relevant for this rule. Only applicable
if port is specified. Either 's', or 'd'.
ip_origin
Specifies whether the ip in this rule refers to
the source or destination ip. Either 's', or
'd'. Only applicable if port is specified.
ttl
How long the rule should exist. If supplied,
`csf.tempallow()` or csf.tempdeny()` are used.
reload
Reload the csf service after applying this rule.
Default false.
'''
ip = name
ret = {'name': name,
'changes': {},
'result': True,
'comment': 'Rule not present.'}
exists = __salt__['csf.exists'](method,
ip,
port=port,
proto=proto,
direction=direction,
port_origin=port_origin,
ip_origin=ip_origin,
ttl=ttl)
if not exists:
return ret
else:
rule = __salt__['csf.remove_rule'](method=method,
ip=ip,
port=port,
proto=proto,
direction=direction,
port_origin=port_origin,
ip_origin=ip_origin,
comment='',
ttl=ttl)
if rule:
comment = 'Rule has been removed.'
if reload:
if __salt__['csf.reload']():
comment += ' Csf reloaded.'
else:
comment += 'Csf unable to be reloaded.'
ret['comment'] = comment
ret['changes']['Rule'] = 'Removed'
return ret
def ports_open(name, ports, proto='tcp', direction='in'):
'''
Ensure ports are open for a protocol, in a direction.
e.g. - proto='tcp', direction='in' would set the values
for TCP_IN in the csf.conf file.
ports
A list of ports that should be open.
proto
The protocol. May be one of 'tcp', 'udp',
'tcp6', or 'udp6'.
direction
Choose 'in', 'out', or both to indicate the port
should be opened for inbound traffic, outbound
traffic, or both.
'''
ports = list(six.moves.map(six.text_type, ports))
diff = False
ret = {'name': ','.join(ports),
'changes': {},
'result': True,
'comment': 'Ports open.'}
current_ports = __salt__['csf.get_ports'](proto=proto, direction=direction)
direction = direction.upper()
directions = __salt__['csf.build_directions'](direction)
for direction in directions:
log.trace('current_ports[direction]: %s', current_ports[direction])
log.trace('ports: %s', ports)
if current_ports[direction] != ports:
diff = True
if diff:
result = __salt__['csf.allow_ports'](ports, proto=proto, direction=direction)
ret['changes']['Ports'] = 'Changed'
ret['comment'] = result
return ret
def nics_skipped(name, nics, ipv6=False):
'''
name
Meaningless arg, but required for state.
nics
A list of nics to skip.
ipv6
Boolean. Set to true if you want to skip
the ipv6 interface. Default false (ipv4).
'''
ret = {'name': ','.join(nics),
'changes': {},
'result': True,
'comment': 'NICs skipped.'}
current_skipped_nics = __salt__['csf.get_skipped_nics'](ipv6=ipv6)
if nics == current_skipped_nics:
return ret
result = __salt__['csf.skip_nics'](nics, ipv6=ipv6)
ret['changes']['Skipped NICs'] = 'Changed'
return ret
def testing_on(name, reload=False):
'''
Ensure testing mode is enabled in csf.
reload
Reload CSF after changing the testing status.
Default false.
'''
ret = {'name': 'testing mode',
'changes': {},
'result': True,
'comment': 'Testing mode already ON.'}
result = {}
testing = __salt__['csf.get_testing_status']()
if int(testing) == 1:
return ret
enable = __salt__['csf.enable_testing_mode']()
if enable:
comment = 'Csf testing mode enabled'
if reload:
if __salt__['csf.reload']():
comment += ' and csf reloaded.'
ret['changes']['Testing Mode'] = 'on'
ret['comment'] = result
return ret
def testing_off(name, reload=False):
'''
Ensure testing mode is enabled in csf.
reload
Reload CSF after changing the testing status.
Default false.
'''
ret = {'name': 'testing mode',
'changes': {},
'result': True,
'comment': 'Testing mode already OFF.'}
result = {}
testing = __salt__['csf.get_testing_status']()
if int(testing) == 0:
return ret
disable = __salt__['csf.disable_testing_mode']()
if disable:
comment = 'Csf testing mode disabled'
if reload:
if __salt__['csf.reload']():
comment += ' and csf reloaded.'
ret['changes']['Testing Mode'] = 'off'
ret['comment'] = comment
return ret
def option_present(name, value, reload=False):
'''
Ensure the state of a particular option/setting in csf.
name
The option name in csf.conf
value
The value it should be set to.
reload
Boolean. If set to true, csf will be reloaded after.
'''
ret = {'name': 'testing mode',
'changes': {},
'result': True,
'comment': 'Option already present.'}
option = name
current_option = __salt__['csf.get_option'](option)
if current_option:
l = __salt__['csf.split_option'](current_option)
option_value = l[1]
if '"{0}"'.format(value) == option_value:
return ret
else:
result = __salt__['csf.set_option'](option, value)
ret['comment'] = 'Option modified.'
ret['changes']['Option'] = 'Changed'
else:
result = __salt__['file.append']('/etc/csf/csf.conf',
args='{0} = "{1}"'.format(option, value))
ret['comment'] = 'Option not present. Appended to csf.conf'
ret['changes']['Option'] = 'Changed.'
if reload:
if __salt__['csf.reload']():
ret['comment'] += '. Csf reloaded.'
else:
ret['comment'] += '. Csf failed to reload.'
ret['result'] = False
return ret
|
saltstack/salt
|
salt/states/csf.py
|
nics_skipped
|
python
|
def nics_skipped(name, nics, ipv6=False):
'''
name
Meaningless arg, but required for state.
nics
A list of nics to skip.
ipv6
Boolean. Set to true if you want to skip
the ipv6 interface. Default false (ipv4).
'''
ret = {'name': ','.join(nics),
'changes': {},
'result': True,
'comment': 'NICs skipped.'}
current_skipped_nics = __salt__['csf.get_skipped_nics'](ipv6=ipv6)
if nics == current_skipped_nics:
return ret
result = __salt__['csf.skip_nics'](nics, ipv6=ipv6)
ret['changes']['Skipped NICs'] = 'Changed'
return ret
|
name
Meaningless arg, but required for state.
nics
A list of nics to skip.
ipv6
Boolean. Set to true if you want to skip
the ipv6 interface. Default false (ipv4).
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/csf.py#L268-L290
| null |
# -*- coding: utf-8 -*-
'''
CSF Ip tables management
========================
:depends: - csf utility
:configuration: See http://download.configserver.com/csf/install.txt
for setup instructions.
.. code-block:: yaml
Simply allow/deny rules:
csf.rule_present:
ip: 1.2.3.4
method: allow
''' # pylint: disable=W0105
# Import Python Libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import Salt Libs
from salt.ext import six
log = logging.getLogger(__name__)
def __virtual__():
return 'csf'
def rule_present(name,
method,
port=None,
proto='tcp',
direction='in',
port_origin='d',
ip_origin='s',
ttl=None,
comment='',
reload=False):
'''
Ensure iptable rule exists.
name
The ip address or CIDR for the rule.
method
The type of rule. Either 'allow' or 'deny'.
port
Optional port to be open or closed for the
iptables rule.
proto
The protocol. Either 'tcp', or 'udp'.
Only applicable if port is specified.
direction
The diretion of traffic to apply the rule to.
Either 'in', or 'out'. Only applicable if
port is specified.
port_origin
Specifies either the source or destination
port is relevant for this rule. Only applicable
if port is specified. Either 's', or 'd'.
ip_origin
Specifies whether the ip in this rule refers to
the source or destination ip. Either 's', or
'd'. Only applicable if port is specified.
ttl
How long the rule should exist. If supplied,
`csf.tempallow()` or csf.tempdeny()` are used.
comment
An optional comment to appear after the rule
as a #comment .
reload
Reload the csf service after applying this rule.
Default false.
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': 'Rule already exists.'}
ip = name
# Check if rule is already present
exists = __salt__['csf.exists'](method=method,
ip=ip,
port=port,
proto=proto,
direction=direction,
port_origin=port_origin,
ip_origin=ip_origin,
ttl=ttl,
comment=comment)
if exists:
return ret
else:
if ttl:
method = 'temp{0}'.format(method)
func = __salt__['csf.{0}'.format(method)]
rule = func(ip,
port=port,
proto=proto,
direction=direction,
port_origin=port_origin,
ip_origin=ip_origin,
ttl=ttl,
comment=comment)
if rule:
comment = 'Rule has been added.'
if reload:
if __salt__['csf.reload']():
comment += ' Csf reloaded.'
else:
comment += ' Unable to reload csf.'
ret['result'] = False
ret['comment'] = comment
ret['changes']['Rule'] = 'Created'
return ret
def rule_absent(name,
method,
port=None,
proto='tcp',
direction='in',
port_origin='d',
ip_origin='s',
ttl=None,
reload=False):
'''
Ensure iptable is not present.
name
The ip address or CIDR for the rule.
method
The type of rule. Either 'allow' or 'deny'.
port
Optional port to be open or closed for the
iptables rule.
proto
The protocol. Either 'tcp', 'udp'.
Only applicable if port is specified.
direction
The diretion of traffic to apply the rule to.
Either 'in', or 'out'. Only applicable if
port is specified.
port_origin
Specifies either the source or destination
port is relevant for this rule. Only applicable
if port is specified. Either 's', or 'd'.
ip_origin
Specifies whether the ip in this rule refers to
the source or destination ip. Either 's', or
'd'. Only applicable if port is specified.
ttl
How long the rule should exist. If supplied,
`csf.tempallow()` or csf.tempdeny()` are used.
reload
Reload the csf service after applying this rule.
Default false.
'''
ip = name
ret = {'name': name,
'changes': {},
'result': True,
'comment': 'Rule not present.'}
exists = __salt__['csf.exists'](method,
ip,
port=port,
proto=proto,
direction=direction,
port_origin=port_origin,
ip_origin=ip_origin,
ttl=ttl)
if not exists:
return ret
else:
rule = __salt__['csf.remove_rule'](method=method,
ip=ip,
port=port,
proto=proto,
direction=direction,
port_origin=port_origin,
ip_origin=ip_origin,
comment='',
ttl=ttl)
if rule:
comment = 'Rule has been removed.'
if reload:
if __salt__['csf.reload']():
comment += ' Csf reloaded.'
else:
comment += 'Csf unable to be reloaded.'
ret['comment'] = comment
ret['changes']['Rule'] = 'Removed'
return ret
def ports_open(name, ports, proto='tcp', direction='in'):
'''
Ensure ports are open for a protocol, in a direction.
e.g. - proto='tcp', direction='in' would set the values
for TCP_IN in the csf.conf file.
ports
A list of ports that should be open.
proto
The protocol. May be one of 'tcp', 'udp',
'tcp6', or 'udp6'.
direction
Choose 'in', 'out', or both to indicate the port
should be opened for inbound traffic, outbound
traffic, or both.
'''
ports = list(six.moves.map(six.text_type, ports))
diff = False
ret = {'name': ','.join(ports),
'changes': {},
'result': True,
'comment': 'Ports open.'}
current_ports = __salt__['csf.get_ports'](proto=proto, direction=direction)
direction = direction.upper()
directions = __salt__['csf.build_directions'](direction)
for direction in directions:
log.trace('current_ports[direction]: %s', current_ports[direction])
log.trace('ports: %s', ports)
if current_ports[direction] != ports:
diff = True
if diff:
result = __salt__['csf.allow_ports'](ports, proto=proto, direction=direction)
ret['changes']['Ports'] = 'Changed'
ret['comment'] = result
return ret
def nics_skip(name, nics, ipv6):
'''
Alias for :mod:`csf.nics_skipped <salt.states.csf.nics_skipped>`
'''
return nics_skipped(name, nics=nics, ipv6=ipv6)
def testing_on(name, reload=False):
'''
Ensure testing mode is enabled in csf.
reload
Reload CSF after changing the testing status.
Default false.
'''
ret = {'name': 'testing mode',
'changes': {},
'result': True,
'comment': 'Testing mode already ON.'}
result = {}
testing = __salt__['csf.get_testing_status']()
if int(testing) == 1:
return ret
enable = __salt__['csf.enable_testing_mode']()
if enable:
comment = 'Csf testing mode enabled'
if reload:
if __salt__['csf.reload']():
comment += ' and csf reloaded.'
ret['changes']['Testing Mode'] = 'on'
ret['comment'] = result
return ret
def testing_off(name, reload=False):
'''
Ensure testing mode is enabled in csf.
reload
Reload CSF after changing the testing status.
Default false.
'''
ret = {'name': 'testing mode',
'changes': {},
'result': True,
'comment': 'Testing mode already OFF.'}
result = {}
testing = __salt__['csf.get_testing_status']()
if int(testing) == 0:
return ret
disable = __salt__['csf.disable_testing_mode']()
if disable:
comment = 'Csf testing mode disabled'
if reload:
if __salt__['csf.reload']():
comment += ' and csf reloaded.'
ret['changes']['Testing Mode'] = 'off'
ret['comment'] = comment
return ret
def option_present(name, value, reload=False):
'''
Ensure the state of a particular option/setting in csf.
name
The option name in csf.conf
value
The value it should be set to.
reload
Boolean. If set to true, csf will be reloaded after.
'''
ret = {'name': 'testing mode',
'changes': {},
'result': True,
'comment': 'Option already present.'}
option = name
current_option = __salt__['csf.get_option'](option)
if current_option:
l = __salt__['csf.split_option'](current_option)
option_value = l[1]
if '"{0}"'.format(value) == option_value:
return ret
else:
result = __salt__['csf.set_option'](option, value)
ret['comment'] = 'Option modified.'
ret['changes']['Option'] = 'Changed'
else:
result = __salt__['file.append']('/etc/csf/csf.conf',
args='{0} = "{1}"'.format(option, value))
ret['comment'] = 'Option not present. Appended to csf.conf'
ret['changes']['Option'] = 'Changed.'
if reload:
if __salt__['csf.reload']():
ret['comment'] += '. Csf reloaded.'
else:
ret['comment'] += '. Csf failed to reload.'
ret['result'] = False
return ret
|
saltstack/salt
|
salt/states/csf.py
|
option_present
|
python
|
def option_present(name, value, reload=False):
'''
Ensure the state of a particular option/setting in csf.
name
The option name in csf.conf
value
The value it should be set to.
reload
Boolean. If set to true, csf will be reloaded after.
'''
ret = {'name': 'testing mode',
'changes': {},
'result': True,
'comment': 'Option already present.'}
option = name
current_option = __salt__['csf.get_option'](option)
if current_option:
l = __salt__['csf.split_option'](current_option)
option_value = l[1]
if '"{0}"'.format(value) == option_value:
return ret
else:
result = __salt__['csf.set_option'](option, value)
ret['comment'] = 'Option modified.'
ret['changes']['Option'] = 'Changed'
else:
result = __salt__['file.append']('/etc/csf/csf.conf',
args='{0} = "{1}"'.format(option, value))
ret['comment'] = 'Option not present. Appended to csf.conf'
ret['changes']['Option'] = 'Changed.'
if reload:
if __salt__['csf.reload']():
ret['comment'] += '. Csf reloaded.'
else:
ret['comment'] += '. Csf failed to reload.'
ret['result'] = False
return ret
|
Ensure the state of a particular option/setting in csf.
name
The option name in csf.conf
value
The value it should be set to.
reload
Boolean. If set to true, csf will be reloaded after.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/csf.py#L350-L389
| null |
# -*- coding: utf-8 -*-
'''
CSF Ip tables management
========================
:depends: - csf utility
:configuration: See http://download.configserver.com/csf/install.txt
for setup instructions.
.. code-block:: yaml
Simply allow/deny rules:
csf.rule_present:
ip: 1.2.3.4
method: allow
''' # pylint: disable=W0105
# Import Python Libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import Salt Libs
from salt.ext import six
log = logging.getLogger(__name__)
def __virtual__():
return 'csf'
def rule_present(name,
method,
port=None,
proto='tcp',
direction='in',
port_origin='d',
ip_origin='s',
ttl=None,
comment='',
reload=False):
'''
Ensure iptable rule exists.
name
The ip address or CIDR for the rule.
method
The type of rule. Either 'allow' or 'deny'.
port
Optional port to be open or closed for the
iptables rule.
proto
The protocol. Either 'tcp', or 'udp'.
Only applicable if port is specified.
direction
The diretion of traffic to apply the rule to.
Either 'in', or 'out'. Only applicable if
port is specified.
port_origin
Specifies either the source or destination
port is relevant for this rule. Only applicable
if port is specified. Either 's', or 'd'.
ip_origin
Specifies whether the ip in this rule refers to
the source or destination ip. Either 's', or
'd'. Only applicable if port is specified.
ttl
How long the rule should exist. If supplied,
`csf.tempallow()` or csf.tempdeny()` are used.
comment
An optional comment to appear after the rule
as a #comment .
reload
Reload the csf service after applying this rule.
Default false.
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': 'Rule already exists.'}
ip = name
# Check if rule is already present
exists = __salt__['csf.exists'](method=method,
ip=ip,
port=port,
proto=proto,
direction=direction,
port_origin=port_origin,
ip_origin=ip_origin,
ttl=ttl,
comment=comment)
if exists:
return ret
else:
if ttl:
method = 'temp{0}'.format(method)
func = __salt__['csf.{0}'.format(method)]
rule = func(ip,
port=port,
proto=proto,
direction=direction,
port_origin=port_origin,
ip_origin=ip_origin,
ttl=ttl,
comment=comment)
if rule:
comment = 'Rule has been added.'
if reload:
if __salt__['csf.reload']():
comment += ' Csf reloaded.'
else:
comment += ' Unable to reload csf.'
ret['result'] = False
ret['comment'] = comment
ret['changes']['Rule'] = 'Created'
return ret
def rule_absent(name,
method,
port=None,
proto='tcp',
direction='in',
port_origin='d',
ip_origin='s',
ttl=None,
reload=False):
'''
Ensure iptable is not present.
name
The ip address or CIDR for the rule.
method
The type of rule. Either 'allow' or 'deny'.
port
Optional port to be open or closed for the
iptables rule.
proto
The protocol. Either 'tcp', 'udp'.
Only applicable if port is specified.
direction
The diretion of traffic to apply the rule to.
Either 'in', or 'out'. Only applicable if
port is specified.
port_origin
Specifies either the source or destination
port is relevant for this rule. Only applicable
if port is specified. Either 's', or 'd'.
ip_origin
Specifies whether the ip in this rule refers to
the source or destination ip. Either 's', or
'd'. Only applicable if port is specified.
ttl
How long the rule should exist. If supplied,
`csf.tempallow()` or csf.tempdeny()` are used.
reload
Reload the csf service after applying this rule.
Default false.
'''
ip = name
ret = {'name': name,
'changes': {},
'result': True,
'comment': 'Rule not present.'}
exists = __salt__['csf.exists'](method,
ip,
port=port,
proto=proto,
direction=direction,
port_origin=port_origin,
ip_origin=ip_origin,
ttl=ttl)
if not exists:
return ret
else:
rule = __salt__['csf.remove_rule'](method=method,
ip=ip,
port=port,
proto=proto,
direction=direction,
port_origin=port_origin,
ip_origin=ip_origin,
comment='',
ttl=ttl)
if rule:
comment = 'Rule has been removed.'
if reload:
if __salt__['csf.reload']():
comment += ' Csf reloaded.'
else:
comment += 'Csf unable to be reloaded.'
ret['comment'] = comment
ret['changes']['Rule'] = 'Removed'
return ret
def ports_open(name, ports, proto='tcp', direction='in'):
'''
Ensure ports are open for a protocol, in a direction.
e.g. - proto='tcp', direction='in' would set the values
for TCP_IN in the csf.conf file.
ports
A list of ports that should be open.
proto
The protocol. May be one of 'tcp', 'udp',
'tcp6', or 'udp6'.
direction
Choose 'in', 'out', or both to indicate the port
should be opened for inbound traffic, outbound
traffic, or both.
'''
ports = list(six.moves.map(six.text_type, ports))
diff = False
ret = {'name': ','.join(ports),
'changes': {},
'result': True,
'comment': 'Ports open.'}
current_ports = __salt__['csf.get_ports'](proto=proto, direction=direction)
direction = direction.upper()
directions = __salt__['csf.build_directions'](direction)
for direction in directions:
log.trace('current_ports[direction]: %s', current_ports[direction])
log.trace('ports: %s', ports)
if current_ports[direction] != ports:
diff = True
if diff:
result = __salt__['csf.allow_ports'](ports, proto=proto, direction=direction)
ret['changes']['Ports'] = 'Changed'
ret['comment'] = result
return ret
def nics_skip(name, nics, ipv6):
'''
Alias for :mod:`csf.nics_skipped <salt.states.csf.nics_skipped>`
'''
return nics_skipped(name, nics=nics, ipv6=ipv6)
def nics_skipped(name, nics, ipv6=False):
'''
name
Meaningless arg, but required for state.
nics
A list of nics to skip.
ipv6
Boolean. Set to true if you want to skip
the ipv6 interface. Default false (ipv4).
'''
ret = {'name': ','.join(nics),
'changes': {},
'result': True,
'comment': 'NICs skipped.'}
current_skipped_nics = __salt__['csf.get_skipped_nics'](ipv6=ipv6)
if nics == current_skipped_nics:
return ret
result = __salt__['csf.skip_nics'](nics, ipv6=ipv6)
ret['changes']['Skipped NICs'] = 'Changed'
return ret
def testing_on(name, reload=False):
'''
Ensure testing mode is enabled in csf.
reload
Reload CSF after changing the testing status.
Default false.
'''
ret = {'name': 'testing mode',
'changes': {},
'result': True,
'comment': 'Testing mode already ON.'}
result = {}
testing = __salt__['csf.get_testing_status']()
if int(testing) == 1:
return ret
enable = __salt__['csf.enable_testing_mode']()
if enable:
comment = 'Csf testing mode enabled'
if reload:
if __salt__['csf.reload']():
comment += ' and csf reloaded.'
ret['changes']['Testing Mode'] = 'on'
ret['comment'] = result
return ret
def testing_off(name, reload=False):
'''
Ensure testing mode is enabled in csf.
reload
Reload CSF after changing the testing status.
Default false.
'''
ret = {'name': 'testing mode',
'changes': {},
'result': True,
'comment': 'Testing mode already OFF.'}
result = {}
testing = __salt__['csf.get_testing_status']()
if int(testing) == 0:
return ret
disable = __salt__['csf.disable_testing_mode']()
if disable:
comment = 'Csf testing mode disabled'
if reload:
if __salt__['csf.reload']():
comment += ' and csf reloaded.'
ret['changes']['Testing Mode'] = 'off'
ret['comment'] = comment
return ret
|
saltstack/salt
|
salt/pillar/stack.py
|
_parse_stack_cfg
|
python
|
def _parse_stack_cfg(content):
'''
Allow top level cfg to be YAML
'''
try:
obj = salt.utils.yaml.safe_load(content)
if isinstance(obj, list):
return obj
except Exception as e:
pass
return content.splitlines()
|
Allow top level cfg to be YAML
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/pillar/stack.py#L529-L539
| null |
# -*- coding: utf-8 -*-
'''
Simple and flexible YAML ext_pillar which can read pillar from within pillar.
.. versionadded:: 2016.3.0
`PillarStack <https://github.com/bbinet/pillarstack>`_ is a custom saltstack
``ext_pillar`` which was inspired by `varstack
<https://github.com/conversis/varstack>`_ but is heavily based on Jinja2 for
maximum flexibility.
Any issue should be reported to the upstream project at:
https://github.com/bbinet/pillarstack/issues
It supports the following features:
- multiple config files that are jinja2 templates with support for ``pillar``,
``__grains__``, ``__salt__``, ``__opts__`` objects
- a config file renders as an ordered list of files (paths of these files are
relative to the current config file)
- this list of files are read in ordered as jinja2 templates with support for
``stack``, ``pillar``, ``__grains__``, ``__salt__``, ``__opts__`` objects
- all these rendered files are then parsed as ``yaml``
- then all yaml dicts are merged in order with support for the following
merging strategies: ``merge-first``, ``merge-last``, ``remove``, and
``overwrite``
- stack config files can be matched based on ``pillar``, ``grains``, or
``opts`` values, which make it possible to support kind of self-contained
environments
Installation
------------
PillarStack is already bundled with Salt since 2016.3.0 version so there is
nothing to install from version 2016.3.0.
If you use an older Salt version or you want to override PillarStack with a
more recent one, follow the installation procedure below.
Installing the PillarStack ``ext_pillar`` is as simple as dropping the
``stack.py`` file in the ``<extension_modules>/pillar`` directory (no external
python module required), given that ``extension_modules`` is set in your
salt-master configuration, see:
http://docs.saltstack.com/en/latest/ref/configuration/master.html#extension-modules
Configuration in Salt
---------------------
Like any other external pillar, its configuration takes place through the
``ext_pillar`` key in the master config file.
However, you can configure PillarStack in 3 different ways:
Single config file
~~~~~~~~~~~~~~~~~~
This is the simplest option, you just need to set the path to your single
PillarStack config file like below:
.. code:: yaml
ext_pillar:
- stack: /path/to/stack.cfg
List of config files
~~~~~~~~~~~~~~~~~~~~
You can also provide a list of config files:
.. code:: yaml
ext_pillar:
- stack:
- /path/to/stack1.cfg
- /path/to/stack2.cfg
Select config files through grains|pillar|opts matching
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
You can also opt for a much more flexible configuration: PillarStack allows one
to select the config files for the current minion based on matching values from
either grains, or pillar, or opts objects.
Here is an example of such a configuration, which should speak by itself:
.. code:: yaml
ext_pillar:
- stack:
pillar:environment:
dev: /path/to/dev/stack.cfg
prod: /path/to/prod/stack.cfg
grains:custom:grain:
value:
- /path/to/stack1.cfg
- /path/to/stack2.cfg
opts:custom:opt:
value: /path/to/stack0.cfg
PillarStack configuration files
-------------------------------
The config files that are referenced in the above ``ext_pillar`` configuration
are jinja2 templates which must render as a simple ordered list of ``yaml``
files that will then be merged to build pillar data.
The path of these ``yaml`` files must be relative to the directory of the
PillarStack config file. These paths support unix style pathname pattern
expansion through the
`Python glob module <https://docs.python.org/2/library/glob.html>`.
The following variables are available in jinja2 templating of PillarStack
configuration files:
- ``pillar``: the pillar data (as passed by Salt to our ``ext_pillar``
function)
- ``minion_id``: the minion id ;-)
- ``__opts__``: a dictionary of mostly Salt configuration options
- ``__grains__``: a dictionary of the grains of the minion making this pillar
call
- ``__salt__``: a dictionary of Salt module functions, useful so you don't have
to duplicate functions that already exist (note: runs on the master)
So you can use all the power of jinja2 to build your list of ``yaml`` files
that will be merged in pillar data.
For example, you could have a PillarStack config file which looks like:
.. code:: jinja
$ cat /path/to/stack/config.cfg
core.yml
common/*.yml
osarchs/{{ __grains__['osarch'] }}.yml
oscodenames/{{ __grains__['oscodename'] }}.yml
{%- for role in pillar.get('roles', []) %}
roles/{{ role }}.yml
{%- endfor %}
minions/{{ minion_id }}.yml
And the whole directory structure could look like:
.. code::
$ tree /path/to/stack/
/path/to/stack/
├── config.cfg
├── core.yml
├── common/
│ ├── xxx.yml
│ └── yyy.yml
├── osarchs/
│ ├── amd64.yml
│ └── armhf.yml
├── oscodenames/
│ ├── wheezy.yml
│ └── jessie.yml
├── roles/
│ ├── web.yml
│ └── db.yml
└── minions/
├── test-1-dev.yml
└── test-2-dev.yml
Overall process
---------------
In the above PillarStack configuration, given that test-1-dev minion is an
amd64 platform running Debian Jessie, and which pillar ``roles`` is ``["db"]``,
the following ``yaml`` files would be merged in order:
- ``core.yml``
- ``common/xxx.yml``
- ``common/yyy.yml``
- ``osarchs/amd64.yml``
- ``oscodenames/jessie.yml``
- ``roles/db.yml``
- ``minions/test-1-dev.yml``
Before merging, every files above will be preprocessed as Jinja2 templates.
The following variables are available in Jinja2 templating of ``yaml`` files:
- ``stack``: the PillarStack pillar data object that has currently been merged
(data from previous ``yaml`` files in PillarStack configuration)
- ``pillar``: the pillar data (as passed by Salt to our ``ext_pillar``
function)
- ``minion_id``: the minion id ;-)
- ``__opts__``: a dictionary of mostly Salt configuration options
- ``__grains__``: a dictionary of the grains of the minion making this pillar
call
- ``__salt__``: a dictionary of Salt module functions, useful so you don't have
to duplicate functions that already exist (note: runs on the master)
So you can use all the power of jinja2 to build your pillar data, and even use
other pillar values that has already been merged by PillarStack (from previous
``yaml`` files in PillarStack configuration) through the ``stack`` variable.
Once a ``yaml`` file has been preprocessed by Jinja2, we obtain a Python dict -
let's call it ``yml_data`` - then, PillarStack will merge this ``yml_data``
dict in the main ``stack`` dict (which contains already merged PillarStack
pillar data).
By default, PillarStack will deeply merge ``yml_data`` in ``stack`` (similarly
to the ``recurse`` salt ``pillar_source_merging_strategy``), but 3 merging
strategies are currently available for you to choose (see next section).
Once every ``yaml`` files have been processed, the ``stack`` dict will contain
your whole own pillar data, merged in order by PillarStack.
So PillarStack ``ext_pillar`` returns the ``stack`` dict, the contents of which
Salt takes care to merge in with all of the other pillars and finally return
the whole pillar to the minion.
Merging strategies
------------------
The way the data from a new ``yaml_data`` dict is merged with the existing
``stack`` data can be controlled by specifying a merging strategy. Right now
this strategy can either be ``merge-last`` (the default), ``merge-first``,
``remove``, or ``overwrite``.
Note that scalar values like strings, integers, booleans, etc. are always
evaluated using the ``overwrite`` strategy (other strategies don't make sense
in that case).
The merging strategy can be set by including a dict in the form of:
.. code:: yaml
__: <merging strategy>
as the first item of the dict or list.
This allows fine grained control over the merging process.
``merge-last`` (default) strategy
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
If the ``merge-last`` strategy is selected (the default), then content of dict
or list variables is merged recursively with previous definitions of this
variable (similarly to the ``recurse`` salt
``pillar_source_merging_strategy``).
This allows for extending previously defined data.
``merge-first`` strategy
~~~~~~~~~~~~~~~~~~~~~~~~
If the ``merge-first`` strategy is selected, then the content of dict or list
variables are swapped between the ``yaml_data`` and ``stack`` objects before
being merged recursively with the ``merge-last`` previous strategy.
``remove`` strategy
~~~~~~~~~~~~~~~~~~~
If the ``remove`` strategy is selected, then content of dict or list variables
in ``stack`` are removed only if the corresponding item is present in the
``yaml_data`` dict.
This allows for removing items from previously defined data.
``overwrite`` strategy
~~~~~~~~~~~~~~~~~~~~~~
If the ``overwrite`` strategy is selected, then the content of dict or list
variables in ``stack`` is overwritten by the content of ``yaml_data`` dict.
So this allows one to overwrite variables from previous definitions.
Merging examples
----------------
Let's go through small examples that should clarify what's going on when a
``yaml_data`` dict is merged in the ``stack`` dict.
When you don't specify any strategy, the default ``merge-last`` strategy is
selected:
+----------------------+-----------------------+-------------------------+
| ``stack`` | ``yaml_data`` | ``stack`` (after merge) |
+======================+=======================+=========================+
| .. code:: yaml | .. code:: yaml | .. code:: yaml |
| | | |
| users: | users: | users: |
| tom: | tom: | tom: |
| uid: 500 | uid: 1000 | uid: 1000 |
| roles: | roles: | roles: |
| - sysadmin | - developer | - sysadmin |
| root: | mat: | - developer |
| uid: 0 | uid: 1001 | mat: |
| | | uid: 1001 |
| | | root: |
| | | uid: 0 |
+----------------------+-----------------------+-------------------------+
Then you can select a custom merging strategy using the ``__`` key in a dict:
+----------------------+-----------------------+-------------------------+
| ``stack`` | ``yaml_data`` | ``stack`` (after merge) |
+======================+=======================+=========================+
| .. code:: yaml | .. code:: yaml | .. code:: yaml |
| | | |
| users: | users: | users: |
| tom: | __: merge-last | tom: |
| uid: 500 | tom: | uid: 1000 |
| roles: | uid: 1000 | roles: |
| - sysadmin | roles: | - sysadmin |
| root: | - developer | - developer |
| uid: 0 | mat: | mat: |
| | uid: 1001 | uid: 1001 |
| | | root: |
| | | uid: 0 |
+----------------------+-----------------------+-------------------------+
| .. code:: yaml | .. code:: yaml | .. code:: yaml |
| | | |
| users: | users: | users: |
| tom: | __: merge-first | tom: |
| uid: 500 | tom: | uid: 500 |
| roles: | uid: 1000 | roles: |
| - sysadmin | roles: | - developer |
| root: | - developer | - sysadmin |
| uid: 0 | mat: | mat: |
| | uid: 1001 | uid: 1001 |
| | | root: |
| | | uid: 0 |
+----------------------+-----------------------+-------------------------+
| .. code:: yaml | .. code:: yaml | .. code:: yaml |
| | | |
| users: | users: | users: |
| tom: | __: remove | root: |
| uid: 500 | tom: | uid: 0 |
| roles: | mat: | |
| - sysadmin | | |
| root: | | |
| uid: 0 | | |
+----------------------+-----------------------+-------------------------+
| .. code:: yaml | .. code:: yaml | .. code:: yaml |
| | | |
| users: | users: | users: |
| tom: | __: overwrite | tom: |
| uid: 500 | tom: | uid: 1000 |
| roles: | uid: 1000 | roles: |
| - sysadmin | roles: | - developer |
| root: | - developer | mat: |
| uid: 0 | mat: | uid: 1001 |
| | uid: 1001 | |
+----------------------+-----------------------+-------------------------+
You can also select a custom merging strategy using a ``__`` object in a list:
+----------------+-------------------------+-------------------------+
| ``stack`` | ``yaml_data`` | ``stack`` (after merge) |
+================+=========================+=========================+
| .. code:: yaml | .. code:: yaml | .. code:: yaml |
| | | |
| users: | users: | users: |
| - tom | - __: merge-last | - tom |
| - root | - mat | - root |
| | | - mat |
+----------------+-------------------------+-------------------------+
| .. code:: yaml | .. code:: yaml | .. code:: yaml |
| | | |
| users: | users: | users: |
| - tom | - __: merge-first | - mat |
| - root | - mat | - tom |
| | | - root |
+----------------+-------------------------+-------------------------+
| .. code:: yaml | .. code:: yaml | .. code:: yaml |
| | | |
| users: | users: | users: |
| - tom | - __: remove | - root |
| - root | - mat | |
| | - tom | |
+----------------+-------------------------+-------------------------+
| .. code:: yaml | .. code:: yaml | .. code:: yaml |
| | | |
| users: | users: | users: |
| - tom | - __: overwrite | - mat |
| - root | - mat | |
+----------------+-------------------------+-------------------------+
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import functools
import glob
import os
import posixpath
import logging
from jinja2 import FileSystemLoader, Environment
# Import Salt libs
from salt.ext import six
import salt.utils.data
import salt.utils.jinja
import salt.utils.yaml
log = logging.getLogger(__name__)
strategies = ('overwrite', 'merge-first', 'merge-last', 'remove')
def ext_pillar(minion_id, pillar, *args, **kwargs):
stack = {}
stack_config_files = list(args)
traverse = {
'pillar': functools.partial(salt.utils.data.traverse_dict_and_list, pillar),
'grains': functools.partial(salt.utils.data.traverse_dict_and_list, __grains__),
'opts': functools.partial(salt.utils.data.traverse_dict_and_list, __opts__),
}
for matcher, matchs in six.iteritems(kwargs):
t, matcher = matcher.split(':', 1)
if t not in traverse:
raise Exception('Unknown traverse option "{0}", '
'should be one of {1}'.format(t, traverse.keys()))
cfgs = matchs.get(traverse[t](matcher, None), [])
if not isinstance(cfgs, list):
cfgs = [cfgs]
stack_config_files += cfgs
for cfg in stack_config_files:
if not os.path.isfile(cfg):
log.info(
'Ignoring pillar stack cfg "%s": file does not exist', cfg)
continue
stack = _process_stack_cfg(cfg, stack, minion_id, pillar)
return stack
def _to_unix_slashes(path):
return posixpath.join(*path.split(os.sep))
def _process_stack_cfg(cfg, stack, minion_id, pillar):
log.debug('Config: %s', cfg)
basedir, filename = os.path.split(cfg)
jenv = Environment(loader=FileSystemLoader(basedir), extensions=['jinja2.ext.do', salt.utils.jinja.SerializerExtension])
jenv.globals.update({
"__opts__": __opts__,
"__salt__": __salt__,
"__grains__": __grains__,
"__stack__": {
'traverse': salt.utils.data.traverse_dict_and_list,
'cfg_path': cfg,
},
"minion_id": minion_id,
"pillar": pillar,
})
for item in _parse_stack_cfg(
jenv.get_template(filename).render(stack=stack)):
if not item.strip():
continue # silently ignore whitespace or empty lines
paths = glob.glob(os.path.join(basedir, item))
if not paths:
log.info(
'Ignoring pillar stack template "%s": can\'t find from root '
'dir "%s"', item, basedir
)
continue
for path in sorted(paths):
log.debug('YAML: basedir=%s, path=%s', basedir, path)
# FileSystemLoader always expects unix-style paths
unix_path = _to_unix_slashes(os.path.relpath(path, basedir))
obj = salt.utils.yaml.safe_load(jenv.get_template(unix_path).render(stack=stack, ymlpath=path))
if not isinstance(obj, dict):
log.info('Ignoring pillar stack template "%s": Can\'t parse '
'as a valid yaml dictionary', path)
continue
stack = _merge_dict(stack, obj)
return stack
def _cleanup(obj):
if obj:
if isinstance(obj, dict):
obj.pop('__', None)
for k, v in six.iteritems(obj):
obj[k] = _cleanup(v)
elif isinstance(obj, list) and isinstance(obj[0], dict) \
and '__' in obj[0]:
del obj[0]
return obj
def _merge_dict(stack, obj):
strategy = obj.pop('__', 'merge-last')
if strategy not in strategies:
raise Exception('Unknown strategy "{0}", should be one of {1}'.format(
strategy, strategies))
if strategy == 'overwrite':
return _cleanup(obj)
else:
for k, v in six.iteritems(obj):
if strategy == 'remove':
stack.pop(k, None)
continue
if k in stack:
if strategy == 'merge-first':
# merge-first is same as merge-last but the other way round
# so let's switch stack[k] and v
stack_k = stack[k]
stack[k] = _cleanup(v)
v = stack_k
if type(stack[k]) != type(v):
log.debug('Force overwrite, types differ: \'%s\' != \'%s\'', stack[k], v)
stack[k] = _cleanup(v)
elif isinstance(v, dict):
stack[k] = _merge_dict(stack[k], v)
elif isinstance(v, list):
stack[k] = _merge_list(stack[k], v)
else:
stack[k] = v
else:
stack[k] = _cleanup(v)
return stack
def _merge_list(stack, obj):
strategy = 'merge-last'
if obj and isinstance(obj[0], dict) and '__' in obj[0]:
strategy = obj[0]['__']
del obj[0]
if strategy not in strategies:
raise Exception('Unknown strategy "{0}", should be one of {1}'.format(
strategy, strategies))
if strategy == 'overwrite':
return obj
elif strategy == 'remove':
return [item for item in stack if item not in obj]
elif strategy == 'merge-first':
return obj + stack
else:
return stack + obj
|
saltstack/salt
|
salt/modules/pip.py
|
_clear_context
|
python
|
def _clear_context(bin_env=None):
'''
Remove the cached pip version
'''
contextkey = 'pip.version'
if bin_env is not None:
contextkey = '{0}.{1}'.format(contextkey, bin_env)
__context__.pop(contextkey, None)
|
Remove the cached pip version
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/pip.py#L131-L138
| null |
# -*- coding: utf-8 -*-
r'''
Install Python packages with pip to either the system or a virtualenv
Windows Support
===============
.. versionadded:: 2014.7.4
Salt now uses a portable python. As a result the entire pip module is now
functional on the salt installation itself. You can pip install dependencies
for your custom modules. You can even upgrade salt itself using pip. For this
to work properly, you must specify the Current Working Directory (``cwd``) and
the Pip Binary (``bin_env``) salt should use. The variable ``pip_bin`` can be
either a virtualenv path or the path to the pip binary itself.
For example, the following command will list all software installed using pip
to your current salt environment:
.. code-block:: bat
salt <minion> pip.list cwd='C:\salt\bin\Scripts' bin_env='C:\salt\bin\Scripts\pip.exe'
Specifying the ``cwd`` and ``bin_env`` options ensures you're modifying the
salt environment. If these are omitted, it will default to the local
installation of python. If python is not installed locally it will fail saying
it couldn't find pip.
State File Support
------------------
This functionality works in states as well. If you need to pip install colorama
with a state, for example, the following will work:
.. code-block:: yaml
install_colorama:
pip.installed:
- name: colorama
- cwd: 'C:\salt\bin\scripts'
- bin_env: 'C:\salt\bin\scripts\pip.exe'
- upgrade: True
Upgrading Salt using Pip
------------------------
You can now update salt using pip to any version from the 2014.7 branch
forward. Previous version require recompiling some of the dependencies which is
painful in windows.
To do this you just use pip with git to update to the version you want and then
restart the service. Here is a sample state file that upgrades salt to the head
of the 2015.5 branch:
.. code-block:: yaml
install_salt:
pip.installed:
- cwd: 'C:\salt\bin\scripts'
- bin_env: 'C:\salt\bin\scripts\pip.exe'
- editable: git+https://github.com/saltstack/salt@2015.5#egg=salt
- upgrade: True
restart_service:
service.running:
- name: salt-minion
- enable: True
- watch:
- pip: install_salt
.. note::
If you're having problems, you might try doubling the back slashes. For
example, cwd: 'C:\\salt\\bin\\scripts'. Sometimes python thinks the single
back slash is an escape character.
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import logging
import os
try:
import pkg_resources
except ImportError:
pkg_resources = None
import re
import shutil
import sys
import tempfile
# Import Salt libs
import salt.utils.data
import salt.utils.files
import salt.utils.json
import salt.utils.locales
import salt.utils.platform
import salt.utils.stringutils
import salt.utils.url
import salt.utils.versions
from salt.ext import six
from salt.exceptions import CommandExecutionError, CommandNotFoundError
# This needs to be named logger so we don't shadow it in pip.install
logger = logging.getLogger(__name__) # pylint: disable=C0103
# Don't shadow built-in's.
__func_alias__ = {
'list_': 'list'
}
VALID_PROTOS = ['http', 'https', 'ftp', 'file']
rex_pip_chain_read = re.compile(r'-r\s(.*)\n?', re.MULTILINE)
def __virtual__():
'''
There is no way to verify that pip is installed without inspecting the
entire filesystem. If it's not installed in a conventional location, the
user is required to provide the location of pip each time it is used.
'''
if pkg_resources is None:
ret = False, 'Package dependency "pkg_resource" is missing'
else:
ret = 'pip'
return ret
def _get_pip_bin(bin_env):
'''
Locate the pip binary, either from `bin_env` as a virtualenv, as the
executable itself, or from searching conventional filesystem locations
'''
if not bin_env:
logger.debug('pip: Using pip from currently-running Python')
return [os.path.normpath(sys.executable), '-m', 'pip']
python_bin = 'python.exe' if salt.utils.platform.is_windows() else 'python'
def _search_paths(*basedirs):
ret = []
for path in basedirs:
ret.extend([
os.path.join(path, python_bin),
os.path.join(path, 'bin', python_bin),
os.path.join(path, 'Scripts', python_bin)
])
return ret
# try to get python bin from virtualenv (i.e. bin_env)
if os.path.isdir(bin_env):
for bin_path in _search_paths(bin_env):
if os.path.isfile(bin_path):
if os.access(bin_path, os.X_OK):
logger.debug('pip: Found python binary: %s', bin_path)
return [os.path.normpath(bin_path), '-m', 'pip']
else:
logger.debug(
'pip: Found python binary by name but it is not '
'executable: %s', bin_path
)
raise CommandNotFoundError(
'Could not find a pip binary in virtualenv {0}'.format(bin_env)
)
# bin_env is the python or pip binary
elif os.access(bin_env, os.X_OK):
if os.path.isfile(bin_env):
# If the python binary was passed, return it
if 'python' in os.path.basename(bin_env):
return [os.path.normpath(bin_env), '-m', 'pip']
# We have been passed a pip binary, use the pip binary.
return [os.path.normpath(bin_env)]
raise CommandExecutionError(
'Could not find a pip binary within {0}'.format(bin_env)
)
else:
raise CommandNotFoundError(
'Access denied to {0}, could not find a pip binary'.format(bin_env)
)
def _get_cached_requirements(requirements, saltenv):
'''
Get the location of a cached requirements file; caching if necessary.
'''
req_file, senv = salt.utils.url.parse(requirements)
if senv:
saltenv = senv
if req_file not in __salt__['cp.list_master'](saltenv):
# Requirements file does not exist in the given saltenv.
return False
cached_requirements = __salt__['cp.is_cached'](
requirements, saltenv
)
if not cached_requirements:
# It's not cached, let's cache it.
cached_requirements = __salt__['cp.cache_file'](
requirements, saltenv
)
# Check if the master version has changed.
if __salt__['cp.hash_file'](requirements, saltenv) != \
__salt__['cp.hash_file'](cached_requirements, saltenv):
cached_requirements = __salt__['cp.cache_file'](
requirements, saltenv
)
return cached_requirements
def _get_env_activate(bin_env):
'''
Return the path to the activate binary
'''
if not bin_env:
raise CommandNotFoundError('Could not find a `activate` binary')
if os.path.isdir(bin_env):
if salt.utils.platform.is_windows():
activate_bin = os.path.join(bin_env, 'Scripts', 'activate.bat')
else:
activate_bin = os.path.join(bin_env, 'bin', 'activate')
if os.path.isfile(activate_bin):
return activate_bin
raise CommandNotFoundError('Could not find a `activate` binary')
def _find_req(link):
logger.info('_find_req -- link = %s', link)
with salt.utils.files.fopen(link) as fh_link:
child_links = rex_pip_chain_read.findall(
salt.utils.stringutils.to_unicode(fh_link.read())
)
base_path = os.path.dirname(link)
child_links = [os.path.join(base_path, d) for d in child_links]
return child_links
def _resolve_requirements_chain(requirements):
'''
Return an array of requirements file paths that can be used to complete
the no_chown==False && user != None conundrum
'''
chain = []
if isinstance(requirements, six.string_types):
requirements = [requirements]
for req_file in requirements:
chain.append(req_file)
chain.extend(_resolve_requirements_chain(_find_req(req_file)))
return chain
def _process_requirements(requirements, cmd, cwd, saltenv, user):
'''
Process the requirements argument
'''
cleanup_requirements = []
if requirements is not None:
if isinstance(requirements, six.string_types):
requirements = [r.strip() for r in requirements.split(',')]
elif not isinstance(requirements, list):
raise TypeError('requirements must be a string or list')
treq = None
for requirement in requirements:
logger.debug('TREQ IS: %s', treq)
if requirement.startswith('salt://'):
cached_requirements = _get_cached_requirements(
requirement, saltenv
)
if not cached_requirements:
ret = {'result': False,
'comment': 'pip requirements file \'{0}\' not found'
.format(requirement)}
return None, ret
requirement = cached_requirements
if user:
# Need to make a temporary copy since the user will, most
# likely, not have the right permissions to read the file
if not treq:
treq = tempfile.mkdtemp()
__salt__['file.chown'](treq, user, None)
# In Windows, just being owner of a file isn't enough. You also
# need permissions
if salt.utils.platform.is_windows():
__utils__['dacl.set_permissions'](
obj_name=treq,
principal=user,
permissions='read_execute')
current_directory = None
if not current_directory:
current_directory = os.path.abspath(os.curdir)
logger.info('_process_requirements from directory, '
'%s -- requirement: %s', cwd, requirement)
if cwd is None:
r = requirement
c = cwd
requirement_abspath = os.path.abspath(requirement)
cwd = os.path.dirname(requirement_abspath)
requirement = os.path.basename(requirement)
logger.debug('\n\tcwd: %s -> %s\n\trequirement: %s -> %s\n',
c, cwd, r, requirement
)
os.chdir(cwd)
reqs = _resolve_requirements_chain(requirement)
os.chdir(current_directory)
logger.info('request files: %s', reqs)
for req_file in reqs:
if not os.path.isabs(req_file):
req_file = os.path.join(cwd, req_file)
logger.debug('TREQ N CWD: %s -- %s -- for %s', treq, cwd, req_file)
target_path = os.path.join(treq, os.path.basename(req_file))
logger.debug('S: %s', req_file)
logger.debug('T: %s', target_path)
target_base = os.path.dirname(target_path)
if not os.path.exists(target_base):
os.makedirs(target_base, mode=0o755)
__salt__['file.chown'](target_base, user, None)
if not os.path.exists(target_path):
logger.debug(
'Copying %s to %s', req_file, target_path
)
__salt__['file.copy'](req_file, target_path)
logger.debug(
'Changing ownership of requirements file \'%s\' to '
'user \'%s\'', target_path, user
)
__salt__['file.chown'](target_path, user, None)
req_args = os.path.join(treq, requirement) if treq else requirement
cmd.extend(['--requirement', req_args])
cleanup_requirements.append(treq)
logger.debug('CLEANUP_REQUIREMENTS: %s', cleanup_requirements)
return cleanup_requirements, None
def _format_env_vars(env_vars):
ret = {}
if env_vars:
if isinstance(env_vars, dict):
for key, val in six.iteritems(env_vars):
if not isinstance(key, six.string_types):
key = str(key) # future lint: disable=blacklisted-function
if not isinstance(val, six.string_types):
val = str(val) # future lint: disable=blacklisted-function
ret[key] = val
else:
raise CommandExecutionError(
'env_vars {0} is not a dictionary'.format(env_vars))
return ret
def install(pkgs=None, # pylint: disable=R0912,R0913,R0914
requirements=None,
bin_env=None,
use_wheel=False,
no_use_wheel=False,
log=None,
proxy=None,
timeout=None,
editable=None,
find_links=None,
index_url=None,
extra_index_url=None,
no_index=False,
mirrors=None,
build=None,
target=None,
download=None,
download_cache=None,
source=None,
upgrade=False,
force_reinstall=False,
ignore_installed=False,
exists_action=None,
no_deps=False,
no_install=False,
no_download=False,
global_options=None,
install_options=None,
user=None,
cwd=None,
pre_releases=False,
cert=None,
allow_all_external=False,
allow_external=None,
allow_unverified=None,
process_dependency_links=False,
saltenv='base',
env_vars=None,
use_vt=False,
trusted_host=None,
no_cache_dir=False,
cache_dir=None,
no_binary=None,
extra_args=None,
**kwargs):
'''
Install packages with pip
Install packages individually or from a pip requirements file. Install
packages globally or to a virtualenv.
pkgs
Comma separated list of packages to install
requirements
Path to requirements
bin_env
Path to pip (or to a virtualenv). This can be used to specify the path
to the pip to use when more than one Python release is installed (e.g.
``/usr/bin/pip-2.7`` or ``/usr/bin/pip-2.6``. If a directory path is
specified, it is assumed to be a virtualenv.
.. note::
For Windows, if the pip module is being used to upgrade the pip
package, bin_env should be the path to the virtualenv or to the
python binary that should be used. The pip command is unable to
upgrade itself in Windows.
use_wheel
Prefer wheel archives (requires pip>=1.4)
no_use_wheel
Force to not use wheel archives (requires pip>=1.4,<10.0.0)
no_binary
Force to not use binary packages (requires pip >= 7.0.0)
Accepts either :all: to disable all binary packages, :none: to empty the set,
or one or more package names with commas between them
log
Log file where a complete (maximum verbosity) record will be kept
proxy
Specify a proxy in the form ``user:passwd@proxy.server:port``. Note
that the ``user:password@`` is optional and required only if you are
behind an authenticated proxy. If you provide
``user@proxy.server:port`` then you will be prompted for a password.
timeout
Set the socket timeout (default 15 seconds)
editable
install something editable (e.g.
``git+https://github.com/worldcompany/djangoembed.git#egg=djangoembed``)
find_links
URL to search for packages
index_url
Base URL of Python Package Index
extra_index_url
Extra URLs of package indexes to use in addition to ``index_url``
no_index
Ignore package index
mirrors
Specific mirror URL(s) to query (automatically adds --use-mirrors)
.. warning::
This option has been deprecated and removed in pip version 7.0.0.
Please use ``index_url`` and/or ``extra_index_url`` instead.
build
Unpack packages into ``build`` dir
target
Install packages into ``target`` dir
download
Download packages into ``download`` instead of installing them
download_cache | cache_dir
Cache downloaded packages in ``download_cache`` or ``cache_dir`` dir
source
Check out ``editable`` packages into ``source`` dir
upgrade
Upgrade all packages to the newest available version
force_reinstall
When upgrading, reinstall all packages even if they are already
up-to-date.
ignore_installed
Ignore the installed packages (reinstalling instead)
exists_action
Default action when a path already exists: (s)witch, (i)gnore, (w)ipe,
(b)ackup
no_deps
Ignore package dependencies
no_install
Download and unpack all packages, but don't actually install them
no_download
Don't download any packages, just install the ones already downloaded
(completes an install run with ``--no-install``)
install_options
Extra arguments to be supplied to the setup.py install command (e.g.
like ``--install-option='--install-scripts=/usr/local/bin'``). Use
multiple --install-option options to pass multiple options to setup.py
install. If you are using an option with a directory path, be sure to
use absolute path.
global_options
Extra global options to be supplied to the setup.py call before the
install command.
user
The user under which to run pip
cwd
Directory from which to run pip
pre_releases
Include pre-releases in the available versions
cert
Provide a path to an alternate CA bundle
allow_all_external
Allow the installation of all externally hosted files
allow_external
Allow the installation of externally hosted files (comma separated
list)
allow_unverified
Allow the installation of insecure and unverifiable files (comma
separated list)
process_dependency_links
Enable the processing of dependency links
env_vars
Set environment variables that some builds will depend on. For example,
a Python C-module may have a Makefile that needs INCLUDE_PATH set to
pick up a header file while compiling. This must be in the form of a
dictionary or a mapping.
Example:
.. code-block:: bash
salt '*' pip.install django_app env_vars="{'CUSTOM_PATH': '/opt/django_app'}"
trusted_host
Mark this host as trusted, even though it does not have valid or any
HTTPS.
use_vt
Use VT terminal emulation (see output while installing)
no_cache_dir
Disable the cache.
extra_args
pip keyword and positional arguments not yet implemented in salt
.. code-block:: yaml
salt '*' pip.install pandas extra_args="[{'--latest-pip-kwarg':'param'}, '--latest-pip-arg']"
.. warning::
If unsupported options are passed here that are not supported in a
minion's version of pip, a `No such option error` will be thrown.
Will be translated into the following pip command:
.. code-block:: bash
pip install pandas --latest-pip-kwarg param --latest-pip-arg
CLI Example:
.. code-block:: bash
salt '*' pip.install <package name>,<package2 name>
salt '*' pip.install requirements=/path/to/requirements.txt
salt '*' pip.install <package name> bin_env=/path/to/virtualenv
salt '*' pip.install <package name> bin_env=/path/to/pip_bin
Complicated CLI example::
salt '*' pip.install markdown,django \
editable=git+https://github.com/worldcompany/djangoembed.git#egg=djangoembed upgrade=True no_deps=True
'''
cmd = _get_pip_bin(bin_env)
cmd.append('install')
cleanup_requirements, error = _process_requirements(
requirements=requirements,
cmd=cmd,
cwd=cwd,
saltenv=saltenv,
user=user
)
if error:
return error
cur_version = version(bin_env)
if use_wheel:
min_version = '1.4'
max_version = '9.0.3'
too_low = salt.utils.versions.compare(ver1=cur_version, oper='<', ver2=min_version)
too_high = salt.utils.versions.compare(ver1=cur_version, oper='>', ver2=max_version)
if too_low or too_high:
logger.error(
'The --use-wheel option is only supported in pip between %s and '
'%s. The version of pip detected is %s. This option '
'will be ignored.', min_version, max_version, cur_version
)
else:
cmd.append('--use-wheel')
if no_use_wheel:
min_version = '1.4'
max_version = '9.0.3'
too_low = salt.utils.versions.compare(ver1=cur_version, oper='<', ver2=min_version)
too_high = salt.utils.versions.compare(ver1=cur_version, oper='>', ver2=max_version)
if too_low or too_high:
logger.error(
'The --no-use-wheel option is only supported in pip between %s and '
'%s. The version of pip detected is %s. This option '
'will be ignored.', min_version, max_version, cur_version
)
else:
cmd.append('--no-use-wheel')
if no_binary:
min_version = '7.0.0'
too_low = salt.utils.versions.compare(ver1=cur_version, oper='<', ver2=min_version)
if too_low:
logger.error(
'The --no-binary option is only supported in pip %s and '
'newer. The version of pip detected is %s. This option '
'will be ignored.', min_version, cur_version
)
else:
if isinstance(no_binary, list):
no_binary = ','.join(no_binary)
cmd.extend(['--no-binary', no_binary])
if log:
if os.path.isdir(log):
raise IOError(
'\'{0}\' is a directory. Use --log path_to_file'.format(log))
elif not os.access(log, os.W_OK):
raise IOError('\'{0}\' is not writeable'.format(log))
cmd.extend(['--log', log])
if proxy:
cmd.extend(['--proxy', proxy])
if timeout:
try:
if isinstance(timeout, float):
# Catch floating point input, exception will be caught in
# exception class below.
raise ValueError('Timeout cannot be a float')
int(timeout)
except ValueError:
raise ValueError(
'\'{0}\' is not a valid timeout, must be an integer'
.format(timeout)
)
cmd.extend(['--timeout', timeout])
if find_links:
if isinstance(find_links, six.string_types):
find_links = [l.strip() for l in find_links.split(',')]
for link in find_links:
if not (salt.utils.url.validate(link, VALID_PROTOS) or os.path.exists(link)):
raise CommandExecutionError(
'\'{0}\' is not a valid URL or path'.format(link)
)
cmd.extend(['--find-links', link])
if no_index and (index_url or extra_index_url):
raise CommandExecutionError(
'\'no_index\' and (\'index_url\' or \'extra_index_url\') are '
'mutually exclusive.'
)
if index_url:
if not salt.utils.url.validate(index_url, VALID_PROTOS):
raise CommandExecutionError(
'\'{0}\' is not a valid URL'.format(index_url)
)
cmd.extend(['--index-url', index_url])
if extra_index_url:
if not salt.utils.url.validate(extra_index_url, VALID_PROTOS):
raise CommandExecutionError(
'\'{0}\' is not a valid URL'.format(extra_index_url)
)
cmd.extend(['--extra-index-url', extra_index_url])
if no_index:
cmd.append('--no-index')
if mirrors:
# https://github.com/pypa/pip/pull/2641/files#diff-3ef137fb9ffdd400f117a565cd94c188L216
if salt.utils.versions.compare(ver1=cur_version, oper='>=', ver2='7.0.0'):
raise CommandExecutionError(
'pip >= 7.0.0 does not support mirror argument:'
' use index_url and/or extra_index_url instead'
)
if isinstance(mirrors, six.string_types):
mirrors = [m.strip() for m in mirrors.split(',')]
cmd.append('--use-mirrors')
for mirror in mirrors:
if not mirror.startswith('http://'):
raise CommandExecutionError(
'\'{0}\' is not a valid URL'.format(mirror)
)
cmd.extend(['--mirrors', mirror])
if build:
cmd.extend(['--build', build])
if target:
cmd.extend(['--target', target])
if download:
cmd.extend(['--download', download])
if download_cache or cache_dir:
cmd.extend(['--cache-dir' if salt.utils.versions.compare(
ver1=cur_version, oper='>=', ver2='6.0'
) else '--download-cache', download_cache or cache_dir])
if source:
cmd.extend(['--source', source])
if upgrade:
cmd.append('--upgrade')
if force_reinstall:
cmd.append('--force-reinstall')
if ignore_installed:
cmd.append('--ignore-installed')
if exists_action:
if exists_action.lower() not in ('s', 'i', 'w', 'b'):
raise CommandExecutionError(
'The exists_action pip option only supports the values '
's, i, w, and b. \'{0}\' is not valid.'.format(exists_action)
)
cmd.extend(['--exists-action', exists_action])
if no_deps:
cmd.append('--no-deps')
if no_install:
cmd.append('--no-install')
if no_download:
cmd.append('--no-download')
if no_cache_dir:
cmd.append('--no-cache-dir')
if pre_releases:
# Check the locally installed pip version
pip_version = cur_version
# From pip v1.4 the --pre flag is available
if salt.utils.versions.compare(ver1=pip_version, oper='>=', ver2='1.4'):
cmd.append('--pre')
if cert:
cmd.extend(['--cert', cert])
if global_options:
if isinstance(global_options, six.string_types):
global_options = [go.strip() for go in global_options.split(',')]
for opt in global_options:
cmd.extend(['--global-option', opt])
if install_options:
if isinstance(install_options, six.string_types):
install_options = [io.strip() for io in install_options.split(',')]
for opt in install_options:
cmd.extend(['--install-option', opt])
if pkgs:
if not isinstance(pkgs, list):
try:
pkgs = [p.strip() for p in pkgs.split(',')]
except AttributeError:
pkgs = [p.strip() for p in six.text_type(pkgs).split(',')]
pkgs = salt.utils.data.stringify(salt.utils.data.decode_list(pkgs))
# It's possible we replaced version-range commas with semicolons so
# they would survive the previous line (in the pip.installed state).
# Put the commas back in while making sure the names are contained in
# quotes, this allows for proper version spec passing salt>=0.17.0
cmd.extend([p.replace(';', ',') for p in pkgs])
elif not any([requirements, editable]):
# Starting with pip 10.0.0, if no packages are specified in the
# command, it returns a retcode 1. So instead of running the command,
# just return the output without running pip.
return {'retcode': 0, 'stdout': 'No packages to install.'}
if editable:
egg_match = re.compile(r'(?:#|#.*?&)egg=([^&]*)')
if isinstance(editable, six.string_types):
editable = [e.strip() for e in editable.split(',')]
for entry in editable:
# Is the editable local?
if not (entry == '.' or entry.startswith(('file://', '/'))):
match = egg_match.search(entry)
if not match or not match.group(1):
# Missing #egg=theEggName
raise CommandExecutionError(
'You must specify an egg for this editable'
)
cmd.extend(['--editable', entry])
if allow_all_external:
cmd.append('--allow-all-external')
if allow_external:
if isinstance(allow_external, six.string_types):
allow_external = [p.strip() for p in allow_external.split(',')]
for pkg in allow_external:
cmd.extend(['--allow-external', pkg])
if allow_unverified:
if isinstance(allow_unverified, six.string_types):
allow_unverified = \
[p.strip() for p in allow_unverified.split(',')]
for pkg in allow_unverified:
cmd.extend(['--allow-unverified', pkg])
if process_dependency_links:
cmd.append('--process-dependency-links')
if trusted_host:
cmd.extend(['--trusted-host', trusted_host])
if extra_args:
# These are arguments from the latest version of pip that
# have not yet been implemented in salt
for arg in extra_args:
# It is a keyword argument
if isinstance(arg, dict):
# There will only ever be one item in this dictionary
key, val = arg.popitem()
# Don't allow any recursion into keyword arg definitions
# Don't allow multiple definitions of a keyword
if isinstance(val, (dict, list)):
raise TypeError("Too many levels in: {}".format(key))
# This is a a normal one-to-one keyword argument
cmd.extend([key, val])
# It is a positional argument, append it to the list
else:
cmd.append(arg)
cmd_kwargs = dict(saltenv=saltenv, use_vt=use_vt, runas=user)
if kwargs:
cmd_kwargs.update(kwargs)
if env_vars:
cmd_kwargs.setdefault('env', {}).update(_format_env_vars(env_vars))
try:
if cwd:
cmd_kwargs['cwd'] = cwd
if bin_env and os.path.isdir(bin_env):
cmd_kwargs.setdefault('env', {})['VIRTUAL_ENV'] = bin_env
logger.debug(
'TRY BLOCK: end of pip.install -- cmd: %s, cmd_kwargs: %s',
cmd, cmd_kwargs
)
return __salt__['cmd.run_all'](cmd, python_shell=False, **cmd_kwargs)
finally:
_clear_context(bin_env)
for tempdir in [cr for cr in cleanup_requirements if cr is not None]:
if os.path.isdir(tempdir):
shutil.rmtree(tempdir)
def uninstall(pkgs=None,
requirements=None,
bin_env=None,
log=None,
proxy=None,
timeout=None,
user=None,
cwd=None,
saltenv='base',
use_vt=False):
'''
Uninstall packages individually or from a pip requirements file
pkgs
comma separated list of packages to install
requirements
Path to requirements file
bin_env
Path to pip (or to a virtualenv). This can be used to specify the path
to the pip to use when more than one Python release is installed (e.g.
``/usr/bin/pip-2.7`` or ``/usr/bin/pip-2.6``. If a directory path is
specified, it is assumed to be a virtualenv.
log
Log file where a complete (maximum verbosity) record will be kept
proxy
Specify a proxy in the format ``user:passwd@proxy.server:port``. Note
that the ``user:password@`` is optional and required only if you are
behind an authenticated proxy. If you provide
``user@proxy.server:port`` then you will be prompted for a password.
timeout
Set the socket timeout (default 15 seconds)
user
The user under which to run pip
cwd
Directory from which to run pip
use_vt
Use VT terminal emulation (see output while installing)
CLI Example:
.. code-block:: bash
salt '*' pip.uninstall <package name>,<package2 name>
salt '*' pip.uninstall requirements=/path/to/requirements.txt
salt '*' pip.uninstall <package name> bin_env=/path/to/virtualenv
salt '*' pip.uninstall <package name> bin_env=/path/to/pip_bin
'''
cmd = _get_pip_bin(bin_env)
cmd.extend(['uninstall', '-y'])
cleanup_requirements, error = _process_requirements(
requirements=requirements, cmd=cmd, saltenv=saltenv, user=user,
cwd=cwd
)
if error:
return error
if log:
try:
# TODO make this check if writeable
os.path.exists(log)
except IOError:
raise IOError('\'{0}\' is not writeable'.format(log))
cmd.extend(['--log', log])
if proxy:
cmd.extend(['--proxy', proxy])
if timeout:
try:
if isinstance(timeout, float):
# Catch floating point input, exception will be caught in
# exception class below.
raise ValueError('Timeout cannot be a float')
int(timeout)
except ValueError:
raise ValueError(
'\'{0}\' is not a valid timeout, must be an integer'
.format(timeout)
)
cmd.extend(['--timeout', timeout])
if pkgs:
if isinstance(pkgs, six.string_types):
pkgs = [p.strip() for p in pkgs.split(',')]
if requirements:
for requirement in requirements:
with salt.utils.files.fopen(requirement) as rq_:
for req in rq_:
req = salt.utils.stringutils.to_unicode(req)
try:
req_pkg, _ = req.split('==')
if req_pkg in pkgs:
pkgs.remove(req_pkg)
except ValueError:
pass
cmd.extend(pkgs)
cmd_kwargs = dict(python_shell=False, runas=user,
cwd=cwd, saltenv=saltenv, use_vt=use_vt)
if bin_env and os.path.isdir(bin_env):
cmd_kwargs['env'] = {'VIRTUAL_ENV': bin_env}
try:
return __salt__['cmd.run_all'](cmd, **cmd_kwargs)
finally:
_clear_context(bin_env)
for requirement in cleanup_requirements:
if requirement:
try:
os.remove(requirement)
except OSError:
pass
def freeze(bin_env=None,
user=None,
cwd=None,
use_vt=False,
env_vars=None,
**kwargs):
'''
Return a list of installed packages either globally or in the specified
virtualenv
bin_env
Path to pip (or to a virtualenv). This can be used to specify the path
to the pip to use when more than one Python release is installed (e.g.
``/usr/bin/pip-2.7`` or ``/usr/bin/pip-2.6``. If a directory path is
specified, it is assumed to be a virtualenv.
user
The user under which to run pip
cwd
Directory from which to run pip
.. note::
If the version of pip available is older than 8.0.3, the list will not
include the packages ``pip``, ``wheel``, ``setuptools``, or
``distribute`` even if they are installed.
CLI Example:
.. code-block:: bash
salt '*' pip.freeze bin_env=/home/code/path/to/virtualenv
'''
cmd = _get_pip_bin(bin_env)
cmd.append('freeze')
# Include pip, setuptools, distribute, wheel
min_version = '8.0.3'
cur_version = version(bin_env)
if salt.utils.versions.compare(ver1=cur_version, oper='<', ver2=min_version):
logger.warning(
'The version of pip installed is %s, which is older than %s. '
'The packages pip, wheel, setuptools, and distribute will not be '
'included in the output of pip.freeze', cur_version, min_version
)
else:
cmd.append('--all')
cmd_kwargs = dict(runas=user, cwd=cwd, use_vt=use_vt, python_shell=False)
if kwargs:
cmd_kwargs.update(**kwargs)
if bin_env and os.path.isdir(bin_env):
cmd_kwargs['env'] = {'VIRTUAL_ENV': bin_env}
if env_vars:
cmd_kwargs.setdefault('env', {}).update(_format_env_vars(env_vars))
result = __salt__['cmd.run_all'](cmd, **cmd_kwargs)
if result['retcode']:
raise CommandExecutionError(result['stderr'], info=result)
return result['stdout'].splitlines()
def list_(prefix=None,
bin_env=None,
user=None,
cwd=None,
env_vars=None,
**kwargs):
'''
Filter list of installed apps from ``freeze`` and check to see if
``prefix`` exists in the list of packages installed.
.. note::
If the version of pip available is older than 8.0.3, the packages
``wheel``, ``setuptools``, and ``distribute`` will not be reported by
this function even if they are installed. Unlike :py:func:`pip.freeze
<salt.modules.pip.freeze>`, this function always reports the version of
pip which is installed.
CLI Example:
.. code-block:: bash
salt '*' pip.list salt
'''
packages = {}
if prefix is None or 'pip'.startswith(prefix):
packages['pip'] = version(bin_env)
for line in freeze(bin_env=bin_env,
user=user,
cwd=cwd,
env_vars=env_vars,
**kwargs):
if line.startswith('-f') or line.startswith('#'):
# ignore -f line as it contains --find-links directory
# ignore comment lines
continue
elif line.startswith('-e hg+not trust'):
# ignore hg + not trust problem
continue
elif line.startswith('-e'):
line = line.split('-e ')[1]
if '#egg=' in line:
version_, name = line.split('#egg=')
else:
if len(line.split('===')) >= 2:
name = line.split('===')[0]
version_ = line.split('===')[1]
elif len(line.split('==')) >= 2:
name = line.split('==')[0]
version_ = line.split('==')[1]
elif len(line.split('===')) >= 2:
name = line.split('===')[0]
version_ = line.split('===')[1]
elif len(line.split('==')) >= 2:
name = line.split('==')[0]
version_ = line.split('==')[1]
else:
logger.error('Can\'t parse line \'%s\'', line)
continue
if prefix:
if name.lower().startswith(prefix.lower()):
packages[name] = version_
else:
packages[name] = version_
return packages
def version(bin_env=None):
'''
.. versionadded:: 0.17.0
Returns the version of pip. Use ``bin_env`` to specify the path to a
virtualenv and get the version of pip in that virtualenv.
If unable to detect the pip version, returns ``None``.
CLI Example:
.. code-block:: bash
salt '*' pip.version
'''
contextkey = 'pip.version'
if bin_env is not None:
contextkey = '{0}.{1}'.format(contextkey, bin_env)
if contextkey in __context__:
return __context__[contextkey]
cmd = _get_pip_bin(bin_env)[:]
cmd.append('--version')
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
if ret['retcode']:
raise CommandNotFoundError('Could not find a `pip` binary')
try:
pip_version = re.match(r'^pip (\S+)', ret['stdout']).group(1)
except AttributeError:
pip_version = None
__context__[contextkey] = pip_version
return pip_version
def list_upgrades(bin_env=None,
user=None,
cwd=None):
'''
Check whether or not an upgrade is available for all packages
CLI Example:
.. code-block:: bash
salt '*' pip.list_upgrades
'''
cmd = _get_pip_bin(bin_env)
cmd.extend(['list', '--outdated'])
pip_version = version(bin_env)
# Pip started supporting the ability to output json starting with 9.0.0
min_version = '9.0'
if salt.utils.versions.compare(ver1=pip_version,
oper='>=',
ver2=min_version):
cmd.append('--format=json')
cmd_kwargs = dict(cwd=cwd, runas=user)
if bin_env and os.path.isdir(bin_env):
cmd_kwargs['env'] = {'VIRTUAL_ENV': bin_env}
result = __salt__['cmd.run_all'](cmd, **cmd_kwargs)
if result['retcode']:
raise CommandExecutionError(result['stderr'], info=result)
packages = {}
# Pip started supporting the ability to output json starting with 9.0.0
# Older versions will have to parse stdout
if salt.utils.versions.compare(ver1=pip_version, oper='<', ver2='9.0.0'):
# Pip versions < 8.0.0 had a different output format
# Sample data:
# pip (Current: 7.1.2 Latest: 10.0.1 [wheel])
# psutil (Current: 5.2.2 Latest: 5.4.5 [wheel])
# pyasn1 (Current: 0.2.3 Latest: 0.4.2 [wheel])
# pycparser (Current: 2.17 Latest: 2.18 [sdist])
if salt.utils.versions.compare(ver1=pip_version, oper='<', ver2='8.0.0'):
logger.debug('pip module: Old output format')
pat = re.compile(r'(\S*)\s+\(.*Latest:\s+(.*)\)')
# New output format for version 8.0.0+
# Sample data:
# pip (8.0.0) - Latest: 10.0.1 [wheel]
# psutil (5.2.2) - Latest: 5.4.5 [wheel]
# pyasn1 (0.2.3) - Latest: 0.4.2 [wheel]
# pycparser (2.17) - Latest: 2.18 [sdist]
else:
logger.debug('pip module: New output format')
pat = re.compile(r'(\S*)\s+\(.*\)\s+-\s+Latest:\s+(.*)')
for line in result['stdout'].splitlines():
match = pat.search(line)
if match:
name, version_ = match.groups()
else:
logger.error('Can\'t parse line \'%s\'', line)
continue
packages[name] = version_
else:
logger.debug('pip module: JSON output format')
try:
pkgs = salt.utils.json.loads(result['stdout'], strict=False)
except ValueError:
raise CommandExecutionError('Invalid JSON', info=result)
for pkg in pkgs:
packages[pkg['name']] = '{0} [{1}]'.format(pkg['latest_version'],
pkg['latest_filetype'])
return packages
def is_installed(pkgname=None,
bin_env=None,
user=None,
cwd=None):
'''
.. versionadded:: 2018.3.0
Filter list of installed apps from ``freeze`` and return True or False if
``pkgname`` exists in the list of packages installed.
.. note::
If the version of pip available is older than 8.0.3, the packages
wheel, setuptools, and distribute will not be reported by this function
even if they are installed. Unlike :py:func:`pip.freeze
<salt.modules.pip.freeze>`, this function always reports the version of
pip which is installed.
CLI Example:
.. code-block:: bash
salt '*' pip.is_installed salt
'''
for line in freeze(bin_env=bin_env, user=user, cwd=cwd):
if line.startswith('-f') or line.startswith('#'):
# ignore -f line as it contains --find-links directory
# ignore comment lines
continue
elif line.startswith('-e hg+not trust'):
# ignore hg + not trust problem
continue
elif line.startswith('-e'):
line = line.split('-e ')[1]
version_, name = line.split('#egg=')
elif len(line.split('===')) >= 2:
name = line.split('===')[0]
version_ = line.split('===')[1]
elif len(line.split('==')) >= 2:
name = line.split('==')[0]
version_ = line.split('==')[1]
else:
logger.error('Can\'t parse line \'%s\'', line)
continue
if pkgname:
if pkgname == name.lower():
return True
return False
def upgrade_available(pkg,
bin_env=None,
user=None,
cwd=None):
'''
.. versionadded:: 2015.5.0
Check whether or not an upgrade is available for a given package
CLI Example:
.. code-block:: bash
salt '*' pip.upgrade_available <package name>
'''
return pkg in list_upgrades(bin_env=bin_env, user=user, cwd=cwd)
def upgrade(bin_env=None,
user=None,
cwd=None,
use_vt=False):
'''
.. versionadded:: 2015.5.0
Upgrades outdated pip packages.
.. note::
On Windows you can't update salt from pip using salt, so salt will be
skipped
Returns a dict containing the changes.
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
CLI Example:
.. code-block:: bash
salt '*' pip.upgrade
'''
ret = {'changes': {},
'result': True,
'comment': '',
}
cmd = _get_pip_bin(bin_env)
cmd.extend(['install', '-U'])
old = list_(bin_env=bin_env, user=user, cwd=cwd)
cmd_kwargs = dict(cwd=cwd, use_vt=use_vt)
if bin_env and os.path.isdir(bin_env):
cmd_kwargs['env'] = {'VIRTUAL_ENV': bin_env}
errors = False
for pkg in list_upgrades(bin_env=bin_env, user=user, cwd=cwd):
if pkg == 'salt':
if salt.utils.platform.is_windows():
continue
result = __salt__['cmd.run_all'](cmd + [pkg], **cmd_kwargs)
if result['retcode'] != 0:
errors = True
if 'stderr' in result:
ret['comment'] += result['stderr']
if errors:
ret['result'] = False
_clear_context(bin_env)
new = list_(bin_env=bin_env, user=user, cwd=cwd)
ret['changes'] = salt.utils.data.compare_dicts(old, new)
return ret
def list_all_versions(pkg,
bin_env=None,
include_alpha=False,
include_beta=False,
include_rc=False,
user=None,
cwd=None,
index_url=None,
extra_index_url=None):
'''
.. versionadded:: 2017.7.3
List all available versions of a pip package
pkg
The package to check
bin_env
Path to pip (or to a virtualenv). This can be used to specify the path
to the pip to use when more than one Python release is installed (e.g.
``/usr/bin/pip-2.7`` or ``/usr/bin/pip-2.6``. If a directory path is
specified, it is assumed to be a virtualenv.
include_alpha
Include alpha versions in the list
include_beta
Include beta versions in the list
include_rc
Include release candidates versions in the list
user
The user under which to run pip
cwd
Directory from which to run pip
index_url
Base URL of Python Package Index
.. versionadded:: 2019.2.0
extra_index_url
Additional URL of Python Package Index
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' pip.list_all_versions <package name>
'''
cmd = _get_pip_bin(bin_env)
cmd.extend(['install', '{0}==versions'.format(pkg)])
if index_url:
if not salt.utils.url.validate(index_url, VALID_PROTOS):
raise CommandExecutionError(
'\'{0}\' is not a valid URL'.format(index_url)
)
cmd.extend(['--index-url', index_url])
if extra_index_url:
if not salt.utils.url.validate(extra_index_url, VALID_PROTOS):
raise CommandExecutionError(
'\'{0}\' is not a valid URL'.format(extra_index_url)
)
cmd.extend(['--extra-index-url', extra_index_url])
cmd_kwargs = dict(cwd=cwd, runas=user, output_loglevel='quiet', redirect_stderr=True)
if bin_env and os.path.isdir(bin_env):
cmd_kwargs['env'] = {'VIRTUAL_ENV': bin_env}
result = __salt__['cmd.run_all'](cmd, **cmd_kwargs)
filtered = []
if not include_alpha:
filtered.append('a')
if not include_beta:
filtered.append('b')
if not include_rc:
filtered.append('rc')
if filtered:
excludes = re.compile(r'^((?!{0}).)*$'.format('|'.join(filtered)))
else:
excludes = re.compile(r'')
versions = []
for line in result['stdout'].splitlines():
match = re.search(r'\s*Could not find a version.* \(from versions: (.*)\)', line)
if match:
versions = [v for v in match.group(1).split(', ') if v and excludes.match(v)]
versions.sort(key=pkg_resources.parse_version)
break
if not versions:
return None
return versions
|
saltstack/salt
|
salt/modules/pip.py
|
_get_pip_bin
|
python
|
def _get_pip_bin(bin_env):
'''
Locate the pip binary, either from `bin_env` as a virtualenv, as the
executable itself, or from searching conventional filesystem locations
'''
if not bin_env:
logger.debug('pip: Using pip from currently-running Python')
return [os.path.normpath(sys.executable), '-m', 'pip']
python_bin = 'python.exe' if salt.utils.platform.is_windows() else 'python'
def _search_paths(*basedirs):
ret = []
for path in basedirs:
ret.extend([
os.path.join(path, python_bin),
os.path.join(path, 'bin', python_bin),
os.path.join(path, 'Scripts', python_bin)
])
return ret
# try to get python bin from virtualenv (i.e. bin_env)
if os.path.isdir(bin_env):
for bin_path in _search_paths(bin_env):
if os.path.isfile(bin_path):
if os.access(bin_path, os.X_OK):
logger.debug('pip: Found python binary: %s', bin_path)
return [os.path.normpath(bin_path), '-m', 'pip']
else:
logger.debug(
'pip: Found python binary by name but it is not '
'executable: %s', bin_path
)
raise CommandNotFoundError(
'Could not find a pip binary in virtualenv {0}'.format(bin_env)
)
# bin_env is the python or pip binary
elif os.access(bin_env, os.X_OK):
if os.path.isfile(bin_env):
# If the python binary was passed, return it
if 'python' in os.path.basename(bin_env):
return [os.path.normpath(bin_env), '-m', 'pip']
# We have been passed a pip binary, use the pip binary.
return [os.path.normpath(bin_env)]
raise CommandExecutionError(
'Could not find a pip binary within {0}'.format(bin_env)
)
else:
raise CommandNotFoundError(
'Access denied to {0}, could not find a pip binary'.format(bin_env)
)
|
Locate the pip binary, either from `bin_env` as a virtualenv, as the
executable itself, or from searching conventional filesystem locations
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/pip.py#L141-L193
|
[
"def _search_paths(*basedirs):\n ret = []\n for path in basedirs:\n ret.extend([\n os.path.join(path, python_bin),\n os.path.join(path, 'bin', python_bin),\n os.path.join(path, 'Scripts', python_bin)\n ])\n return ret\n"
] |
# -*- coding: utf-8 -*-
r'''
Install Python packages with pip to either the system or a virtualenv
Windows Support
===============
.. versionadded:: 2014.7.4
Salt now uses a portable python. As a result the entire pip module is now
functional on the salt installation itself. You can pip install dependencies
for your custom modules. You can even upgrade salt itself using pip. For this
to work properly, you must specify the Current Working Directory (``cwd``) and
the Pip Binary (``bin_env``) salt should use. The variable ``pip_bin`` can be
either a virtualenv path or the path to the pip binary itself.
For example, the following command will list all software installed using pip
to your current salt environment:
.. code-block:: bat
salt <minion> pip.list cwd='C:\salt\bin\Scripts' bin_env='C:\salt\bin\Scripts\pip.exe'
Specifying the ``cwd`` and ``bin_env`` options ensures you're modifying the
salt environment. If these are omitted, it will default to the local
installation of python. If python is not installed locally it will fail saying
it couldn't find pip.
State File Support
------------------
This functionality works in states as well. If you need to pip install colorama
with a state, for example, the following will work:
.. code-block:: yaml
install_colorama:
pip.installed:
- name: colorama
- cwd: 'C:\salt\bin\scripts'
- bin_env: 'C:\salt\bin\scripts\pip.exe'
- upgrade: True
Upgrading Salt using Pip
------------------------
You can now update salt using pip to any version from the 2014.7 branch
forward. Previous version require recompiling some of the dependencies which is
painful in windows.
To do this you just use pip with git to update to the version you want and then
restart the service. Here is a sample state file that upgrades salt to the head
of the 2015.5 branch:
.. code-block:: yaml
install_salt:
pip.installed:
- cwd: 'C:\salt\bin\scripts'
- bin_env: 'C:\salt\bin\scripts\pip.exe'
- editable: git+https://github.com/saltstack/salt@2015.5#egg=salt
- upgrade: True
restart_service:
service.running:
- name: salt-minion
- enable: True
- watch:
- pip: install_salt
.. note::
If you're having problems, you might try doubling the back slashes. For
example, cwd: 'C:\\salt\\bin\\scripts'. Sometimes python thinks the single
back slash is an escape character.
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import logging
import os
try:
import pkg_resources
except ImportError:
pkg_resources = None
import re
import shutil
import sys
import tempfile
# Import Salt libs
import salt.utils.data
import salt.utils.files
import salt.utils.json
import salt.utils.locales
import salt.utils.platform
import salt.utils.stringutils
import salt.utils.url
import salt.utils.versions
from salt.ext import six
from salt.exceptions import CommandExecutionError, CommandNotFoundError
# This needs to be named logger so we don't shadow it in pip.install
logger = logging.getLogger(__name__) # pylint: disable=C0103
# Don't shadow built-in's.
__func_alias__ = {
'list_': 'list'
}
VALID_PROTOS = ['http', 'https', 'ftp', 'file']
rex_pip_chain_read = re.compile(r'-r\s(.*)\n?', re.MULTILINE)
def __virtual__():
'''
There is no way to verify that pip is installed without inspecting the
entire filesystem. If it's not installed in a conventional location, the
user is required to provide the location of pip each time it is used.
'''
if pkg_resources is None:
ret = False, 'Package dependency "pkg_resource" is missing'
else:
ret = 'pip'
return ret
def _clear_context(bin_env=None):
'''
Remove the cached pip version
'''
contextkey = 'pip.version'
if bin_env is not None:
contextkey = '{0}.{1}'.format(contextkey, bin_env)
__context__.pop(contextkey, None)
def _get_cached_requirements(requirements, saltenv):
'''
Get the location of a cached requirements file; caching if necessary.
'''
req_file, senv = salt.utils.url.parse(requirements)
if senv:
saltenv = senv
if req_file not in __salt__['cp.list_master'](saltenv):
# Requirements file does not exist in the given saltenv.
return False
cached_requirements = __salt__['cp.is_cached'](
requirements, saltenv
)
if not cached_requirements:
# It's not cached, let's cache it.
cached_requirements = __salt__['cp.cache_file'](
requirements, saltenv
)
# Check if the master version has changed.
if __salt__['cp.hash_file'](requirements, saltenv) != \
__salt__['cp.hash_file'](cached_requirements, saltenv):
cached_requirements = __salt__['cp.cache_file'](
requirements, saltenv
)
return cached_requirements
def _get_env_activate(bin_env):
'''
Return the path to the activate binary
'''
if not bin_env:
raise CommandNotFoundError('Could not find a `activate` binary')
if os.path.isdir(bin_env):
if salt.utils.platform.is_windows():
activate_bin = os.path.join(bin_env, 'Scripts', 'activate.bat')
else:
activate_bin = os.path.join(bin_env, 'bin', 'activate')
if os.path.isfile(activate_bin):
return activate_bin
raise CommandNotFoundError('Could not find a `activate` binary')
def _find_req(link):
logger.info('_find_req -- link = %s', link)
with salt.utils.files.fopen(link) as fh_link:
child_links = rex_pip_chain_read.findall(
salt.utils.stringutils.to_unicode(fh_link.read())
)
base_path = os.path.dirname(link)
child_links = [os.path.join(base_path, d) for d in child_links]
return child_links
def _resolve_requirements_chain(requirements):
'''
Return an array of requirements file paths that can be used to complete
the no_chown==False && user != None conundrum
'''
chain = []
if isinstance(requirements, six.string_types):
requirements = [requirements]
for req_file in requirements:
chain.append(req_file)
chain.extend(_resolve_requirements_chain(_find_req(req_file)))
return chain
def _process_requirements(requirements, cmd, cwd, saltenv, user):
'''
Process the requirements argument
'''
cleanup_requirements = []
if requirements is not None:
if isinstance(requirements, six.string_types):
requirements = [r.strip() for r in requirements.split(',')]
elif not isinstance(requirements, list):
raise TypeError('requirements must be a string or list')
treq = None
for requirement in requirements:
logger.debug('TREQ IS: %s', treq)
if requirement.startswith('salt://'):
cached_requirements = _get_cached_requirements(
requirement, saltenv
)
if not cached_requirements:
ret = {'result': False,
'comment': 'pip requirements file \'{0}\' not found'
.format(requirement)}
return None, ret
requirement = cached_requirements
if user:
# Need to make a temporary copy since the user will, most
# likely, not have the right permissions to read the file
if not treq:
treq = tempfile.mkdtemp()
__salt__['file.chown'](treq, user, None)
# In Windows, just being owner of a file isn't enough. You also
# need permissions
if salt.utils.platform.is_windows():
__utils__['dacl.set_permissions'](
obj_name=treq,
principal=user,
permissions='read_execute')
current_directory = None
if not current_directory:
current_directory = os.path.abspath(os.curdir)
logger.info('_process_requirements from directory, '
'%s -- requirement: %s', cwd, requirement)
if cwd is None:
r = requirement
c = cwd
requirement_abspath = os.path.abspath(requirement)
cwd = os.path.dirname(requirement_abspath)
requirement = os.path.basename(requirement)
logger.debug('\n\tcwd: %s -> %s\n\trequirement: %s -> %s\n',
c, cwd, r, requirement
)
os.chdir(cwd)
reqs = _resolve_requirements_chain(requirement)
os.chdir(current_directory)
logger.info('request files: %s', reqs)
for req_file in reqs:
if not os.path.isabs(req_file):
req_file = os.path.join(cwd, req_file)
logger.debug('TREQ N CWD: %s -- %s -- for %s', treq, cwd, req_file)
target_path = os.path.join(treq, os.path.basename(req_file))
logger.debug('S: %s', req_file)
logger.debug('T: %s', target_path)
target_base = os.path.dirname(target_path)
if not os.path.exists(target_base):
os.makedirs(target_base, mode=0o755)
__salt__['file.chown'](target_base, user, None)
if not os.path.exists(target_path):
logger.debug(
'Copying %s to %s', req_file, target_path
)
__salt__['file.copy'](req_file, target_path)
logger.debug(
'Changing ownership of requirements file \'%s\' to '
'user \'%s\'', target_path, user
)
__salt__['file.chown'](target_path, user, None)
req_args = os.path.join(treq, requirement) if treq else requirement
cmd.extend(['--requirement', req_args])
cleanup_requirements.append(treq)
logger.debug('CLEANUP_REQUIREMENTS: %s', cleanup_requirements)
return cleanup_requirements, None
def _format_env_vars(env_vars):
ret = {}
if env_vars:
if isinstance(env_vars, dict):
for key, val in six.iteritems(env_vars):
if not isinstance(key, six.string_types):
key = str(key) # future lint: disable=blacklisted-function
if not isinstance(val, six.string_types):
val = str(val) # future lint: disable=blacklisted-function
ret[key] = val
else:
raise CommandExecutionError(
'env_vars {0} is not a dictionary'.format(env_vars))
return ret
def install(pkgs=None, # pylint: disable=R0912,R0913,R0914
requirements=None,
bin_env=None,
use_wheel=False,
no_use_wheel=False,
log=None,
proxy=None,
timeout=None,
editable=None,
find_links=None,
index_url=None,
extra_index_url=None,
no_index=False,
mirrors=None,
build=None,
target=None,
download=None,
download_cache=None,
source=None,
upgrade=False,
force_reinstall=False,
ignore_installed=False,
exists_action=None,
no_deps=False,
no_install=False,
no_download=False,
global_options=None,
install_options=None,
user=None,
cwd=None,
pre_releases=False,
cert=None,
allow_all_external=False,
allow_external=None,
allow_unverified=None,
process_dependency_links=False,
saltenv='base',
env_vars=None,
use_vt=False,
trusted_host=None,
no_cache_dir=False,
cache_dir=None,
no_binary=None,
extra_args=None,
**kwargs):
'''
Install packages with pip
Install packages individually or from a pip requirements file. Install
packages globally or to a virtualenv.
pkgs
Comma separated list of packages to install
requirements
Path to requirements
bin_env
Path to pip (or to a virtualenv). This can be used to specify the path
to the pip to use when more than one Python release is installed (e.g.
``/usr/bin/pip-2.7`` or ``/usr/bin/pip-2.6``. If a directory path is
specified, it is assumed to be a virtualenv.
.. note::
For Windows, if the pip module is being used to upgrade the pip
package, bin_env should be the path to the virtualenv or to the
python binary that should be used. The pip command is unable to
upgrade itself in Windows.
use_wheel
Prefer wheel archives (requires pip>=1.4)
no_use_wheel
Force to not use wheel archives (requires pip>=1.4,<10.0.0)
no_binary
Force to not use binary packages (requires pip >= 7.0.0)
Accepts either :all: to disable all binary packages, :none: to empty the set,
or one or more package names with commas between them
log
Log file where a complete (maximum verbosity) record will be kept
proxy
Specify a proxy in the form ``user:passwd@proxy.server:port``. Note
that the ``user:password@`` is optional and required only if you are
behind an authenticated proxy. If you provide
``user@proxy.server:port`` then you will be prompted for a password.
timeout
Set the socket timeout (default 15 seconds)
editable
install something editable (e.g.
``git+https://github.com/worldcompany/djangoembed.git#egg=djangoembed``)
find_links
URL to search for packages
index_url
Base URL of Python Package Index
extra_index_url
Extra URLs of package indexes to use in addition to ``index_url``
no_index
Ignore package index
mirrors
Specific mirror URL(s) to query (automatically adds --use-mirrors)
.. warning::
This option has been deprecated and removed in pip version 7.0.0.
Please use ``index_url`` and/or ``extra_index_url`` instead.
build
Unpack packages into ``build`` dir
target
Install packages into ``target`` dir
download
Download packages into ``download`` instead of installing them
download_cache | cache_dir
Cache downloaded packages in ``download_cache`` or ``cache_dir`` dir
source
Check out ``editable`` packages into ``source`` dir
upgrade
Upgrade all packages to the newest available version
force_reinstall
When upgrading, reinstall all packages even if they are already
up-to-date.
ignore_installed
Ignore the installed packages (reinstalling instead)
exists_action
Default action when a path already exists: (s)witch, (i)gnore, (w)ipe,
(b)ackup
no_deps
Ignore package dependencies
no_install
Download and unpack all packages, but don't actually install them
no_download
Don't download any packages, just install the ones already downloaded
(completes an install run with ``--no-install``)
install_options
Extra arguments to be supplied to the setup.py install command (e.g.
like ``--install-option='--install-scripts=/usr/local/bin'``). Use
multiple --install-option options to pass multiple options to setup.py
install. If you are using an option with a directory path, be sure to
use absolute path.
global_options
Extra global options to be supplied to the setup.py call before the
install command.
user
The user under which to run pip
cwd
Directory from which to run pip
pre_releases
Include pre-releases in the available versions
cert
Provide a path to an alternate CA bundle
allow_all_external
Allow the installation of all externally hosted files
allow_external
Allow the installation of externally hosted files (comma separated
list)
allow_unverified
Allow the installation of insecure and unverifiable files (comma
separated list)
process_dependency_links
Enable the processing of dependency links
env_vars
Set environment variables that some builds will depend on. For example,
a Python C-module may have a Makefile that needs INCLUDE_PATH set to
pick up a header file while compiling. This must be in the form of a
dictionary or a mapping.
Example:
.. code-block:: bash
salt '*' pip.install django_app env_vars="{'CUSTOM_PATH': '/opt/django_app'}"
trusted_host
Mark this host as trusted, even though it does not have valid or any
HTTPS.
use_vt
Use VT terminal emulation (see output while installing)
no_cache_dir
Disable the cache.
extra_args
pip keyword and positional arguments not yet implemented in salt
.. code-block:: yaml
salt '*' pip.install pandas extra_args="[{'--latest-pip-kwarg':'param'}, '--latest-pip-arg']"
.. warning::
If unsupported options are passed here that are not supported in a
minion's version of pip, a `No such option error` will be thrown.
Will be translated into the following pip command:
.. code-block:: bash
pip install pandas --latest-pip-kwarg param --latest-pip-arg
CLI Example:
.. code-block:: bash
salt '*' pip.install <package name>,<package2 name>
salt '*' pip.install requirements=/path/to/requirements.txt
salt '*' pip.install <package name> bin_env=/path/to/virtualenv
salt '*' pip.install <package name> bin_env=/path/to/pip_bin
Complicated CLI example::
salt '*' pip.install markdown,django \
editable=git+https://github.com/worldcompany/djangoembed.git#egg=djangoembed upgrade=True no_deps=True
'''
cmd = _get_pip_bin(bin_env)
cmd.append('install')
cleanup_requirements, error = _process_requirements(
requirements=requirements,
cmd=cmd,
cwd=cwd,
saltenv=saltenv,
user=user
)
if error:
return error
cur_version = version(bin_env)
if use_wheel:
min_version = '1.4'
max_version = '9.0.3'
too_low = salt.utils.versions.compare(ver1=cur_version, oper='<', ver2=min_version)
too_high = salt.utils.versions.compare(ver1=cur_version, oper='>', ver2=max_version)
if too_low or too_high:
logger.error(
'The --use-wheel option is only supported in pip between %s and '
'%s. The version of pip detected is %s. This option '
'will be ignored.', min_version, max_version, cur_version
)
else:
cmd.append('--use-wheel')
if no_use_wheel:
min_version = '1.4'
max_version = '9.0.3'
too_low = salt.utils.versions.compare(ver1=cur_version, oper='<', ver2=min_version)
too_high = salt.utils.versions.compare(ver1=cur_version, oper='>', ver2=max_version)
if too_low or too_high:
logger.error(
'The --no-use-wheel option is only supported in pip between %s and '
'%s. The version of pip detected is %s. This option '
'will be ignored.', min_version, max_version, cur_version
)
else:
cmd.append('--no-use-wheel')
if no_binary:
min_version = '7.0.0'
too_low = salt.utils.versions.compare(ver1=cur_version, oper='<', ver2=min_version)
if too_low:
logger.error(
'The --no-binary option is only supported in pip %s and '
'newer. The version of pip detected is %s. This option '
'will be ignored.', min_version, cur_version
)
else:
if isinstance(no_binary, list):
no_binary = ','.join(no_binary)
cmd.extend(['--no-binary', no_binary])
if log:
if os.path.isdir(log):
raise IOError(
'\'{0}\' is a directory. Use --log path_to_file'.format(log))
elif not os.access(log, os.W_OK):
raise IOError('\'{0}\' is not writeable'.format(log))
cmd.extend(['--log', log])
if proxy:
cmd.extend(['--proxy', proxy])
if timeout:
try:
if isinstance(timeout, float):
# Catch floating point input, exception will be caught in
# exception class below.
raise ValueError('Timeout cannot be a float')
int(timeout)
except ValueError:
raise ValueError(
'\'{0}\' is not a valid timeout, must be an integer'
.format(timeout)
)
cmd.extend(['--timeout', timeout])
if find_links:
if isinstance(find_links, six.string_types):
find_links = [l.strip() for l in find_links.split(',')]
for link in find_links:
if not (salt.utils.url.validate(link, VALID_PROTOS) or os.path.exists(link)):
raise CommandExecutionError(
'\'{0}\' is not a valid URL or path'.format(link)
)
cmd.extend(['--find-links', link])
if no_index and (index_url or extra_index_url):
raise CommandExecutionError(
'\'no_index\' and (\'index_url\' or \'extra_index_url\') are '
'mutually exclusive.'
)
if index_url:
if not salt.utils.url.validate(index_url, VALID_PROTOS):
raise CommandExecutionError(
'\'{0}\' is not a valid URL'.format(index_url)
)
cmd.extend(['--index-url', index_url])
if extra_index_url:
if not salt.utils.url.validate(extra_index_url, VALID_PROTOS):
raise CommandExecutionError(
'\'{0}\' is not a valid URL'.format(extra_index_url)
)
cmd.extend(['--extra-index-url', extra_index_url])
if no_index:
cmd.append('--no-index')
if mirrors:
# https://github.com/pypa/pip/pull/2641/files#diff-3ef137fb9ffdd400f117a565cd94c188L216
if salt.utils.versions.compare(ver1=cur_version, oper='>=', ver2='7.0.0'):
raise CommandExecutionError(
'pip >= 7.0.0 does not support mirror argument:'
' use index_url and/or extra_index_url instead'
)
if isinstance(mirrors, six.string_types):
mirrors = [m.strip() for m in mirrors.split(',')]
cmd.append('--use-mirrors')
for mirror in mirrors:
if not mirror.startswith('http://'):
raise CommandExecutionError(
'\'{0}\' is not a valid URL'.format(mirror)
)
cmd.extend(['--mirrors', mirror])
if build:
cmd.extend(['--build', build])
if target:
cmd.extend(['--target', target])
if download:
cmd.extend(['--download', download])
if download_cache or cache_dir:
cmd.extend(['--cache-dir' if salt.utils.versions.compare(
ver1=cur_version, oper='>=', ver2='6.0'
) else '--download-cache', download_cache or cache_dir])
if source:
cmd.extend(['--source', source])
if upgrade:
cmd.append('--upgrade')
if force_reinstall:
cmd.append('--force-reinstall')
if ignore_installed:
cmd.append('--ignore-installed')
if exists_action:
if exists_action.lower() not in ('s', 'i', 'w', 'b'):
raise CommandExecutionError(
'The exists_action pip option only supports the values '
's, i, w, and b. \'{0}\' is not valid.'.format(exists_action)
)
cmd.extend(['--exists-action', exists_action])
if no_deps:
cmd.append('--no-deps')
if no_install:
cmd.append('--no-install')
if no_download:
cmd.append('--no-download')
if no_cache_dir:
cmd.append('--no-cache-dir')
if pre_releases:
# Check the locally installed pip version
pip_version = cur_version
# From pip v1.4 the --pre flag is available
if salt.utils.versions.compare(ver1=pip_version, oper='>=', ver2='1.4'):
cmd.append('--pre')
if cert:
cmd.extend(['--cert', cert])
if global_options:
if isinstance(global_options, six.string_types):
global_options = [go.strip() for go in global_options.split(',')]
for opt in global_options:
cmd.extend(['--global-option', opt])
if install_options:
if isinstance(install_options, six.string_types):
install_options = [io.strip() for io in install_options.split(',')]
for opt in install_options:
cmd.extend(['--install-option', opt])
if pkgs:
if not isinstance(pkgs, list):
try:
pkgs = [p.strip() for p in pkgs.split(',')]
except AttributeError:
pkgs = [p.strip() for p in six.text_type(pkgs).split(',')]
pkgs = salt.utils.data.stringify(salt.utils.data.decode_list(pkgs))
# It's possible we replaced version-range commas with semicolons so
# they would survive the previous line (in the pip.installed state).
# Put the commas back in while making sure the names are contained in
# quotes, this allows for proper version spec passing salt>=0.17.0
cmd.extend([p.replace(';', ',') for p in pkgs])
elif not any([requirements, editable]):
# Starting with pip 10.0.0, if no packages are specified in the
# command, it returns a retcode 1. So instead of running the command,
# just return the output without running pip.
return {'retcode': 0, 'stdout': 'No packages to install.'}
if editable:
egg_match = re.compile(r'(?:#|#.*?&)egg=([^&]*)')
if isinstance(editable, six.string_types):
editable = [e.strip() for e in editable.split(',')]
for entry in editable:
# Is the editable local?
if not (entry == '.' or entry.startswith(('file://', '/'))):
match = egg_match.search(entry)
if not match or not match.group(1):
# Missing #egg=theEggName
raise CommandExecutionError(
'You must specify an egg for this editable'
)
cmd.extend(['--editable', entry])
if allow_all_external:
cmd.append('--allow-all-external')
if allow_external:
if isinstance(allow_external, six.string_types):
allow_external = [p.strip() for p in allow_external.split(',')]
for pkg in allow_external:
cmd.extend(['--allow-external', pkg])
if allow_unverified:
if isinstance(allow_unverified, six.string_types):
allow_unverified = \
[p.strip() for p in allow_unverified.split(',')]
for pkg in allow_unverified:
cmd.extend(['--allow-unverified', pkg])
if process_dependency_links:
cmd.append('--process-dependency-links')
if trusted_host:
cmd.extend(['--trusted-host', trusted_host])
if extra_args:
# These are arguments from the latest version of pip that
# have not yet been implemented in salt
for arg in extra_args:
# It is a keyword argument
if isinstance(arg, dict):
# There will only ever be one item in this dictionary
key, val = arg.popitem()
# Don't allow any recursion into keyword arg definitions
# Don't allow multiple definitions of a keyword
if isinstance(val, (dict, list)):
raise TypeError("Too many levels in: {}".format(key))
# This is a a normal one-to-one keyword argument
cmd.extend([key, val])
# It is a positional argument, append it to the list
else:
cmd.append(arg)
cmd_kwargs = dict(saltenv=saltenv, use_vt=use_vt, runas=user)
if kwargs:
cmd_kwargs.update(kwargs)
if env_vars:
cmd_kwargs.setdefault('env', {}).update(_format_env_vars(env_vars))
try:
if cwd:
cmd_kwargs['cwd'] = cwd
if bin_env and os.path.isdir(bin_env):
cmd_kwargs.setdefault('env', {})['VIRTUAL_ENV'] = bin_env
logger.debug(
'TRY BLOCK: end of pip.install -- cmd: %s, cmd_kwargs: %s',
cmd, cmd_kwargs
)
return __salt__['cmd.run_all'](cmd, python_shell=False, **cmd_kwargs)
finally:
_clear_context(bin_env)
for tempdir in [cr for cr in cleanup_requirements if cr is not None]:
if os.path.isdir(tempdir):
shutil.rmtree(tempdir)
def uninstall(pkgs=None,
requirements=None,
bin_env=None,
log=None,
proxy=None,
timeout=None,
user=None,
cwd=None,
saltenv='base',
use_vt=False):
'''
Uninstall packages individually or from a pip requirements file
pkgs
comma separated list of packages to install
requirements
Path to requirements file
bin_env
Path to pip (or to a virtualenv). This can be used to specify the path
to the pip to use when more than one Python release is installed (e.g.
``/usr/bin/pip-2.7`` or ``/usr/bin/pip-2.6``. If a directory path is
specified, it is assumed to be a virtualenv.
log
Log file where a complete (maximum verbosity) record will be kept
proxy
Specify a proxy in the format ``user:passwd@proxy.server:port``. Note
that the ``user:password@`` is optional and required only if you are
behind an authenticated proxy. If you provide
``user@proxy.server:port`` then you will be prompted for a password.
timeout
Set the socket timeout (default 15 seconds)
user
The user under which to run pip
cwd
Directory from which to run pip
use_vt
Use VT terminal emulation (see output while installing)
CLI Example:
.. code-block:: bash
salt '*' pip.uninstall <package name>,<package2 name>
salt '*' pip.uninstall requirements=/path/to/requirements.txt
salt '*' pip.uninstall <package name> bin_env=/path/to/virtualenv
salt '*' pip.uninstall <package name> bin_env=/path/to/pip_bin
'''
cmd = _get_pip_bin(bin_env)
cmd.extend(['uninstall', '-y'])
cleanup_requirements, error = _process_requirements(
requirements=requirements, cmd=cmd, saltenv=saltenv, user=user,
cwd=cwd
)
if error:
return error
if log:
try:
# TODO make this check if writeable
os.path.exists(log)
except IOError:
raise IOError('\'{0}\' is not writeable'.format(log))
cmd.extend(['--log', log])
if proxy:
cmd.extend(['--proxy', proxy])
if timeout:
try:
if isinstance(timeout, float):
# Catch floating point input, exception will be caught in
# exception class below.
raise ValueError('Timeout cannot be a float')
int(timeout)
except ValueError:
raise ValueError(
'\'{0}\' is not a valid timeout, must be an integer'
.format(timeout)
)
cmd.extend(['--timeout', timeout])
if pkgs:
if isinstance(pkgs, six.string_types):
pkgs = [p.strip() for p in pkgs.split(',')]
if requirements:
for requirement in requirements:
with salt.utils.files.fopen(requirement) as rq_:
for req in rq_:
req = salt.utils.stringutils.to_unicode(req)
try:
req_pkg, _ = req.split('==')
if req_pkg in pkgs:
pkgs.remove(req_pkg)
except ValueError:
pass
cmd.extend(pkgs)
cmd_kwargs = dict(python_shell=False, runas=user,
cwd=cwd, saltenv=saltenv, use_vt=use_vt)
if bin_env and os.path.isdir(bin_env):
cmd_kwargs['env'] = {'VIRTUAL_ENV': bin_env}
try:
return __salt__['cmd.run_all'](cmd, **cmd_kwargs)
finally:
_clear_context(bin_env)
for requirement in cleanup_requirements:
if requirement:
try:
os.remove(requirement)
except OSError:
pass
def freeze(bin_env=None,
user=None,
cwd=None,
use_vt=False,
env_vars=None,
**kwargs):
'''
Return a list of installed packages either globally or in the specified
virtualenv
bin_env
Path to pip (or to a virtualenv). This can be used to specify the path
to the pip to use when more than one Python release is installed (e.g.
``/usr/bin/pip-2.7`` or ``/usr/bin/pip-2.6``. If a directory path is
specified, it is assumed to be a virtualenv.
user
The user under which to run pip
cwd
Directory from which to run pip
.. note::
If the version of pip available is older than 8.0.3, the list will not
include the packages ``pip``, ``wheel``, ``setuptools``, or
``distribute`` even if they are installed.
CLI Example:
.. code-block:: bash
salt '*' pip.freeze bin_env=/home/code/path/to/virtualenv
'''
cmd = _get_pip_bin(bin_env)
cmd.append('freeze')
# Include pip, setuptools, distribute, wheel
min_version = '8.0.3'
cur_version = version(bin_env)
if salt.utils.versions.compare(ver1=cur_version, oper='<', ver2=min_version):
logger.warning(
'The version of pip installed is %s, which is older than %s. '
'The packages pip, wheel, setuptools, and distribute will not be '
'included in the output of pip.freeze', cur_version, min_version
)
else:
cmd.append('--all')
cmd_kwargs = dict(runas=user, cwd=cwd, use_vt=use_vt, python_shell=False)
if kwargs:
cmd_kwargs.update(**kwargs)
if bin_env and os.path.isdir(bin_env):
cmd_kwargs['env'] = {'VIRTUAL_ENV': bin_env}
if env_vars:
cmd_kwargs.setdefault('env', {}).update(_format_env_vars(env_vars))
result = __salt__['cmd.run_all'](cmd, **cmd_kwargs)
if result['retcode']:
raise CommandExecutionError(result['stderr'], info=result)
return result['stdout'].splitlines()
def list_(prefix=None,
bin_env=None,
user=None,
cwd=None,
env_vars=None,
**kwargs):
'''
Filter list of installed apps from ``freeze`` and check to see if
``prefix`` exists in the list of packages installed.
.. note::
If the version of pip available is older than 8.0.3, the packages
``wheel``, ``setuptools``, and ``distribute`` will not be reported by
this function even if they are installed. Unlike :py:func:`pip.freeze
<salt.modules.pip.freeze>`, this function always reports the version of
pip which is installed.
CLI Example:
.. code-block:: bash
salt '*' pip.list salt
'''
packages = {}
if prefix is None or 'pip'.startswith(prefix):
packages['pip'] = version(bin_env)
for line in freeze(bin_env=bin_env,
user=user,
cwd=cwd,
env_vars=env_vars,
**kwargs):
if line.startswith('-f') or line.startswith('#'):
# ignore -f line as it contains --find-links directory
# ignore comment lines
continue
elif line.startswith('-e hg+not trust'):
# ignore hg + not trust problem
continue
elif line.startswith('-e'):
line = line.split('-e ')[1]
if '#egg=' in line:
version_, name = line.split('#egg=')
else:
if len(line.split('===')) >= 2:
name = line.split('===')[0]
version_ = line.split('===')[1]
elif len(line.split('==')) >= 2:
name = line.split('==')[0]
version_ = line.split('==')[1]
elif len(line.split('===')) >= 2:
name = line.split('===')[0]
version_ = line.split('===')[1]
elif len(line.split('==')) >= 2:
name = line.split('==')[0]
version_ = line.split('==')[1]
else:
logger.error('Can\'t parse line \'%s\'', line)
continue
if prefix:
if name.lower().startswith(prefix.lower()):
packages[name] = version_
else:
packages[name] = version_
return packages
def version(bin_env=None):
'''
.. versionadded:: 0.17.0
Returns the version of pip. Use ``bin_env`` to specify the path to a
virtualenv and get the version of pip in that virtualenv.
If unable to detect the pip version, returns ``None``.
CLI Example:
.. code-block:: bash
salt '*' pip.version
'''
contextkey = 'pip.version'
if bin_env is not None:
contextkey = '{0}.{1}'.format(contextkey, bin_env)
if contextkey in __context__:
return __context__[contextkey]
cmd = _get_pip_bin(bin_env)[:]
cmd.append('--version')
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
if ret['retcode']:
raise CommandNotFoundError('Could not find a `pip` binary')
try:
pip_version = re.match(r'^pip (\S+)', ret['stdout']).group(1)
except AttributeError:
pip_version = None
__context__[contextkey] = pip_version
return pip_version
def list_upgrades(bin_env=None,
user=None,
cwd=None):
'''
Check whether or not an upgrade is available for all packages
CLI Example:
.. code-block:: bash
salt '*' pip.list_upgrades
'''
cmd = _get_pip_bin(bin_env)
cmd.extend(['list', '--outdated'])
pip_version = version(bin_env)
# Pip started supporting the ability to output json starting with 9.0.0
min_version = '9.0'
if salt.utils.versions.compare(ver1=pip_version,
oper='>=',
ver2=min_version):
cmd.append('--format=json')
cmd_kwargs = dict(cwd=cwd, runas=user)
if bin_env and os.path.isdir(bin_env):
cmd_kwargs['env'] = {'VIRTUAL_ENV': bin_env}
result = __salt__['cmd.run_all'](cmd, **cmd_kwargs)
if result['retcode']:
raise CommandExecutionError(result['stderr'], info=result)
packages = {}
# Pip started supporting the ability to output json starting with 9.0.0
# Older versions will have to parse stdout
if salt.utils.versions.compare(ver1=pip_version, oper='<', ver2='9.0.0'):
# Pip versions < 8.0.0 had a different output format
# Sample data:
# pip (Current: 7.1.2 Latest: 10.0.1 [wheel])
# psutil (Current: 5.2.2 Latest: 5.4.5 [wheel])
# pyasn1 (Current: 0.2.3 Latest: 0.4.2 [wheel])
# pycparser (Current: 2.17 Latest: 2.18 [sdist])
if salt.utils.versions.compare(ver1=pip_version, oper='<', ver2='8.0.0'):
logger.debug('pip module: Old output format')
pat = re.compile(r'(\S*)\s+\(.*Latest:\s+(.*)\)')
# New output format for version 8.0.0+
# Sample data:
# pip (8.0.0) - Latest: 10.0.1 [wheel]
# psutil (5.2.2) - Latest: 5.4.5 [wheel]
# pyasn1 (0.2.3) - Latest: 0.4.2 [wheel]
# pycparser (2.17) - Latest: 2.18 [sdist]
else:
logger.debug('pip module: New output format')
pat = re.compile(r'(\S*)\s+\(.*\)\s+-\s+Latest:\s+(.*)')
for line in result['stdout'].splitlines():
match = pat.search(line)
if match:
name, version_ = match.groups()
else:
logger.error('Can\'t parse line \'%s\'', line)
continue
packages[name] = version_
else:
logger.debug('pip module: JSON output format')
try:
pkgs = salt.utils.json.loads(result['stdout'], strict=False)
except ValueError:
raise CommandExecutionError('Invalid JSON', info=result)
for pkg in pkgs:
packages[pkg['name']] = '{0} [{1}]'.format(pkg['latest_version'],
pkg['latest_filetype'])
return packages
def is_installed(pkgname=None,
bin_env=None,
user=None,
cwd=None):
'''
.. versionadded:: 2018.3.0
Filter list of installed apps from ``freeze`` and return True or False if
``pkgname`` exists in the list of packages installed.
.. note::
If the version of pip available is older than 8.0.3, the packages
wheel, setuptools, and distribute will not be reported by this function
even if they are installed. Unlike :py:func:`pip.freeze
<salt.modules.pip.freeze>`, this function always reports the version of
pip which is installed.
CLI Example:
.. code-block:: bash
salt '*' pip.is_installed salt
'''
for line in freeze(bin_env=bin_env, user=user, cwd=cwd):
if line.startswith('-f') or line.startswith('#'):
# ignore -f line as it contains --find-links directory
# ignore comment lines
continue
elif line.startswith('-e hg+not trust'):
# ignore hg + not trust problem
continue
elif line.startswith('-e'):
line = line.split('-e ')[1]
version_, name = line.split('#egg=')
elif len(line.split('===')) >= 2:
name = line.split('===')[0]
version_ = line.split('===')[1]
elif len(line.split('==')) >= 2:
name = line.split('==')[0]
version_ = line.split('==')[1]
else:
logger.error('Can\'t parse line \'%s\'', line)
continue
if pkgname:
if pkgname == name.lower():
return True
return False
def upgrade_available(pkg,
bin_env=None,
user=None,
cwd=None):
'''
.. versionadded:: 2015.5.0
Check whether or not an upgrade is available for a given package
CLI Example:
.. code-block:: bash
salt '*' pip.upgrade_available <package name>
'''
return pkg in list_upgrades(bin_env=bin_env, user=user, cwd=cwd)
def upgrade(bin_env=None,
user=None,
cwd=None,
use_vt=False):
'''
.. versionadded:: 2015.5.0
Upgrades outdated pip packages.
.. note::
On Windows you can't update salt from pip using salt, so salt will be
skipped
Returns a dict containing the changes.
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
CLI Example:
.. code-block:: bash
salt '*' pip.upgrade
'''
ret = {'changes': {},
'result': True,
'comment': '',
}
cmd = _get_pip_bin(bin_env)
cmd.extend(['install', '-U'])
old = list_(bin_env=bin_env, user=user, cwd=cwd)
cmd_kwargs = dict(cwd=cwd, use_vt=use_vt)
if bin_env and os.path.isdir(bin_env):
cmd_kwargs['env'] = {'VIRTUAL_ENV': bin_env}
errors = False
for pkg in list_upgrades(bin_env=bin_env, user=user, cwd=cwd):
if pkg == 'salt':
if salt.utils.platform.is_windows():
continue
result = __salt__['cmd.run_all'](cmd + [pkg], **cmd_kwargs)
if result['retcode'] != 0:
errors = True
if 'stderr' in result:
ret['comment'] += result['stderr']
if errors:
ret['result'] = False
_clear_context(bin_env)
new = list_(bin_env=bin_env, user=user, cwd=cwd)
ret['changes'] = salt.utils.data.compare_dicts(old, new)
return ret
def list_all_versions(pkg,
bin_env=None,
include_alpha=False,
include_beta=False,
include_rc=False,
user=None,
cwd=None,
index_url=None,
extra_index_url=None):
'''
.. versionadded:: 2017.7.3
List all available versions of a pip package
pkg
The package to check
bin_env
Path to pip (or to a virtualenv). This can be used to specify the path
to the pip to use when more than one Python release is installed (e.g.
``/usr/bin/pip-2.7`` or ``/usr/bin/pip-2.6``. If a directory path is
specified, it is assumed to be a virtualenv.
include_alpha
Include alpha versions in the list
include_beta
Include beta versions in the list
include_rc
Include release candidates versions in the list
user
The user under which to run pip
cwd
Directory from which to run pip
index_url
Base URL of Python Package Index
.. versionadded:: 2019.2.0
extra_index_url
Additional URL of Python Package Index
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' pip.list_all_versions <package name>
'''
cmd = _get_pip_bin(bin_env)
cmd.extend(['install', '{0}==versions'.format(pkg)])
if index_url:
if not salt.utils.url.validate(index_url, VALID_PROTOS):
raise CommandExecutionError(
'\'{0}\' is not a valid URL'.format(index_url)
)
cmd.extend(['--index-url', index_url])
if extra_index_url:
if not salt.utils.url.validate(extra_index_url, VALID_PROTOS):
raise CommandExecutionError(
'\'{0}\' is not a valid URL'.format(extra_index_url)
)
cmd.extend(['--extra-index-url', extra_index_url])
cmd_kwargs = dict(cwd=cwd, runas=user, output_loglevel='quiet', redirect_stderr=True)
if bin_env and os.path.isdir(bin_env):
cmd_kwargs['env'] = {'VIRTUAL_ENV': bin_env}
result = __salt__['cmd.run_all'](cmd, **cmd_kwargs)
filtered = []
if not include_alpha:
filtered.append('a')
if not include_beta:
filtered.append('b')
if not include_rc:
filtered.append('rc')
if filtered:
excludes = re.compile(r'^((?!{0}).)*$'.format('|'.join(filtered)))
else:
excludes = re.compile(r'')
versions = []
for line in result['stdout'].splitlines():
match = re.search(r'\s*Could not find a version.* \(from versions: (.*)\)', line)
if match:
versions = [v for v in match.group(1).split(', ') if v and excludes.match(v)]
versions.sort(key=pkg_resources.parse_version)
break
if not versions:
return None
return versions
|
saltstack/salt
|
salt/modules/pip.py
|
_get_cached_requirements
|
python
|
def _get_cached_requirements(requirements, saltenv):
'''
Get the location of a cached requirements file; caching if necessary.
'''
req_file, senv = salt.utils.url.parse(requirements)
if senv:
saltenv = senv
if req_file not in __salt__['cp.list_master'](saltenv):
# Requirements file does not exist in the given saltenv.
return False
cached_requirements = __salt__['cp.is_cached'](
requirements, saltenv
)
if not cached_requirements:
# It's not cached, let's cache it.
cached_requirements = __salt__['cp.cache_file'](
requirements, saltenv
)
# Check if the master version has changed.
if __salt__['cp.hash_file'](requirements, saltenv) != \
__salt__['cp.hash_file'](cached_requirements, saltenv):
cached_requirements = __salt__['cp.cache_file'](
requirements, saltenv
)
return cached_requirements
|
Get the location of a cached requirements file; caching if necessary.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/pip.py#L196-L224
| null |
# -*- coding: utf-8 -*-
r'''
Install Python packages with pip to either the system or a virtualenv
Windows Support
===============
.. versionadded:: 2014.7.4
Salt now uses a portable python. As a result the entire pip module is now
functional on the salt installation itself. You can pip install dependencies
for your custom modules. You can even upgrade salt itself using pip. For this
to work properly, you must specify the Current Working Directory (``cwd``) and
the Pip Binary (``bin_env``) salt should use. The variable ``pip_bin`` can be
either a virtualenv path or the path to the pip binary itself.
For example, the following command will list all software installed using pip
to your current salt environment:
.. code-block:: bat
salt <minion> pip.list cwd='C:\salt\bin\Scripts' bin_env='C:\salt\bin\Scripts\pip.exe'
Specifying the ``cwd`` and ``bin_env`` options ensures you're modifying the
salt environment. If these are omitted, it will default to the local
installation of python. If python is not installed locally it will fail saying
it couldn't find pip.
State File Support
------------------
This functionality works in states as well. If you need to pip install colorama
with a state, for example, the following will work:
.. code-block:: yaml
install_colorama:
pip.installed:
- name: colorama
- cwd: 'C:\salt\bin\scripts'
- bin_env: 'C:\salt\bin\scripts\pip.exe'
- upgrade: True
Upgrading Salt using Pip
------------------------
You can now update salt using pip to any version from the 2014.7 branch
forward. Previous version require recompiling some of the dependencies which is
painful in windows.
To do this you just use pip with git to update to the version you want and then
restart the service. Here is a sample state file that upgrades salt to the head
of the 2015.5 branch:
.. code-block:: yaml
install_salt:
pip.installed:
- cwd: 'C:\salt\bin\scripts'
- bin_env: 'C:\salt\bin\scripts\pip.exe'
- editable: git+https://github.com/saltstack/salt@2015.5#egg=salt
- upgrade: True
restart_service:
service.running:
- name: salt-minion
- enable: True
- watch:
- pip: install_salt
.. note::
If you're having problems, you might try doubling the back slashes. For
example, cwd: 'C:\\salt\\bin\\scripts'. Sometimes python thinks the single
back slash is an escape character.
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import logging
import os
try:
import pkg_resources
except ImportError:
pkg_resources = None
import re
import shutil
import sys
import tempfile
# Import Salt libs
import salt.utils.data
import salt.utils.files
import salt.utils.json
import salt.utils.locales
import salt.utils.platform
import salt.utils.stringutils
import salt.utils.url
import salt.utils.versions
from salt.ext import six
from salt.exceptions import CommandExecutionError, CommandNotFoundError
# This needs to be named logger so we don't shadow it in pip.install
logger = logging.getLogger(__name__) # pylint: disable=C0103
# Don't shadow built-in's.
__func_alias__ = {
'list_': 'list'
}
VALID_PROTOS = ['http', 'https', 'ftp', 'file']
rex_pip_chain_read = re.compile(r'-r\s(.*)\n?', re.MULTILINE)
def __virtual__():
'''
There is no way to verify that pip is installed without inspecting the
entire filesystem. If it's not installed in a conventional location, the
user is required to provide the location of pip each time it is used.
'''
if pkg_resources is None:
ret = False, 'Package dependency "pkg_resource" is missing'
else:
ret = 'pip'
return ret
def _clear_context(bin_env=None):
'''
Remove the cached pip version
'''
contextkey = 'pip.version'
if bin_env is not None:
contextkey = '{0}.{1}'.format(contextkey, bin_env)
__context__.pop(contextkey, None)
def _get_pip_bin(bin_env):
'''
Locate the pip binary, either from `bin_env` as a virtualenv, as the
executable itself, or from searching conventional filesystem locations
'''
if not bin_env:
logger.debug('pip: Using pip from currently-running Python')
return [os.path.normpath(sys.executable), '-m', 'pip']
python_bin = 'python.exe' if salt.utils.platform.is_windows() else 'python'
def _search_paths(*basedirs):
ret = []
for path in basedirs:
ret.extend([
os.path.join(path, python_bin),
os.path.join(path, 'bin', python_bin),
os.path.join(path, 'Scripts', python_bin)
])
return ret
# try to get python bin from virtualenv (i.e. bin_env)
if os.path.isdir(bin_env):
for bin_path in _search_paths(bin_env):
if os.path.isfile(bin_path):
if os.access(bin_path, os.X_OK):
logger.debug('pip: Found python binary: %s', bin_path)
return [os.path.normpath(bin_path), '-m', 'pip']
else:
logger.debug(
'pip: Found python binary by name but it is not '
'executable: %s', bin_path
)
raise CommandNotFoundError(
'Could not find a pip binary in virtualenv {0}'.format(bin_env)
)
# bin_env is the python or pip binary
elif os.access(bin_env, os.X_OK):
if os.path.isfile(bin_env):
# If the python binary was passed, return it
if 'python' in os.path.basename(bin_env):
return [os.path.normpath(bin_env), '-m', 'pip']
# We have been passed a pip binary, use the pip binary.
return [os.path.normpath(bin_env)]
raise CommandExecutionError(
'Could not find a pip binary within {0}'.format(bin_env)
)
else:
raise CommandNotFoundError(
'Access denied to {0}, could not find a pip binary'.format(bin_env)
)
def _get_env_activate(bin_env):
'''
Return the path to the activate binary
'''
if not bin_env:
raise CommandNotFoundError('Could not find a `activate` binary')
if os.path.isdir(bin_env):
if salt.utils.platform.is_windows():
activate_bin = os.path.join(bin_env, 'Scripts', 'activate.bat')
else:
activate_bin = os.path.join(bin_env, 'bin', 'activate')
if os.path.isfile(activate_bin):
return activate_bin
raise CommandNotFoundError('Could not find a `activate` binary')
def _find_req(link):
logger.info('_find_req -- link = %s', link)
with salt.utils.files.fopen(link) as fh_link:
child_links = rex_pip_chain_read.findall(
salt.utils.stringutils.to_unicode(fh_link.read())
)
base_path = os.path.dirname(link)
child_links = [os.path.join(base_path, d) for d in child_links]
return child_links
def _resolve_requirements_chain(requirements):
'''
Return an array of requirements file paths that can be used to complete
the no_chown==False && user != None conundrum
'''
chain = []
if isinstance(requirements, six.string_types):
requirements = [requirements]
for req_file in requirements:
chain.append(req_file)
chain.extend(_resolve_requirements_chain(_find_req(req_file)))
return chain
def _process_requirements(requirements, cmd, cwd, saltenv, user):
'''
Process the requirements argument
'''
cleanup_requirements = []
if requirements is not None:
if isinstance(requirements, six.string_types):
requirements = [r.strip() for r in requirements.split(',')]
elif not isinstance(requirements, list):
raise TypeError('requirements must be a string or list')
treq = None
for requirement in requirements:
logger.debug('TREQ IS: %s', treq)
if requirement.startswith('salt://'):
cached_requirements = _get_cached_requirements(
requirement, saltenv
)
if not cached_requirements:
ret = {'result': False,
'comment': 'pip requirements file \'{0}\' not found'
.format(requirement)}
return None, ret
requirement = cached_requirements
if user:
# Need to make a temporary copy since the user will, most
# likely, not have the right permissions to read the file
if not treq:
treq = tempfile.mkdtemp()
__salt__['file.chown'](treq, user, None)
# In Windows, just being owner of a file isn't enough. You also
# need permissions
if salt.utils.platform.is_windows():
__utils__['dacl.set_permissions'](
obj_name=treq,
principal=user,
permissions='read_execute')
current_directory = None
if not current_directory:
current_directory = os.path.abspath(os.curdir)
logger.info('_process_requirements from directory, '
'%s -- requirement: %s', cwd, requirement)
if cwd is None:
r = requirement
c = cwd
requirement_abspath = os.path.abspath(requirement)
cwd = os.path.dirname(requirement_abspath)
requirement = os.path.basename(requirement)
logger.debug('\n\tcwd: %s -> %s\n\trequirement: %s -> %s\n',
c, cwd, r, requirement
)
os.chdir(cwd)
reqs = _resolve_requirements_chain(requirement)
os.chdir(current_directory)
logger.info('request files: %s', reqs)
for req_file in reqs:
if not os.path.isabs(req_file):
req_file = os.path.join(cwd, req_file)
logger.debug('TREQ N CWD: %s -- %s -- for %s', treq, cwd, req_file)
target_path = os.path.join(treq, os.path.basename(req_file))
logger.debug('S: %s', req_file)
logger.debug('T: %s', target_path)
target_base = os.path.dirname(target_path)
if not os.path.exists(target_base):
os.makedirs(target_base, mode=0o755)
__salt__['file.chown'](target_base, user, None)
if not os.path.exists(target_path):
logger.debug(
'Copying %s to %s', req_file, target_path
)
__salt__['file.copy'](req_file, target_path)
logger.debug(
'Changing ownership of requirements file \'%s\' to '
'user \'%s\'', target_path, user
)
__salt__['file.chown'](target_path, user, None)
req_args = os.path.join(treq, requirement) if treq else requirement
cmd.extend(['--requirement', req_args])
cleanup_requirements.append(treq)
logger.debug('CLEANUP_REQUIREMENTS: %s', cleanup_requirements)
return cleanup_requirements, None
def _format_env_vars(env_vars):
ret = {}
if env_vars:
if isinstance(env_vars, dict):
for key, val in six.iteritems(env_vars):
if not isinstance(key, six.string_types):
key = str(key) # future lint: disable=blacklisted-function
if not isinstance(val, six.string_types):
val = str(val) # future lint: disable=blacklisted-function
ret[key] = val
else:
raise CommandExecutionError(
'env_vars {0} is not a dictionary'.format(env_vars))
return ret
def install(pkgs=None, # pylint: disable=R0912,R0913,R0914
requirements=None,
bin_env=None,
use_wheel=False,
no_use_wheel=False,
log=None,
proxy=None,
timeout=None,
editable=None,
find_links=None,
index_url=None,
extra_index_url=None,
no_index=False,
mirrors=None,
build=None,
target=None,
download=None,
download_cache=None,
source=None,
upgrade=False,
force_reinstall=False,
ignore_installed=False,
exists_action=None,
no_deps=False,
no_install=False,
no_download=False,
global_options=None,
install_options=None,
user=None,
cwd=None,
pre_releases=False,
cert=None,
allow_all_external=False,
allow_external=None,
allow_unverified=None,
process_dependency_links=False,
saltenv='base',
env_vars=None,
use_vt=False,
trusted_host=None,
no_cache_dir=False,
cache_dir=None,
no_binary=None,
extra_args=None,
**kwargs):
'''
Install packages with pip
Install packages individually or from a pip requirements file. Install
packages globally or to a virtualenv.
pkgs
Comma separated list of packages to install
requirements
Path to requirements
bin_env
Path to pip (or to a virtualenv). This can be used to specify the path
to the pip to use when more than one Python release is installed (e.g.
``/usr/bin/pip-2.7`` or ``/usr/bin/pip-2.6``. If a directory path is
specified, it is assumed to be a virtualenv.
.. note::
For Windows, if the pip module is being used to upgrade the pip
package, bin_env should be the path to the virtualenv or to the
python binary that should be used. The pip command is unable to
upgrade itself in Windows.
use_wheel
Prefer wheel archives (requires pip>=1.4)
no_use_wheel
Force to not use wheel archives (requires pip>=1.4,<10.0.0)
no_binary
Force to not use binary packages (requires pip >= 7.0.0)
Accepts either :all: to disable all binary packages, :none: to empty the set,
or one or more package names with commas between them
log
Log file where a complete (maximum verbosity) record will be kept
proxy
Specify a proxy in the form ``user:passwd@proxy.server:port``. Note
that the ``user:password@`` is optional and required only if you are
behind an authenticated proxy. If you provide
``user@proxy.server:port`` then you will be prompted for a password.
timeout
Set the socket timeout (default 15 seconds)
editable
install something editable (e.g.
``git+https://github.com/worldcompany/djangoembed.git#egg=djangoembed``)
find_links
URL to search for packages
index_url
Base URL of Python Package Index
extra_index_url
Extra URLs of package indexes to use in addition to ``index_url``
no_index
Ignore package index
mirrors
Specific mirror URL(s) to query (automatically adds --use-mirrors)
.. warning::
This option has been deprecated and removed in pip version 7.0.0.
Please use ``index_url`` and/or ``extra_index_url`` instead.
build
Unpack packages into ``build`` dir
target
Install packages into ``target`` dir
download
Download packages into ``download`` instead of installing them
download_cache | cache_dir
Cache downloaded packages in ``download_cache`` or ``cache_dir`` dir
source
Check out ``editable`` packages into ``source`` dir
upgrade
Upgrade all packages to the newest available version
force_reinstall
When upgrading, reinstall all packages even if they are already
up-to-date.
ignore_installed
Ignore the installed packages (reinstalling instead)
exists_action
Default action when a path already exists: (s)witch, (i)gnore, (w)ipe,
(b)ackup
no_deps
Ignore package dependencies
no_install
Download and unpack all packages, but don't actually install them
no_download
Don't download any packages, just install the ones already downloaded
(completes an install run with ``--no-install``)
install_options
Extra arguments to be supplied to the setup.py install command (e.g.
like ``--install-option='--install-scripts=/usr/local/bin'``). Use
multiple --install-option options to pass multiple options to setup.py
install. If you are using an option with a directory path, be sure to
use absolute path.
global_options
Extra global options to be supplied to the setup.py call before the
install command.
user
The user under which to run pip
cwd
Directory from which to run pip
pre_releases
Include pre-releases in the available versions
cert
Provide a path to an alternate CA bundle
allow_all_external
Allow the installation of all externally hosted files
allow_external
Allow the installation of externally hosted files (comma separated
list)
allow_unverified
Allow the installation of insecure and unverifiable files (comma
separated list)
process_dependency_links
Enable the processing of dependency links
env_vars
Set environment variables that some builds will depend on. For example,
a Python C-module may have a Makefile that needs INCLUDE_PATH set to
pick up a header file while compiling. This must be in the form of a
dictionary or a mapping.
Example:
.. code-block:: bash
salt '*' pip.install django_app env_vars="{'CUSTOM_PATH': '/opt/django_app'}"
trusted_host
Mark this host as trusted, even though it does not have valid or any
HTTPS.
use_vt
Use VT terminal emulation (see output while installing)
no_cache_dir
Disable the cache.
extra_args
pip keyword and positional arguments not yet implemented in salt
.. code-block:: yaml
salt '*' pip.install pandas extra_args="[{'--latest-pip-kwarg':'param'}, '--latest-pip-arg']"
.. warning::
If unsupported options are passed here that are not supported in a
minion's version of pip, a `No such option error` will be thrown.
Will be translated into the following pip command:
.. code-block:: bash
pip install pandas --latest-pip-kwarg param --latest-pip-arg
CLI Example:
.. code-block:: bash
salt '*' pip.install <package name>,<package2 name>
salt '*' pip.install requirements=/path/to/requirements.txt
salt '*' pip.install <package name> bin_env=/path/to/virtualenv
salt '*' pip.install <package name> bin_env=/path/to/pip_bin
Complicated CLI example::
salt '*' pip.install markdown,django \
editable=git+https://github.com/worldcompany/djangoembed.git#egg=djangoembed upgrade=True no_deps=True
'''
cmd = _get_pip_bin(bin_env)
cmd.append('install')
cleanup_requirements, error = _process_requirements(
requirements=requirements,
cmd=cmd,
cwd=cwd,
saltenv=saltenv,
user=user
)
if error:
return error
cur_version = version(bin_env)
if use_wheel:
min_version = '1.4'
max_version = '9.0.3'
too_low = salt.utils.versions.compare(ver1=cur_version, oper='<', ver2=min_version)
too_high = salt.utils.versions.compare(ver1=cur_version, oper='>', ver2=max_version)
if too_low or too_high:
logger.error(
'The --use-wheel option is only supported in pip between %s and '
'%s. The version of pip detected is %s. This option '
'will be ignored.', min_version, max_version, cur_version
)
else:
cmd.append('--use-wheel')
if no_use_wheel:
min_version = '1.4'
max_version = '9.0.3'
too_low = salt.utils.versions.compare(ver1=cur_version, oper='<', ver2=min_version)
too_high = salt.utils.versions.compare(ver1=cur_version, oper='>', ver2=max_version)
if too_low or too_high:
logger.error(
'The --no-use-wheel option is only supported in pip between %s and '
'%s. The version of pip detected is %s. This option '
'will be ignored.', min_version, max_version, cur_version
)
else:
cmd.append('--no-use-wheel')
if no_binary:
min_version = '7.0.0'
too_low = salt.utils.versions.compare(ver1=cur_version, oper='<', ver2=min_version)
if too_low:
logger.error(
'The --no-binary option is only supported in pip %s and '
'newer. The version of pip detected is %s. This option '
'will be ignored.', min_version, cur_version
)
else:
if isinstance(no_binary, list):
no_binary = ','.join(no_binary)
cmd.extend(['--no-binary', no_binary])
if log:
if os.path.isdir(log):
raise IOError(
'\'{0}\' is a directory. Use --log path_to_file'.format(log))
elif not os.access(log, os.W_OK):
raise IOError('\'{0}\' is not writeable'.format(log))
cmd.extend(['--log', log])
if proxy:
cmd.extend(['--proxy', proxy])
if timeout:
try:
if isinstance(timeout, float):
# Catch floating point input, exception will be caught in
# exception class below.
raise ValueError('Timeout cannot be a float')
int(timeout)
except ValueError:
raise ValueError(
'\'{0}\' is not a valid timeout, must be an integer'
.format(timeout)
)
cmd.extend(['--timeout', timeout])
if find_links:
if isinstance(find_links, six.string_types):
find_links = [l.strip() for l in find_links.split(',')]
for link in find_links:
if not (salt.utils.url.validate(link, VALID_PROTOS) or os.path.exists(link)):
raise CommandExecutionError(
'\'{0}\' is not a valid URL or path'.format(link)
)
cmd.extend(['--find-links', link])
if no_index and (index_url or extra_index_url):
raise CommandExecutionError(
'\'no_index\' and (\'index_url\' or \'extra_index_url\') are '
'mutually exclusive.'
)
if index_url:
if not salt.utils.url.validate(index_url, VALID_PROTOS):
raise CommandExecutionError(
'\'{0}\' is not a valid URL'.format(index_url)
)
cmd.extend(['--index-url', index_url])
if extra_index_url:
if not salt.utils.url.validate(extra_index_url, VALID_PROTOS):
raise CommandExecutionError(
'\'{0}\' is not a valid URL'.format(extra_index_url)
)
cmd.extend(['--extra-index-url', extra_index_url])
if no_index:
cmd.append('--no-index')
if mirrors:
# https://github.com/pypa/pip/pull/2641/files#diff-3ef137fb9ffdd400f117a565cd94c188L216
if salt.utils.versions.compare(ver1=cur_version, oper='>=', ver2='7.0.0'):
raise CommandExecutionError(
'pip >= 7.0.0 does not support mirror argument:'
' use index_url and/or extra_index_url instead'
)
if isinstance(mirrors, six.string_types):
mirrors = [m.strip() for m in mirrors.split(',')]
cmd.append('--use-mirrors')
for mirror in mirrors:
if not mirror.startswith('http://'):
raise CommandExecutionError(
'\'{0}\' is not a valid URL'.format(mirror)
)
cmd.extend(['--mirrors', mirror])
if build:
cmd.extend(['--build', build])
if target:
cmd.extend(['--target', target])
if download:
cmd.extend(['--download', download])
if download_cache or cache_dir:
cmd.extend(['--cache-dir' if salt.utils.versions.compare(
ver1=cur_version, oper='>=', ver2='6.0'
) else '--download-cache', download_cache or cache_dir])
if source:
cmd.extend(['--source', source])
if upgrade:
cmd.append('--upgrade')
if force_reinstall:
cmd.append('--force-reinstall')
if ignore_installed:
cmd.append('--ignore-installed')
if exists_action:
if exists_action.lower() not in ('s', 'i', 'w', 'b'):
raise CommandExecutionError(
'The exists_action pip option only supports the values '
's, i, w, and b. \'{0}\' is not valid.'.format(exists_action)
)
cmd.extend(['--exists-action', exists_action])
if no_deps:
cmd.append('--no-deps')
if no_install:
cmd.append('--no-install')
if no_download:
cmd.append('--no-download')
if no_cache_dir:
cmd.append('--no-cache-dir')
if pre_releases:
# Check the locally installed pip version
pip_version = cur_version
# From pip v1.4 the --pre flag is available
if salt.utils.versions.compare(ver1=pip_version, oper='>=', ver2='1.4'):
cmd.append('--pre')
if cert:
cmd.extend(['--cert', cert])
if global_options:
if isinstance(global_options, six.string_types):
global_options = [go.strip() for go in global_options.split(',')]
for opt in global_options:
cmd.extend(['--global-option', opt])
if install_options:
if isinstance(install_options, six.string_types):
install_options = [io.strip() for io in install_options.split(',')]
for opt in install_options:
cmd.extend(['--install-option', opt])
if pkgs:
if not isinstance(pkgs, list):
try:
pkgs = [p.strip() for p in pkgs.split(',')]
except AttributeError:
pkgs = [p.strip() for p in six.text_type(pkgs).split(',')]
pkgs = salt.utils.data.stringify(salt.utils.data.decode_list(pkgs))
# It's possible we replaced version-range commas with semicolons so
# they would survive the previous line (in the pip.installed state).
# Put the commas back in while making sure the names are contained in
# quotes, this allows for proper version spec passing salt>=0.17.0
cmd.extend([p.replace(';', ',') for p in pkgs])
elif not any([requirements, editable]):
# Starting with pip 10.0.0, if no packages are specified in the
# command, it returns a retcode 1. So instead of running the command,
# just return the output without running pip.
return {'retcode': 0, 'stdout': 'No packages to install.'}
if editable:
egg_match = re.compile(r'(?:#|#.*?&)egg=([^&]*)')
if isinstance(editable, six.string_types):
editable = [e.strip() for e in editable.split(',')]
for entry in editable:
# Is the editable local?
if not (entry == '.' or entry.startswith(('file://', '/'))):
match = egg_match.search(entry)
if not match or not match.group(1):
# Missing #egg=theEggName
raise CommandExecutionError(
'You must specify an egg for this editable'
)
cmd.extend(['--editable', entry])
if allow_all_external:
cmd.append('--allow-all-external')
if allow_external:
if isinstance(allow_external, six.string_types):
allow_external = [p.strip() for p in allow_external.split(',')]
for pkg in allow_external:
cmd.extend(['--allow-external', pkg])
if allow_unverified:
if isinstance(allow_unverified, six.string_types):
allow_unverified = \
[p.strip() for p in allow_unverified.split(',')]
for pkg in allow_unverified:
cmd.extend(['--allow-unverified', pkg])
if process_dependency_links:
cmd.append('--process-dependency-links')
if trusted_host:
cmd.extend(['--trusted-host', trusted_host])
if extra_args:
# These are arguments from the latest version of pip that
# have not yet been implemented in salt
for arg in extra_args:
# It is a keyword argument
if isinstance(arg, dict):
# There will only ever be one item in this dictionary
key, val = arg.popitem()
# Don't allow any recursion into keyword arg definitions
# Don't allow multiple definitions of a keyword
if isinstance(val, (dict, list)):
raise TypeError("Too many levels in: {}".format(key))
# This is a a normal one-to-one keyword argument
cmd.extend([key, val])
# It is a positional argument, append it to the list
else:
cmd.append(arg)
cmd_kwargs = dict(saltenv=saltenv, use_vt=use_vt, runas=user)
if kwargs:
cmd_kwargs.update(kwargs)
if env_vars:
cmd_kwargs.setdefault('env', {}).update(_format_env_vars(env_vars))
try:
if cwd:
cmd_kwargs['cwd'] = cwd
if bin_env and os.path.isdir(bin_env):
cmd_kwargs.setdefault('env', {})['VIRTUAL_ENV'] = bin_env
logger.debug(
'TRY BLOCK: end of pip.install -- cmd: %s, cmd_kwargs: %s',
cmd, cmd_kwargs
)
return __salt__['cmd.run_all'](cmd, python_shell=False, **cmd_kwargs)
finally:
_clear_context(bin_env)
for tempdir in [cr for cr in cleanup_requirements if cr is not None]:
if os.path.isdir(tempdir):
shutil.rmtree(tempdir)
def uninstall(pkgs=None,
requirements=None,
bin_env=None,
log=None,
proxy=None,
timeout=None,
user=None,
cwd=None,
saltenv='base',
use_vt=False):
'''
Uninstall packages individually or from a pip requirements file
pkgs
comma separated list of packages to install
requirements
Path to requirements file
bin_env
Path to pip (or to a virtualenv). This can be used to specify the path
to the pip to use when more than one Python release is installed (e.g.
``/usr/bin/pip-2.7`` or ``/usr/bin/pip-2.6``. If a directory path is
specified, it is assumed to be a virtualenv.
log
Log file where a complete (maximum verbosity) record will be kept
proxy
Specify a proxy in the format ``user:passwd@proxy.server:port``. Note
that the ``user:password@`` is optional and required only if you are
behind an authenticated proxy. If you provide
``user@proxy.server:port`` then you will be prompted for a password.
timeout
Set the socket timeout (default 15 seconds)
user
The user under which to run pip
cwd
Directory from which to run pip
use_vt
Use VT terminal emulation (see output while installing)
CLI Example:
.. code-block:: bash
salt '*' pip.uninstall <package name>,<package2 name>
salt '*' pip.uninstall requirements=/path/to/requirements.txt
salt '*' pip.uninstall <package name> bin_env=/path/to/virtualenv
salt '*' pip.uninstall <package name> bin_env=/path/to/pip_bin
'''
cmd = _get_pip_bin(bin_env)
cmd.extend(['uninstall', '-y'])
cleanup_requirements, error = _process_requirements(
requirements=requirements, cmd=cmd, saltenv=saltenv, user=user,
cwd=cwd
)
if error:
return error
if log:
try:
# TODO make this check if writeable
os.path.exists(log)
except IOError:
raise IOError('\'{0}\' is not writeable'.format(log))
cmd.extend(['--log', log])
if proxy:
cmd.extend(['--proxy', proxy])
if timeout:
try:
if isinstance(timeout, float):
# Catch floating point input, exception will be caught in
# exception class below.
raise ValueError('Timeout cannot be a float')
int(timeout)
except ValueError:
raise ValueError(
'\'{0}\' is not a valid timeout, must be an integer'
.format(timeout)
)
cmd.extend(['--timeout', timeout])
if pkgs:
if isinstance(pkgs, six.string_types):
pkgs = [p.strip() for p in pkgs.split(',')]
if requirements:
for requirement in requirements:
with salt.utils.files.fopen(requirement) as rq_:
for req in rq_:
req = salt.utils.stringutils.to_unicode(req)
try:
req_pkg, _ = req.split('==')
if req_pkg in pkgs:
pkgs.remove(req_pkg)
except ValueError:
pass
cmd.extend(pkgs)
cmd_kwargs = dict(python_shell=False, runas=user,
cwd=cwd, saltenv=saltenv, use_vt=use_vt)
if bin_env and os.path.isdir(bin_env):
cmd_kwargs['env'] = {'VIRTUAL_ENV': bin_env}
try:
return __salt__['cmd.run_all'](cmd, **cmd_kwargs)
finally:
_clear_context(bin_env)
for requirement in cleanup_requirements:
if requirement:
try:
os.remove(requirement)
except OSError:
pass
def freeze(bin_env=None,
user=None,
cwd=None,
use_vt=False,
env_vars=None,
**kwargs):
'''
Return a list of installed packages either globally or in the specified
virtualenv
bin_env
Path to pip (or to a virtualenv). This can be used to specify the path
to the pip to use when more than one Python release is installed (e.g.
``/usr/bin/pip-2.7`` or ``/usr/bin/pip-2.6``. If a directory path is
specified, it is assumed to be a virtualenv.
user
The user under which to run pip
cwd
Directory from which to run pip
.. note::
If the version of pip available is older than 8.0.3, the list will not
include the packages ``pip``, ``wheel``, ``setuptools``, or
``distribute`` even if they are installed.
CLI Example:
.. code-block:: bash
salt '*' pip.freeze bin_env=/home/code/path/to/virtualenv
'''
cmd = _get_pip_bin(bin_env)
cmd.append('freeze')
# Include pip, setuptools, distribute, wheel
min_version = '8.0.3'
cur_version = version(bin_env)
if salt.utils.versions.compare(ver1=cur_version, oper='<', ver2=min_version):
logger.warning(
'The version of pip installed is %s, which is older than %s. '
'The packages pip, wheel, setuptools, and distribute will not be '
'included in the output of pip.freeze', cur_version, min_version
)
else:
cmd.append('--all')
cmd_kwargs = dict(runas=user, cwd=cwd, use_vt=use_vt, python_shell=False)
if kwargs:
cmd_kwargs.update(**kwargs)
if bin_env and os.path.isdir(bin_env):
cmd_kwargs['env'] = {'VIRTUAL_ENV': bin_env}
if env_vars:
cmd_kwargs.setdefault('env', {}).update(_format_env_vars(env_vars))
result = __salt__['cmd.run_all'](cmd, **cmd_kwargs)
if result['retcode']:
raise CommandExecutionError(result['stderr'], info=result)
return result['stdout'].splitlines()
def list_(prefix=None,
bin_env=None,
user=None,
cwd=None,
env_vars=None,
**kwargs):
'''
Filter list of installed apps from ``freeze`` and check to see if
``prefix`` exists in the list of packages installed.
.. note::
If the version of pip available is older than 8.0.3, the packages
``wheel``, ``setuptools``, and ``distribute`` will not be reported by
this function even if they are installed. Unlike :py:func:`pip.freeze
<salt.modules.pip.freeze>`, this function always reports the version of
pip which is installed.
CLI Example:
.. code-block:: bash
salt '*' pip.list salt
'''
packages = {}
if prefix is None or 'pip'.startswith(prefix):
packages['pip'] = version(bin_env)
for line in freeze(bin_env=bin_env,
user=user,
cwd=cwd,
env_vars=env_vars,
**kwargs):
if line.startswith('-f') or line.startswith('#'):
# ignore -f line as it contains --find-links directory
# ignore comment lines
continue
elif line.startswith('-e hg+not trust'):
# ignore hg + not trust problem
continue
elif line.startswith('-e'):
line = line.split('-e ')[1]
if '#egg=' in line:
version_, name = line.split('#egg=')
else:
if len(line.split('===')) >= 2:
name = line.split('===')[0]
version_ = line.split('===')[1]
elif len(line.split('==')) >= 2:
name = line.split('==')[0]
version_ = line.split('==')[1]
elif len(line.split('===')) >= 2:
name = line.split('===')[0]
version_ = line.split('===')[1]
elif len(line.split('==')) >= 2:
name = line.split('==')[0]
version_ = line.split('==')[1]
else:
logger.error('Can\'t parse line \'%s\'', line)
continue
if prefix:
if name.lower().startswith(prefix.lower()):
packages[name] = version_
else:
packages[name] = version_
return packages
def version(bin_env=None):
'''
.. versionadded:: 0.17.0
Returns the version of pip. Use ``bin_env`` to specify the path to a
virtualenv and get the version of pip in that virtualenv.
If unable to detect the pip version, returns ``None``.
CLI Example:
.. code-block:: bash
salt '*' pip.version
'''
contextkey = 'pip.version'
if bin_env is not None:
contextkey = '{0}.{1}'.format(contextkey, bin_env)
if contextkey in __context__:
return __context__[contextkey]
cmd = _get_pip_bin(bin_env)[:]
cmd.append('--version')
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
if ret['retcode']:
raise CommandNotFoundError('Could not find a `pip` binary')
try:
pip_version = re.match(r'^pip (\S+)', ret['stdout']).group(1)
except AttributeError:
pip_version = None
__context__[contextkey] = pip_version
return pip_version
def list_upgrades(bin_env=None,
user=None,
cwd=None):
'''
Check whether or not an upgrade is available for all packages
CLI Example:
.. code-block:: bash
salt '*' pip.list_upgrades
'''
cmd = _get_pip_bin(bin_env)
cmd.extend(['list', '--outdated'])
pip_version = version(bin_env)
# Pip started supporting the ability to output json starting with 9.0.0
min_version = '9.0'
if salt.utils.versions.compare(ver1=pip_version,
oper='>=',
ver2=min_version):
cmd.append('--format=json')
cmd_kwargs = dict(cwd=cwd, runas=user)
if bin_env and os.path.isdir(bin_env):
cmd_kwargs['env'] = {'VIRTUAL_ENV': bin_env}
result = __salt__['cmd.run_all'](cmd, **cmd_kwargs)
if result['retcode']:
raise CommandExecutionError(result['stderr'], info=result)
packages = {}
# Pip started supporting the ability to output json starting with 9.0.0
# Older versions will have to parse stdout
if salt.utils.versions.compare(ver1=pip_version, oper='<', ver2='9.0.0'):
# Pip versions < 8.0.0 had a different output format
# Sample data:
# pip (Current: 7.1.2 Latest: 10.0.1 [wheel])
# psutil (Current: 5.2.2 Latest: 5.4.5 [wheel])
# pyasn1 (Current: 0.2.3 Latest: 0.4.2 [wheel])
# pycparser (Current: 2.17 Latest: 2.18 [sdist])
if salt.utils.versions.compare(ver1=pip_version, oper='<', ver2='8.0.0'):
logger.debug('pip module: Old output format')
pat = re.compile(r'(\S*)\s+\(.*Latest:\s+(.*)\)')
# New output format for version 8.0.0+
# Sample data:
# pip (8.0.0) - Latest: 10.0.1 [wheel]
# psutil (5.2.2) - Latest: 5.4.5 [wheel]
# pyasn1 (0.2.3) - Latest: 0.4.2 [wheel]
# pycparser (2.17) - Latest: 2.18 [sdist]
else:
logger.debug('pip module: New output format')
pat = re.compile(r'(\S*)\s+\(.*\)\s+-\s+Latest:\s+(.*)')
for line in result['stdout'].splitlines():
match = pat.search(line)
if match:
name, version_ = match.groups()
else:
logger.error('Can\'t parse line \'%s\'', line)
continue
packages[name] = version_
else:
logger.debug('pip module: JSON output format')
try:
pkgs = salt.utils.json.loads(result['stdout'], strict=False)
except ValueError:
raise CommandExecutionError('Invalid JSON', info=result)
for pkg in pkgs:
packages[pkg['name']] = '{0} [{1}]'.format(pkg['latest_version'],
pkg['latest_filetype'])
return packages
def is_installed(pkgname=None,
bin_env=None,
user=None,
cwd=None):
'''
.. versionadded:: 2018.3.0
Filter list of installed apps from ``freeze`` and return True or False if
``pkgname`` exists in the list of packages installed.
.. note::
If the version of pip available is older than 8.0.3, the packages
wheel, setuptools, and distribute will not be reported by this function
even if they are installed. Unlike :py:func:`pip.freeze
<salt.modules.pip.freeze>`, this function always reports the version of
pip which is installed.
CLI Example:
.. code-block:: bash
salt '*' pip.is_installed salt
'''
for line in freeze(bin_env=bin_env, user=user, cwd=cwd):
if line.startswith('-f') or line.startswith('#'):
# ignore -f line as it contains --find-links directory
# ignore comment lines
continue
elif line.startswith('-e hg+not trust'):
# ignore hg + not trust problem
continue
elif line.startswith('-e'):
line = line.split('-e ')[1]
version_, name = line.split('#egg=')
elif len(line.split('===')) >= 2:
name = line.split('===')[0]
version_ = line.split('===')[1]
elif len(line.split('==')) >= 2:
name = line.split('==')[0]
version_ = line.split('==')[1]
else:
logger.error('Can\'t parse line \'%s\'', line)
continue
if pkgname:
if pkgname == name.lower():
return True
return False
def upgrade_available(pkg,
bin_env=None,
user=None,
cwd=None):
'''
.. versionadded:: 2015.5.0
Check whether or not an upgrade is available for a given package
CLI Example:
.. code-block:: bash
salt '*' pip.upgrade_available <package name>
'''
return pkg in list_upgrades(bin_env=bin_env, user=user, cwd=cwd)
def upgrade(bin_env=None,
user=None,
cwd=None,
use_vt=False):
'''
.. versionadded:: 2015.5.0
Upgrades outdated pip packages.
.. note::
On Windows you can't update salt from pip using salt, so salt will be
skipped
Returns a dict containing the changes.
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
CLI Example:
.. code-block:: bash
salt '*' pip.upgrade
'''
ret = {'changes': {},
'result': True,
'comment': '',
}
cmd = _get_pip_bin(bin_env)
cmd.extend(['install', '-U'])
old = list_(bin_env=bin_env, user=user, cwd=cwd)
cmd_kwargs = dict(cwd=cwd, use_vt=use_vt)
if bin_env and os.path.isdir(bin_env):
cmd_kwargs['env'] = {'VIRTUAL_ENV': bin_env}
errors = False
for pkg in list_upgrades(bin_env=bin_env, user=user, cwd=cwd):
if pkg == 'salt':
if salt.utils.platform.is_windows():
continue
result = __salt__['cmd.run_all'](cmd + [pkg], **cmd_kwargs)
if result['retcode'] != 0:
errors = True
if 'stderr' in result:
ret['comment'] += result['stderr']
if errors:
ret['result'] = False
_clear_context(bin_env)
new = list_(bin_env=bin_env, user=user, cwd=cwd)
ret['changes'] = salt.utils.data.compare_dicts(old, new)
return ret
def list_all_versions(pkg,
bin_env=None,
include_alpha=False,
include_beta=False,
include_rc=False,
user=None,
cwd=None,
index_url=None,
extra_index_url=None):
'''
.. versionadded:: 2017.7.3
List all available versions of a pip package
pkg
The package to check
bin_env
Path to pip (or to a virtualenv). This can be used to specify the path
to the pip to use when more than one Python release is installed (e.g.
``/usr/bin/pip-2.7`` or ``/usr/bin/pip-2.6``. If a directory path is
specified, it is assumed to be a virtualenv.
include_alpha
Include alpha versions in the list
include_beta
Include beta versions in the list
include_rc
Include release candidates versions in the list
user
The user under which to run pip
cwd
Directory from which to run pip
index_url
Base URL of Python Package Index
.. versionadded:: 2019.2.0
extra_index_url
Additional URL of Python Package Index
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' pip.list_all_versions <package name>
'''
cmd = _get_pip_bin(bin_env)
cmd.extend(['install', '{0}==versions'.format(pkg)])
if index_url:
if not salt.utils.url.validate(index_url, VALID_PROTOS):
raise CommandExecutionError(
'\'{0}\' is not a valid URL'.format(index_url)
)
cmd.extend(['--index-url', index_url])
if extra_index_url:
if not salt.utils.url.validate(extra_index_url, VALID_PROTOS):
raise CommandExecutionError(
'\'{0}\' is not a valid URL'.format(extra_index_url)
)
cmd.extend(['--extra-index-url', extra_index_url])
cmd_kwargs = dict(cwd=cwd, runas=user, output_loglevel='quiet', redirect_stderr=True)
if bin_env and os.path.isdir(bin_env):
cmd_kwargs['env'] = {'VIRTUAL_ENV': bin_env}
result = __salt__['cmd.run_all'](cmd, **cmd_kwargs)
filtered = []
if not include_alpha:
filtered.append('a')
if not include_beta:
filtered.append('b')
if not include_rc:
filtered.append('rc')
if filtered:
excludes = re.compile(r'^((?!{0}).)*$'.format('|'.join(filtered)))
else:
excludes = re.compile(r'')
versions = []
for line in result['stdout'].splitlines():
match = re.search(r'\s*Could not find a version.* \(from versions: (.*)\)', line)
if match:
versions = [v for v in match.group(1).split(', ') if v and excludes.match(v)]
versions.sort(key=pkg_resources.parse_version)
break
if not versions:
return None
return versions
|
saltstack/salt
|
salt/modules/pip.py
|
_get_env_activate
|
python
|
def _get_env_activate(bin_env):
'''
Return the path to the activate binary
'''
if not bin_env:
raise CommandNotFoundError('Could not find a `activate` binary')
if os.path.isdir(bin_env):
if salt.utils.platform.is_windows():
activate_bin = os.path.join(bin_env, 'Scripts', 'activate.bat')
else:
activate_bin = os.path.join(bin_env, 'bin', 'activate')
if os.path.isfile(activate_bin):
return activate_bin
raise CommandNotFoundError('Could not find a `activate` binary')
|
Return the path to the activate binary
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/pip.py#L227-L241
| null |
# -*- coding: utf-8 -*-
r'''
Install Python packages with pip to either the system or a virtualenv
Windows Support
===============
.. versionadded:: 2014.7.4
Salt now uses a portable python. As a result the entire pip module is now
functional on the salt installation itself. You can pip install dependencies
for your custom modules. You can even upgrade salt itself using pip. For this
to work properly, you must specify the Current Working Directory (``cwd``) and
the Pip Binary (``bin_env``) salt should use. The variable ``pip_bin`` can be
either a virtualenv path or the path to the pip binary itself.
For example, the following command will list all software installed using pip
to your current salt environment:
.. code-block:: bat
salt <minion> pip.list cwd='C:\salt\bin\Scripts' bin_env='C:\salt\bin\Scripts\pip.exe'
Specifying the ``cwd`` and ``bin_env`` options ensures you're modifying the
salt environment. If these are omitted, it will default to the local
installation of python. If python is not installed locally it will fail saying
it couldn't find pip.
State File Support
------------------
This functionality works in states as well. If you need to pip install colorama
with a state, for example, the following will work:
.. code-block:: yaml
install_colorama:
pip.installed:
- name: colorama
- cwd: 'C:\salt\bin\scripts'
- bin_env: 'C:\salt\bin\scripts\pip.exe'
- upgrade: True
Upgrading Salt using Pip
------------------------
You can now update salt using pip to any version from the 2014.7 branch
forward. Previous version require recompiling some of the dependencies which is
painful in windows.
To do this you just use pip with git to update to the version you want and then
restart the service. Here is a sample state file that upgrades salt to the head
of the 2015.5 branch:
.. code-block:: yaml
install_salt:
pip.installed:
- cwd: 'C:\salt\bin\scripts'
- bin_env: 'C:\salt\bin\scripts\pip.exe'
- editable: git+https://github.com/saltstack/salt@2015.5#egg=salt
- upgrade: True
restart_service:
service.running:
- name: salt-minion
- enable: True
- watch:
- pip: install_salt
.. note::
If you're having problems, you might try doubling the back slashes. For
example, cwd: 'C:\\salt\\bin\\scripts'. Sometimes python thinks the single
back slash is an escape character.
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import logging
import os
try:
import pkg_resources
except ImportError:
pkg_resources = None
import re
import shutil
import sys
import tempfile
# Import Salt libs
import salt.utils.data
import salt.utils.files
import salt.utils.json
import salt.utils.locales
import salt.utils.platform
import salt.utils.stringutils
import salt.utils.url
import salt.utils.versions
from salt.ext import six
from salt.exceptions import CommandExecutionError, CommandNotFoundError
# This needs to be named logger so we don't shadow it in pip.install
logger = logging.getLogger(__name__) # pylint: disable=C0103
# Don't shadow built-in's.
__func_alias__ = {
'list_': 'list'
}
VALID_PROTOS = ['http', 'https', 'ftp', 'file']
rex_pip_chain_read = re.compile(r'-r\s(.*)\n?', re.MULTILINE)
def __virtual__():
'''
There is no way to verify that pip is installed without inspecting the
entire filesystem. If it's not installed in a conventional location, the
user is required to provide the location of pip each time it is used.
'''
if pkg_resources is None:
ret = False, 'Package dependency "pkg_resource" is missing'
else:
ret = 'pip'
return ret
def _clear_context(bin_env=None):
'''
Remove the cached pip version
'''
contextkey = 'pip.version'
if bin_env is not None:
contextkey = '{0}.{1}'.format(contextkey, bin_env)
__context__.pop(contextkey, None)
def _get_pip_bin(bin_env):
'''
Locate the pip binary, either from `bin_env` as a virtualenv, as the
executable itself, or from searching conventional filesystem locations
'''
if not bin_env:
logger.debug('pip: Using pip from currently-running Python')
return [os.path.normpath(sys.executable), '-m', 'pip']
python_bin = 'python.exe' if salt.utils.platform.is_windows() else 'python'
def _search_paths(*basedirs):
ret = []
for path in basedirs:
ret.extend([
os.path.join(path, python_bin),
os.path.join(path, 'bin', python_bin),
os.path.join(path, 'Scripts', python_bin)
])
return ret
# try to get python bin from virtualenv (i.e. bin_env)
if os.path.isdir(bin_env):
for bin_path in _search_paths(bin_env):
if os.path.isfile(bin_path):
if os.access(bin_path, os.X_OK):
logger.debug('pip: Found python binary: %s', bin_path)
return [os.path.normpath(bin_path), '-m', 'pip']
else:
logger.debug(
'pip: Found python binary by name but it is not '
'executable: %s', bin_path
)
raise CommandNotFoundError(
'Could not find a pip binary in virtualenv {0}'.format(bin_env)
)
# bin_env is the python or pip binary
elif os.access(bin_env, os.X_OK):
if os.path.isfile(bin_env):
# If the python binary was passed, return it
if 'python' in os.path.basename(bin_env):
return [os.path.normpath(bin_env), '-m', 'pip']
# We have been passed a pip binary, use the pip binary.
return [os.path.normpath(bin_env)]
raise CommandExecutionError(
'Could not find a pip binary within {0}'.format(bin_env)
)
else:
raise CommandNotFoundError(
'Access denied to {0}, could not find a pip binary'.format(bin_env)
)
def _get_cached_requirements(requirements, saltenv):
'''
Get the location of a cached requirements file; caching if necessary.
'''
req_file, senv = salt.utils.url.parse(requirements)
if senv:
saltenv = senv
if req_file not in __salt__['cp.list_master'](saltenv):
# Requirements file does not exist in the given saltenv.
return False
cached_requirements = __salt__['cp.is_cached'](
requirements, saltenv
)
if not cached_requirements:
# It's not cached, let's cache it.
cached_requirements = __salt__['cp.cache_file'](
requirements, saltenv
)
# Check if the master version has changed.
if __salt__['cp.hash_file'](requirements, saltenv) != \
__salt__['cp.hash_file'](cached_requirements, saltenv):
cached_requirements = __salt__['cp.cache_file'](
requirements, saltenv
)
return cached_requirements
def _find_req(link):
logger.info('_find_req -- link = %s', link)
with salt.utils.files.fopen(link) as fh_link:
child_links = rex_pip_chain_read.findall(
salt.utils.stringutils.to_unicode(fh_link.read())
)
base_path = os.path.dirname(link)
child_links = [os.path.join(base_path, d) for d in child_links]
return child_links
def _resolve_requirements_chain(requirements):
'''
Return an array of requirements file paths that can be used to complete
the no_chown==False && user != None conundrum
'''
chain = []
if isinstance(requirements, six.string_types):
requirements = [requirements]
for req_file in requirements:
chain.append(req_file)
chain.extend(_resolve_requirements_chain(_find_req(req_file)))
return chain
def _process_requirements(requirements, cmd, cwd, saltenv, user):
'''
Process the requirements argument
'''
cleanup_requirements = []
if requirements is not None:
if isinstance(requirements, six.string_types):
requirements = [r.strip() for r in requirements.split(',')]
elif not isinstance(requirements, list):
raise TypeError('requirements must be a string or list')
treq = None
for requirement in requirements:
logger.debug('TREQ IS: %s', treq)
if requirement.startswith('salt://'):
cached_requirements = _get_cached_requirements(
requirement, saltenv
)
if not cached_requirements:
ret = {'result': False,
'comment': 'pip requirements file \'{0}\' not found'
.format(requirement)}
return None, ret
requirement = cached_requirements
if user:
# Need to make a temporary copy since the user will, most
# likely, not have the right permissions to read the file
if not treq:
treq = tempfile.mkdtemp()
__salt__['file.chown'](treq, user, None)
# In Windows, just being owner of a file isn't enough. You also
# need permissions
if salt.utils.platform.is_windows():
__utils__['dacl.set_permissions'](
obj_name=treq,
principal=user,
permissions='read_execute')
current_directory = None
if not current_directory:
current_directory = os.path.abspath(os.curdir)
logger.info('_process_requirements from directory, '
'%s -- requirement: %s', cwd, requirement)
if cwd is None:
r = requirement
c = cwd
requirement_abspath = os.path.abspath(requirement)
cwd = os.path.dirname(requirement_abspath)
requirement = os.path.basename(requirement)
logger.debug('\n\tcwd: %s -> %s\n\trequirement: %s -> %s\n',
c, cwd, r, requirement
)
os.chdir(cwd)
reqs = _resolve_requirements_chain(requirement)
os.chdir(current_directory)
logger.info('request files: %s', reqs)
for req_file in reqs:
if not os.path.isabs(req_file):
req_file = os.path.join(cwd, req_file)
logger.debug('TREQ N CWD: %s -- %s -- for %s', treq, cwd, req_file)
target_path = os.path.join(treq, os.path.basename(req_file))
logger.debug('S: %s', req_file)
logger.debug('T: %s', target_path)
target_base = os.path.dirname(target_path)
if not os.path.exists(target_base):
os.makedirs(target_base, mode=0o755)
__salt__['file.chown'](target_base, user, None)
if not os.path.exists(target_path):
logger.debug(
'Copying %s to %s', req_file, target_path
)
__salt__['file.copy'](req_file, target_path)
logger.debug(
'Changing ownership of requirements file \'%s\' to '
'user \'%s\'', target_path, user
)
__salt__['file.chown'](target_path, user, None)
req_args = os.path.join(treq, requirement) if treq else requirement
cmd.extend(['--requirement', req_args])
cleanup_requirements.append(treq)
logger.debug('CLEANUP_REQUIREMENTS: %s', cleanup_requirements)
return cleanup_requirements, None
def _format_env_vars(env_vars):
ret = {}
if env_vars:
if isinstance(env_vars, dict):
for key, val in six.iteritems(env_vars):
if not isinstance(key, six.string_types):
key = str(key) # future lint: disable=blacklisted-function
if not isinstance(val, six.string_types):
val = str(val) # future lint: disable=blacklisted-function
ret[key] = val
else:
raise CommandExecutionError(
'env_vars {0} is not a dictionary'.format(env_vars))
return ret
def install(pkgs=None, # pylint: disable=R0912,R0913,R0914
requirements=None,
bin_env=None,
use_wheel=False,
no_use_wheel=False,
log=None,
proxy=None,
timeout=None,
editable=None,
find_links=None,
index_url=None,
extra_index_url=None,
no_index=False,
mirrors=None,
build=None,
target=None,
download=None,
download_cache=None,
source=None,
upgrade=False,
force_reinstall=False,
ignore_installed=False,
exists_action=None,
no_deps=False,
no_install=False,
no_download=False,
global_options=None,
install_options=None,
user=None,
cwd=None,
pre_releases=False,
cert=None,
allow_all_external=False,
allow_external=None,
allow_unverified=None,
process_dependency_links=False,
saltenv='base',
env_vars=None,
use_vt=False,
trusted_host=None,
no_cache_dir=False,
cache_dir=None,
no_binary=None,
extra_args=None,
**kwargs):
'''
Install packages with pip
Install packages individually or from a pip requirements file. Install
packages globally or to a virtualenv.
pkgs
Comma separated list of packages to install
requirements
Path to requirements
bin_env
Path to pip (or to a virtualenv). This can be used to specify the path
to the pip to use when more than one Python release is installed (e.g.
``/usr/bin/pip-2.7`` or ``/usr/bin/pip-2.6``. If a directory path is
specified, it is assumed to be a virtualenv.
.. note::
For Windows, if the pip module is being used to upgrade the pip
package, bin_env should be the path to the virtualenv or to the
python binary that should be used. The pip command is unable to
upgrade itself in Windows.
use_wheel
Prefer wheel archives (requires pip>=1.4)
no_use_wheel
Force to not use wheel archives (requires pip>=1.4,<10.0.0)
no_binary
Force to not use binary packages (requires pip >= 7.0.0)
Accepts either :all: to disable all binary packages, :none: to empty the set,
or one or more package names with commas between them
log
Log file where a complete (maximum verbosity) record will be kept
proxy
Specify a proxy in the form ``user:passwd@proxy.server:port``. Note
that the ``user:password@`` is optional and required only if you are
behind an authenticated proxy. If you provide
``user@proxy.server:port`` then you will be prompted for a password.
timeout
Set the socket timeout (default 15 seconds)
editable
install something editable (e.g.
``git+https://github.com/worldcompany/djangoembed.git#egg=djangoembed``)
find_links
URL to search for packages
index_url
Base URL of Python Package Index
extra_index_url
Extra URLs of package indexes to use in addition to ``index_url``
no_index
Ignore package index
mirrors
Specific mirror URL(s) to query (automatically adds --use-mirrors)
.. warning::
This option has been deprecated and removed in pip version 7.0.0.
Please use ``index_url`` and/or ``extra_index_url`` instead.
build
Unpack packages into ``build`` dir
target
Install packages into ``target`` dir
download
Download packages into ``download`` instead of installing them
download_cache | cache_dir
Cache downloaded packages in ``download_cache`` or ``cache_dir`` dir
source
Check out ``editable`` packages into ``source`` dir
upgrade
Upgrade all packages to the newest available version
force_reinstall
When upgrading, reinstall all packages even if they are already
up-to-date.
ignore_installed
Ignore the installed packages (reinstalling instead)
exists_action
Default action when a path already exists: (s)witch, (i)gnore, (w)ipe,
(b)ackup
no_deps
Ignore package dependencies
no_install
Download and unpack all packages, but don't actually install them
no_download
Don't download any packages, just install the ones already downloaded
(completes an install run with ``--no-install``)
install_options
Extra arguments to be supplied to the setup.py install command (e.g.
like ``--install-option='--install-scripts=/usr/local/bin'``). Use
multiple --install-option options to pass multiple options to setup.py
install. If you are using an option with a directory path, be sure to
use absolute path.
global_options
Extra global options to be supplied to the setup.py call before the
install command.
user
The user under which to run pip
cwd
Directory from which to run pip
pre_releases
Include pre-releases in the available versions
cert
Provide a path to an alternate CA bundle
allow_all_external
Allow the installation of all externally hosted files
allow_external
Allow the installation of externally hosted files (comma separated
list)
allow_unverified
Allow the installation of insecure and unverifiable files (comma
separated list)
process_dependency_links
Enable the processing of dependency links
env_vars
Set environment variables that some builds will depend on. For example,
a Python C-module may have a Makefile that needs INCLUDE_PATH set to
pick up a header file while compiling. This must be in the form of a
dictionary or a mapping.
Example:
.. code-block:: bash
salt '*' pip.install django_app env_vars="{'CUSTOM_PATH': '/opt/django_app'}"
trusted_host
Mark this host as trusted, even though it does not have valid or any
HTTPS.
use_vt
Use VT terminal emulation (see output while installing)
no_cache_dir
Disable the cache.
extra_args
pip keyword and positional arguments not yet implemented in salt
.. code-block:: yaml
salt '*' pip.install pandas extra_args="[{'--latest-pip-kwarg':'param'}, '--latest-pip-arg']"
.. warning::
If unsupported options are passed here that are not supported in a
minion's version of pip, a `No such option error` will be thrown.
Will be translated into the following pip command:
.. code-block:: bash
pip install pandas --latest-pip-kwarg param --latest-pip-arg
CLI Example:
.. code-block:: bash
salt '*' pip.install <package name>,<package2 name>
salt '*' pip.install requirements=/path/to/requirements.txt
salt '*' pip.install <package name> bin_env=/path/to/virtualenv
salt '*' pip.install <package name> bin_env=/path/to/pip_bin
Complicated CLI example::
salt '*' pip.install markdown,django \
editable=git+https://github.com/worldcompany/djangoembed.git#egg=djangoembed upgrade=True no_deps=True
'''
cmd = _get_pip_bin(bin_env)
cmd.append('install')
cleanup_requirements, error = _process_requirements(
requirements=requirements,
cmd=cmd,
cwd=cwd,
saltenv=saltenv,
user=user
)
if error:
return error
cur_version = version(bin_env)
if use_wheel:
min_version = '1.4'
max_version = '9.0.3'
too_low = salt.utils.versions.compare(ver1=cur_version, oper='<', ver2=min_version)
too_high = salt.utils.versions.compare(ver1=cur_version, oper='>', ver2=max_version)
if too_low or too_high:
logger.error(
'The --use-wheel option is only supported in pip between %s and '
'%s. The version of pip detected is %s. This option '
'will be ignored.', min_version, max_version, cur_version
)
else:
cmd.append('--use-wheel')
if no_use_wheel:
min_version = '1.4'
max_version = '9.0.3'
too_low = salt.utils.versions.compare(ver1=cur_version, oper='<', ver2=min_version)
too_high = salt.utils.versions.compare(ver1=cur_version, oper='>', ver2=max_version)
if too_low or too_high:
logger.error(
'The --no-use-wheel option is only supported in pip between %s and '
'%s. The version of pip detected is %s. This option '
'will be ignored.', min_version, max_version, cur_version
)
else:
cmd.append('--no-use-wheel')
if no_binary:
min_version = '7.0.0'
too_low = salt.utils.versions.compare(ver1=cur_version, oper='<', ver2=min_version)
if too_low:
logger.error(
'The --no-binary option is only supported in pip %s and '
'newer. The version of pip detected is %s. This option '
'will be ignored.', min_version, cur_version
)
else:
if isinstance(no_binary, list):
no_binary = ','.join(no_binary)
cmd.extend(['--no-binary', no_binary])
if log:
if os.path.isdir(log):
raise IOError(
'\'{0}\' is a directory. Use --log path_to_file'.format(log))
elif not os.access(log, os.W_OK):
raise IOError('\'{0}\' is not writeable'.format(log))
cmd.extend(['--log', log])
if proxy:
cmd.extend(['--proxy', proxy])
if timeout:
try:
if isinstance(timeout, float):
# Catch floating point input, exception will be caught in
# exception class below.
raise ValueError('Timeout cannot be a float')
int(timeout)
except ValueError:
raise ValueError(
'\'{0}\' is not a valid timeout, must be an integer'
.format(timeout)
)
cmd.extend(['--timeout', timeout])
if find_links:
if isinstance(find_links, six.string_types):
find_links = [l.strip() for l in find_links.split(',')]
for link in find_links:
if not (salt.utils.url.validate(link, VALID_PROTOS) or os.path.exists(link)):
raise CommandExecutionError(
'\'{0}\' is not a valid URL or path'.format(link)
)
cmd.extend(['--find-links', link])
if no_index and (index_url or extra_index_url):
raise CommandExecutionError(
'\'no_index\' and (\'index_url\' or \'extra_index_url\') are '
'mutually exclusive.'
)
if index_url:
if not salt.utils.url.validate(index_url, VALID_PROTOS):
raise CommandExecutionError(
'\'{0}\' is not a valid URL'.format(index_url)
)
cmd.extend(['--index-url', index_url])
if extra_index_url:
if not salt.utils.url.validate(extra_index_url, VALID_PROTOS):
raise CommandExecutionError(
'\'{0}\' is not a valid URL'.format(extra_index_url)
)
cmd.extend(['--extra-index-url', extra_index_url])
if no_index:
cmd.append('--no-index')
if mirrors:
# https://github.com/pypa/pip/pull/2641/files#diff-3ef137fb9ffdd400f117a565cd94c188L216
if salt.utils.versions.compare(ver1=cur_version, oper='>=', ver2='7.0.0'):
raise CommandExecutionError(
'pip >= 7.0.0 does not support mirror argument:'
' use index_url and/or extra_index_url instead'
)
if isinstance(mirrors, six.string_types):
mirrors = [m.strip() for m in mirrors.split(',')]
cmd.append('--use-mirrors')
for mirror in mirrors:
if not mirror.startswith('http://'):
raise CommandExecutionError(
'\'{0}\' is not a valid URL'.format(mirror)
)
cmd.extend(['--mirrors', mirror])
if build:
cmd.extend(['--build', build])
if target:
cmd.extend(['--target', target])
if download:
cmd.extend(['--download', download])
if download_cache or cache_dir:
cmd.extend(['--cache-dir' if salt.utils.versions.compare(
ver1=cur_version, oper='>=', ver2='6.0'
) else '--download-cache', download_cache or cache_dir])
if source:
cmd.extend(['--source', source])
if upgrade:
cmd.append('--upgrade')
if force_reinstall:
cmd.append('--force-reinstall')
if ignore_installed:
cmd.append('--ignore-installed')
if exists_action:
if exists_action.lower() not in ('s', 'i', 'w', 'b'):
raise CommandExecutionError(
'The exists_action pip option only supports the values '
's, i, w, and b. \'{0}\' is not valid.'.format(exists_action)
)
cmd.extend(['--exists-action', exists_action])
if no_deps:
cmd.append('--no-deps')
if no_install:
cmd.append('--no-install')
if no_download:
cmd.append('--no-download')
if no_cache_dir:
cmd.append('--no-cache-dir')
if pre_releases:
# Check the locally installed pip version
pip_version = cur_version
# From pip v1.4 the --pre flag is available
if salt.utils.versions.compare(ver1=pip_version, oper='>=', ver2='1.4'):
cmd.append('--pre')
if cert:
cmd.extend(['--cert', cert])
if global_options:
if isinstance(global_options, six.string_types):
global_options = [go.strip() for go in global_options.split(',')]
for opt in global_options:
cmd.extend(['--global-option', opt])
if install_options:
if isinstance(install_options, six.string_types):
install_options = [io.strip() for io in install_options.split(',')]
for opt in install_options:
cmd.extend(['--install-option', opt])
if pkgs:
if not isinstance(pkgs, list):
try:
pkgs = [p.strip() for p in pkgs.split(',')]
except AttributeError:
pkgs = [p.strip() for p in six.text_type(pkgs).split(',')]
pkgs = salt.utils.data.stringify(salt.utils.data.decode_list(pkgs))
# It's possible we replaced version-range commas with semicolons so
# they would survive the previous line (in the pip.installed state).
# Put the commas back in while making sure the names are contained in
# quotes, this allows for proper version spec passing salt>=0.17.0
cmd.extend([p.replace(';', ',') for p in pkgs])
elif not any([requirements, editable]):
# Starting with pip 10.0.0, if no packages are specified in the
# command, it returns a retcode 1. So instead of running the command,
# just return the output without running pip.
return {'retcode': 0, 'stdout': 'No packages to install.'}
if editable:
egg_match = re.compile(r'(?:#|#.*?&)egg=([^&]*)')
if isinstance(editable, six.string_types):
editable = [e.strip() for e in editable.split(',')]
for entry in editable:
# Is the editable local?
if not (entry == '.' or entry.startswith(('file://', '/'))):
match = egg_match.search(entry)
if not match or not match.group(1):
# Missing #egg=theEggName
raise CommandExecutionError(
'You must specify an egg for this editable'
)
cmd.extend(['--editable', entry])
if allow_all_external:
cmd.append('--allow-all-external')
if allow_external:
if isinstance(allow_external, six.string_types):
allow_external = [p.strip() for p in allow_external.split(',')]
for pkg in allow_external:
cmd.extend(['--allow-external', pkg])
if allow_unverified:
if isinstance(allow_unverified, six.string_types):
allow_unverified = \
[p.strip() for p in allow_unverified.split(',')]
for pkg in allow_unverified:
cmd.extend(['--allow-unverified', pkg])
if process_dependency_links:
cmd.append('--process-dependency-links')
if trusted_host:
cmd.extend(['--trusted-host', trusted_host])
if extra_args:
# These are arguments from the latest version of pip that
# have not yet been implemented in salt
for arg in extra_args:
# It is a keyword argument
if isinstance(arg, dict):
# There will only ever be one item in this dictionary
key, val = arg.popitem()
# Don't allow any recursion into keyword arg definitions
# Don't allow multiple definitions of a keyword
if isinstance(val, (dict, list)):
raise TypeError("Too many levels in: {}".format(key))
# This is a a normal one-to-one keyword argument
cmd.extend([key, val])
# It is a positional argument, append it to the list
else:
cmd.append(arg)
cmd_kwargs = dict(saltenv=saltenv, use_vt=use_vt, runas=user)
if kwargs:
cmd_kwargs.update(kwargs)
if env_vars:
cmd_kwargs.setdefault('env', {}).update(_format_env_vars(env_vars))
try:
if cwd:
cmd_kwargs['cwd'] = cwd
if bin_env and os.path.isdir(bin_env):
cmd_kwargs.setdefault('env', {})['VIRTUAL_ENV'] = bin_env
logger.debug(
'TRY BLOCK: end of pip.install -- cmd: %s, cmd_kwargs: %s',
cmd, cmd_kwargs
)
return __salt__['cmd.run_all'](cmd, python_shell=False, **cmd_kwargs)
finally:
_clear_context(bin_env)
for tempdir in [cr for cr in cleanup_requirements if cr is not None]:
if os.path.isdir(tempdir):
shutil.rmtree(tempdir)
def uninstall(pkgs=None,
requirements=None,
bin_env=None,
log=None,
proxy=None,
timeout=None,
user=None,
cwd=None,
saltenv='base',
use_vt=False):
'''
Uninstall packages individually or from a pip requirements file
pkgs
comma separated list of packages to install
requirements
Path to requirements file
bin_env
Path to pip (or to a virtualenv). This can be used to specify the path
to the pip to use when more than one Python release is installed (e.g.
``/usr/bin/pip-2.7`` or ``/usr/bin/pip-2.6``. If a directory path is
specified, it is assumed to be a virtualenv.
log
Log file where a complete (maximum verbosity) record will be kept
proxy
Specify a proxy in the format ``user:passwd@proxy.server:port``. Note
that the ``user:password@`` is optional and required only if you are
behind an authenticated proxy. If you provide
``user@proxy.server:port`` then you will be prompted for a password.
timeout
Set the socket timeout (default 15 seconds)
user
The user under which to run pip
cwd
Directory from which to run pip
use_vt
Use VT terminal emulation (see output while installing)
CLI Example:
.. code-block:: bash
salt '*' pip.uninstall <package name>,<package2 name>
salt '*' pip.uninstall requirements=/path/to/requirements.txt
salt '*' pip.uninstall <package name> bin_env=/path/to/virtualenv
salt '*' pip.uninstall <package name> bin_env=/path/to/pip_bin
'''
cmd = _get_pip_bin(bin_env)
cmd.extend(['uninstall', '-y'])
cleanup_requirements, error = _process_requirements(
requirements=requirements, cmd=cmd, saltenv=saltenv, user=user,
cwd=cwd
)
if error:
return error
if log:
try:
# TODO make this check if writeable
os.path.exists(log)
except IOError:
raise IOError('\'{0}\' is not writeable'.format(log))
cmd.extend(['--log', log])
if proxy:
cmd.extend(['--proxy', proxy])
if timeout:
try:
if isinstance(timeout, float):
# Catch floating point input, exception will be caught in
# exception class below.
raise ValueError('Timeout cannot be a float')
int(timeout)
except ValueError:
raise ValueError(
'\'{0}\' is not a valid timeout, must be an integer'
.format(timeout)
)
cmd.extend(['--timeout', timeout])
if pkgs:
if isinstance(pkgs, six.string_types):
pkgs = [p.strip() for p in pkgs.split(',')]
if requirements:
for requirement in requirements:
with salt.utils.files.fopen(requirement) as rq_:
for req in rq_:
req = salt.utils.stringutils.to_unicode(req)
try:
req_pkg, _ = req.split('==')
if req_pkg in pkgs:
pkgs.remove(req_pkg)
except ValueError:
pass
cmd.extend(pkgs)
cmd_kwargs = dict(python_shell=False, runas=user,
cwd=cwd, saltenv=saltenv, use_vt=use_vt)
if bin_env and os.path.isdir(bin_env):
cmd_kwargs['env'] = {'VIRTUAL_ENV': bin_env}
try:
return __salt__['cmd.run_all'](cmd, **cmd_kwargs)
finally:
_clear_context(bin_env)
for requirement in cleanup_requirements:
if requirement:
try:
os.remove(requirement)
except OSError:
pass
def freeze(bin_env=None,
user=None,
cwd=None,
use_vt=False,
env_vars=None,
**kwargs):
'''
Return a list of installed packages either globally or in the specified
virtualenv
bin_env
Path to pip (or to a virtualenv). This can be used to specify the path
to the pip to use when more than one Python release is installed (e.g.
``/usr/bin/pip-2.7`` or ``/usr/bin/pip-2.6``. If a directory path is
specified, it is assumed to be a virtualenv.
user
The user under which to run pip
cwd
Directory from which to run pip
.. note::
If the version of pip available is older than 8.0.3, the list will not
include the packages ``pip``, ``wheel``, ``setuptools``, or
``distribute`` even if they are installed.
CLI Example:
.. code-block:: bash
salt '*' pip.freeze bin_env=/home/code/path/to/virtualenv
'''
cmd = _get_pip_bin(bin_env)
cmd.append('freeze')
# Include pip, setuptools, distribute, wheel
min_version = '8.0.3'
cur_version = version(bin_env)
if salt.utils.versions.compare(ver1=cur_version, oper='<', ver2=min_version):
logger.warning(
'The version of pip installed is %s, which is older than %s. '
'The packages pip, wheel, setuptools, and distribute will not be '
'included in the output of pip.freeze', cur_version, min_version
)
else:
cmd.append('--all')
cmd_kwargs = dict(runas=user, cwd=cwd, use_vt=use_vt, python_shell=False)
if kwargs:
cmd_kwargs.update(**kwargs)
if bin_env and os.path.isdir(bin_env):
cmd_kwargs['env'] = {'VIRTUAL_ENV': bin_env}
if env_vars:
cmd_kwargs.setdefault('env', {}).update(_format_env_vars(env_vars))
result = __salt__['cmd.run_all'](cmd, **cmd_kwargs)
if result['retcode']:
raise CommandExecutionError(result['stderr'], info=result)
return result['stdout'].splitlines()
def list_(prefix=None,
bin_env=None,
user=None,
cwd=None,
env_vars=None,
**kwargs):
'''
Filter list of installed apps from ``freeze`` and check to see if
``prefix`` exists in the list of packages installed.
.. note::
If the version of pip available is older than 8.0.3, the packages
``wheel``, ``setuptools``, and ``distribute`` will not be reported by
this function even if they are installed. Unlike :py:func:`pip.freeze
<salt.modules.pip.freeze>`, this function always reports the version of
pip which is installed.
CLI Example:
.. code-block:: bash
salt '*' pip.list salt
'''
packages = {}
if prefix is None or 'pip'.startswith(prefix):
packages['pip'] = version(bin_env)
for line in freeze(bin_env=bin_env,
user=user,
cwd=cwd,
env_vars=env_vars,
**kwargs):
if line.startswith('-f') or line.startswith('#'):
# ignore -f line as it contains --find-links directory
# ignore comment lines
continue
elif line.startswith('-e hg+not trust'):
# ignore hg + not trust problem
continue
elif line.startswith('-e'):
line = line.split('-e ')[1]
if '#egg=' in line:
version_, name = line.split('#egg=')
else:
if len(line.split('===')) >= 2:
name = line.split('===')[0]
version_ = line.split('===')[1]
elif len(line.split('==')) >= 2:
name = line.split('==')[0]
version_ = line.split('==')[1]
elif len(line.split('===')) >= 2:
name = line.split('===')[0]
version_ = line.split('===')[1]
elif len(line.split('==')) >= 2:
name = line.split('==')[0]
version_ = line.split('==')[1]
else:
logger.error('Can\'t parse line \'%s\'', line)
continue
if prefix:
if name.lower().startswith(prefix.lower()):
packages[name] = version_
else:
packages[name] = version_
return packages
def version(bin_env=None):
'''
.. versionadded:: 0.17.0
Returns the version of pip. Use ``bin_env`` to specify the path to a
virtualenv and get the version of pip in that virtualenv.
If unable to detect the pip version, returns ``None``.
CLI Example:
.. code-block:: bash
salt '*' pip.version
'''
contextkey = 'pip.version'
if bin_env is not None:
contextkey = '{0}.{1}'.format(contextkey, bin_env)
if contextkey in __context__:
return __context__[contextkey]
cmd = _get_pip_bin(bin_env)[:]
cmd.append('--version')
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
if ret['retcode']:
raise CommandNotFoundError('Could not find a `pip` binary')
try:
pip_version = re.match(r'^pip (\S+)', ret['stdout']).group(1)
except AttributeError:
pip_version = None
__context__[contextkey] = pip_version
return pip_version
def list_upgrades(bin_env=None,
user=None,
cwd=None):
'''
Check whether or not an upgrade is available for all packages
CLI Example:
.. code-block:: bash
salt '*' pip.list_upgrades
'''
cmd = _get_pip_bin(bin_env)
cmd.extend(['list', '--outdated'])
pip_version = version(bin_env)
# Pip started supporting the ability to output json starting with 9.0.0
min_version = '9.0'
if salt.utils.versions.compare(ver1=pip_version,
oper='>=',
ver2=min_version):
cmd.append('--format=json')
cmd_kwargs = dict(cwd=cwd, runas=user)
if bin_env and os.path.isdir(bin_env):
cmd_kwargs['env'] = {'VIRTUAL_ENV': bin_env}
result = __salt__['cmd.run_all'](cmd, **cmd_kwargs)
if result['retcode']:
raise CommandExecutionError(result['stderr'], info=result)
packages = {}
# Pip started supporting the ability to output json starting with 9.0.0
# Older versions will have to parse stdout
if salt.utils.versions.compare(ver1=pip_version, oper='<', ver2='9.0.0'):
# Pip versions < 8.0.0 had a different output format
# Sample data:
# pip (Current: 7.1.2 Latest: 10.0.1 [wheel])
# psutil (Current: 5.2.2 Latest: 5.4.5 [wheel])
# pyasn1 (Current: 0.2.3 Latest: 0.4.2 [wheel])
# pycparser (Current: 2.17 Latest: 2.18 [sdist])
if salt.utils.versions.compare(ver1=pip_version, oper='<', ver2='8.0.0'):
logger.debug('pip module: Old output format')
pat = re.compile(r'(\S*)\s+\(.*Latest:\s+(.*)\)')
# New output format for version 8.0.0+
# Sample data:
# pip (8.0.0) - Latest: 10.0.1 [wheel]
# psutil (5.2.2) - Latest: 5.4.5 [wheel]
# pyasn1 (0.2.3) - Latest: 0.4.2 [wheel]
# pycparser (2.17) - Latest: 2.18 [sdist]
else:
logger.debug('pip module: New output format')
pat = re.compile(r'(\S*)\s+\(.*\)\s+-\s+Latest:\s+(.*)')
for line in result['stdout'].splitlines():
match = pat.search(line)
if match:
name, version_ = match.groups()
else:
logger.error('Can\'t parse line \'%s\'', line)
continue
packages[name] = version_
else:
logger.debug('pip module: JSON output format')
try:
pkgs = salt.utils.json.loads(result['stdout'], strict=False)
except ValueError:
raise CommandExecutionError('Invalid JSON', info=result)
for pkg in pkgs:
packages[pkg['name']] = '{0} [{1}]'.format(pkg['latest_version'],
pkg['latest_filetype'])
return packages
def is_installed(pkgname=None,
bin_env=None,
user=None,
cwd=None):
'''
.. versionadded:: 2018.3.0
Filter list of installed apps from ``freeze`` and return True or False if
``pkgname`` exists in the list of packages installed.
.. note::
If the version of pip available is older than 8.0.3, the packages
wheel, setuptools, and distribute will not be reported by this function
even if they are installed. Unlike :py:func:`pip.freeze
<salt.modules.pip.freeze>`, this function always reports the version of
pip which is installed.
CLI Example:
.. code-block:: bash
salt '*' pip.is_installed salt
'''
for line in freeze(bin_env=bin_env, user=user, cwd=cwd):
if line.startswith('-f') or line.startswith('#'):
# ignore -f line as it contains --find-links directory
# ignore comment lines
continue
elif line.startswith('-e hg+not trust'):
# ignore hg + not trust problem
continue
elif line.startswith('-e'):
line = line.split('-e ')[1]
version_, name = line.split('#egg=')
elif len(line.split('===')) >= 2:
name = line.split('===')[0]
version_ = line.split('===')[1]
elif len(line.split('==')) >= 2:
name = line.split('==')[0]
version_ = line.split('==')[1]
else:
logger.error('Can\'t parse line \'%s\'', line)
continue
if pkgname:
if pkgname == name.lower():
return True
return False
def upgrade_available(pkg,
bin_env=None,
user=None,
cwd=None):
'''
.. versionadded:: 2015.5.0
Check whether or not an upgrade is available for a given package
CLI Example:
.. code-block:: bash
salt '*' pip.upgrade_available <package name>
'''
return pkg in list_upgrades(bin_env=bin_env, user=user, cwd=cwd)
def upgrade(bin_env=None,
user=None,
cwd=None,
use_vt=False):
'''
.. versionadded:: 2015.5.0
Upgrades outdated pip packages.
.. note::
On Windows you can't update salt from pip using salt, so salt will be
skipped
Returns a dict containing the changes.
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
CLI Example:
.. code-block:: bash
salt '*' pip.upgrade
'''
ret = {'changes': {},
'result': True,
'comment': '',
}
cmd = _get_pip_bin(bin_env)
cmd.extend(['install', '-U'])
old = list_(bin_env=bin_env, user=user, cwd=cwd)
cmd_kwargs = dict(cwd=cwd, use_vt=use_vt)
if bin_env and os.path.isdir(bin_env):
cmd_kwargs['env'] = {'VIRTUAL_ENV': bin_env}
errors = False
for pkg in list_upgrades(bin_env=bin_env, user=user, cwd=cwd):
if pkg == 'salt':
if salt.utils.platform.is_windows():
continue
result = __salt__['cmd.run_all'](cmd + [pkg], **cmd_kwargs)
if result['retcode'] != 0:
errors = True
if 'stderr' in result:
ret['comment'] += result['stderr']
if errors:
ret['result'] = False
_clear_context(bin_env)
new = list_(bin_env=bin_env, user=user, cwd=cwd)
ret['changes'] = salt.utils.data.compare_dicts(old, new)
return ret
def list_all_versions(pkg,
bin_env=None,
include_alpha=False,
include_beta=False,
include_rc=False,
user=None,
cwd=None,
index_url=None,
extra_index_url=None):
'''
.. versionadded:: 2017.7.3
List all available versions of a pip package
pkg
The package to check
bin_env
Path to pip (or to a virtualenv). This can be used to specify the path
to the pip to use when more than one Python release is installed (e.g.
``/usr/bin/pip-2.7`` or ``/usr/bin/pip-2.6``. If a directory path is
specified, it is assumed to be a virtualenv.
include_alpha
Include alpha versions in the list
include_beta
Include beta versions in the list
include_rc
Include release candidates versions in the list
user
The user under which to run pip
cwd
Directory from which to run pip
index_url
Base URL of Python Package Index
.. versionadded:: 2019.2.0
extra_index_url
Additional URL of Python Package Index
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' pip.list_all_versions <package name>
'''
cmd = _get_pip_bin(bin_env)
cmd.extend(['install', '{0}==versions'.format(pkg)])
if index_url:
if not salt.utils.url.validate(index_url, VALID_PROTOS):
raise CommandExecutionError(
'\'{0}\' is not a valid URL'.format(index_url)
)
cmd.extend(['--index-url', index_url])
if extra_index_url:
if not salt.utils.url.validate(extra_index_url, VALID_PROTOS):
raise CommandExecutionError(
'\'{0}\' is not a valid URL'.format(extra_index_url)
)
cmd.extend(['--extra-index-url', extra_index_url])
cmd_kwargs = dict(cwd=cwd, runas=user, output_loglevel='quiet', redirect_stderr=True)
if bin_env and os.path.isdir(bin_env):
cmd_kwargs['env'] = {'VIRTUAL_ENV': bin_env}
result = __salt__['cmd.run_all'](cmd, **cmd_kwargs)
filtered = []
if not include_alpha:
filtered.append('a')
if not include_beta:
filtered.append('b')
if not include_rc:
filtered.append('rc')
if filtered:
excludes = re.compile(r'^((?!{0}).)*$'.format('|'.join(filtered)))
else:
excludes = re.compile(r'')
versions = []
for line in result['stdout'].splitlines():
match = re.search(r'\s*Could not find a version.* \(from versions: (.*)\)', line)
if match:
versions = [v for v in match.group(1).split(', ') if v and excludes.match(v)]
versions.sort(key=pkg_resources.parse_version)
break
if not versions:
return None
return versions
|
saltstack/salt
|
salt/modules/pip.py
|
_resolve_requirements_chain
|
python
|
def _resolve_requirements_chain(requirements):
'''
Return an array of requirements file paths that can be used to complete
the no_chown==False && user != None conundrum
'''
chain = []
if isinstance(requirements, six.string_types):
requirements = [requirements]
for req_file in requirements:
chain.append(req_file)
chain.extend(_resolve_requirements_chain(_find_req(req_file)))
return chain
|
Return an array of requirements file paths that can be used to complete
the no_chown==False && user != None conundrum
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/pip.py#L259-L274
| null |
# -*- coding: utf-8 -*-
r'''
Install Python packages with pip to either the system or a virtualenv
Windows Support
===============
.. versionadded:: 2014.7.4
Salt now uses a portable python. As a result the entire pip module is now
functional on the salt installation itself. You can pip install dependencies
for your custom modules. You can even upgrade salt itself using pip. For this
to work properly, you must specify the Current Working Directory (``cwd``) and
the Pip Binary (``bin_env``) salt should use. The variable ``pip_bin`` can be
either a virtualenv path or the path to the pip binary itself.
For example, the following command will list all software installed using pip
to your current salt environment:
.. code-block:: bat
salt <minion> pip.list cwd='C:\salt\bin\Scripts' bin_env='C:\salt\bin\Scripts\pip.exe'
Specifying the ``cwd`` and ``bin_env`` options ensures you're modifying the
salt environment. If these are omitted, it will default to the local
installation of python. If python is not installed locally it will fail saying
it couldn't find pip.
State File Support
------------------
This functionality works in states as well. If you need to pip install colorama
with a state, for example, the following will work:
.. code-block:: yaml
install_colorama:
pip.installed:
- name: colorama
- cwd: 'C:\salt\bin\scripts'
- bin_env: 'C:\salt\bin\scripts\pip.exe'
- upgrade: True
Upgrading Salt using Pip
------------------------
You can now update salt using pip to any version from the 2014.7 branch
forward. Previous version require recompiling some of the dependencies which is
painful in windows.
To do this you just use pip with git to update to the version you want and then
restart the service. Here is a sample state file that upgrades salt to the head
of the 2015.5 branch:
.. code-block:: yaml
install_salt:
pip.installed:
- cwd: 'C:\salt\bin\scripts'
- bin_env: 'C:\salt\bin\scripts\pip.exe'
- editable: git+https://github.com/saltstack/salt@2015.5#egg=salt
- upgrade: True
restart_service:
service.running:
- name: salt-minion
- enable: True
- watch:
- pip: install_salt
.. note::
If you're having problems, you might try doubling the back slashes. For
example, cwd: 'C:\\salt\\bin\\scripts'. Sometimes python thinks the single
back slash is an escape character.
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import logging
import os
try:
import pkg_resources
except ImportError:
pkg_resources = None
import re
import shutil
import sys
import tempfile
# Import Salt libs
import salt.utils.data
import salt.utils.files
import salt.utils.json
import salt.utils.locales
import salt.utils.platform
import salt.utils.stringutils
import salt.utils.url
import salt.utils.versions
from salt.ext import six
from salt.exceptions import CommandExecutionError, CommandNotFoundError
# This needs to be named logger so we don't shadow it in pip.install
logger = logging.getLogger(__name__) # pylint: disable=C0103
# Don't shadow built-in's.
__func_alias__ = {
'list_': 'list'
}
VALID_PROTOS = ['http', 'https', 'ftp', 'file']
rex_pip_chain_read = re.compile(r'-r\s(.*)\n?', re.MULTILINE)
def __virtual__():
'''
There is no way to verify that pip is installed without inspecting the
entire filesystem. If it's not installed in a conventional location, the
user is required to provide the location of pip each time it is used.
'''
if pkg_resources is None:
ret = False, 'Package dependency "pkg_resource" is missing'
else:
ret = 'pip'
return ret
def _clear_context(bin_env=None):
'''
Remove the cached pip version
'''
contextkey = 'pip.version'
if bin_env is not None:
contextkey = '{0}.{1}'.format(contextkey, bin_env)
__context__.pop(contextkey, None)
def _get_pip_bin(bin_env):
'''
Locate the pip binary, either from `bin_env` as a virtualenv, as the
executable itself, or from searching conventional filesystem locations
'''
if not bin_env:
logger.debug('pip: Using pip from currently-running Python')
return [os.path.normpath(sys.executable), '-m', 'pip']
python_bin = 'python.exe' if salt.utils.platform.is_windows() else 'python'
def _search_paths(*basedirs):
ret = []
for path in basedirs:
ret.extend([
os.path.join(path, python_bin),
os.path.join(path, 'bin', python_bin),
os.path.join(path, 'Scripts', python_bin)
])
return ret
# try to get python bin from virtualenv (i.e. bin_env)
if os.path.isdir(bin_env):
for bin_path in _search_paths(bin_env):
if os.path.isfile(bin_path):
if os.access(bin_path, os.X_OK):
logger.debug('pip: Found python binary: %s', bin_path)
return [os.path.normpath(bin_path), '-m', 'pip']
else:
logger.debug(
'pip: Found python binary by name but it is not '
'executable: %s', bin_path
)
raise CommandNotFoundError(
'Could not find a pip binary in virtualenv {0}'.format(bin_env)
)
# bin_env is the python or pip binary
elif os.access(bin_env, os.X_OK):
if os.path.isfile(bin_env):
# If the python binary was passed, return it
if 'python' in os.path.basename(bin_env):
return [os.path.normpath(bin_env), '-m', 'pip']
# We have been passed a pip binary, use the pip binary.
return [os.path.normpath(bin_env)]
raise CommandExecutionError(
'Could not find a pip binary within {0}'.format(bin_env)
)
else:
raise CommandNotFoundError(
'Access denied to {0}, could not find a pip binary'.format(bin_env)
)
def _get_cached_requirements(requirements, saltenv):
'''
Get the location of a cached requirements file; caching if necessary.
'''
req_file, senv = salt.utils.url.parse(requirements)
if senv:
saltenv = senv
if req_file not in __salt__['cp.list_master'](saltenv):
# Requirements file does not exist in the given saltenv.
return False
cached_requirements = __salt__['cp.is_cached'](
requirements, saltenv
)
if not cached_requirements:
# It's not cached, let's cache it.
cached_requirements = __salt__['cp.cache_file'](
requirements, saltenv
)
# Check if the master version has changed.
if __salt__['cp.hash_file'](requirements, saltenv) != \
__salt__['cp.hash_file'](cached_requirements, saltenv):
cached_requirements = __salt__['cp.cache_file'](
requirements, saltenv
)
return cached_requirements
def _get_env_activate(bin_env):
'''
Return the path to the activate binary
'''
if not bin_env:
raise CommandNotFoundError('Could not find a `activate` binary')
if os.path.isdir(bin_env):
if salt.utils.platform.is_windows():
activate_bin = os.path.join(bin_env, 'Scripts', 'activate.bat')
else:
activate_bin = os.path.join(bin_env, 'bin', 'activate')
if os.path.isfile(activate_bin):
return activate_bin
raise CommandNotFoundError('Could not find a `activate` binary')
def _find_req(link):
logger.info('_find_req -- link = %s', link)
with salt.utils.files.fopen(link) as fh_link:
child_links = rex_pip_chain_read.findall(
salt.utils.stringutils.to_unicode(fh_link.read())
)
base_path = os.path.dirname(link)
child_links = [os.path.join(base_path, d) for d in child_links]
return child_links
def _process_requirements(requirements, cmd, cwd, saltenv, user):
'''
Process the requirements argument
'''
cleanup_requirements = []
if requirements is not None:
if isinstance(requirements, six.string_types):
requirements = [r.strip() for r in requirements.split(',')]
elif not isinstance(requirements, list):
raise TypeError('requirements must be a string or list')
treq = None
for requirement in requirements:
logger.debug('TREQ IS: %s', treq)
if requirement.startswith('salt://'):
cached_requirements = _get_cached_requirements(
requirement, saltenv
)
if not cached_requirements:
ret = {'result': False,
'comment': 'pip requirements file \'{0}\' not found'
.format(requirement)}
return None, ret
requirement = cached_requirements
if user:
# Need to make a temporary copy since the user will, most
# likely, not have the right permissions to read the file
if not treq:
treq = tempfile.mkdtemp()
__salt__['file.chown'](treq, user, None)
# In Windows, just being owner of a file isn't enough. You also
# need permissions
if salt.utils.platform.is_windows():
__utils__['dacl.set_permissions'](
obj_name=treq,
principal=user,
permissions='read_execute')
current_directory = None
if not current_directory:
current_directory = os.path.abspath(os.curdir)
logger.info('_process_requirements from directory, '
'%s -- requirement: %s', cwd, requirement)
if cwd is None:
r = requirement
c = cwd
requirement_abspath = os.path.abspath(requirement)
cwd = os.path.dirname(requirement_abspath)
requirement = os.path.basename(requirement)
logger.debug('\n\tcwd: %s -> %s\n\trequirement: %s -> %s\n',
c, cwd, r, requirement
)
os.chdir(cwd)
reqs = _resolve_requirements_chain(requirement)
os.chdir(current_directory)
logger.info('request files: %s', reqs)
for req_file in reqs:
if not os.path.isabs(req_file):
req_file = os.path.join(cwd, req_file)
logger.debug('TREQ N CWD: %s -- %s -- for %s', treq, cwd, req_file)
target_path = os.path.join(treq, os.path.basename(req_file))
logger.debug('S: %s', req_file)
logger.debug('T: %s', target_path)
target_base = os.path.dirname(target_path)
if not os.path.exists(target_base):
os.makedirs(target_base, mode=0o755)
__salt__['file.chown'](target_base, user, None)
if not os.path.exists(target_path):
logger.debug(
'Copying %s to %s', req_file, target_path
)
__salt__['file.copy'](req_file, target_path)
logger.debug(
'Changing ownership of requirements file \'%s\' to '
'user \'%s\'', target_path, user
)
__salt__['file.chown'](target_path, user, None)
req_args = os.path.join(treq, requirement) if treq else requirement
cmd.extend(['--requirement', req_args])
cleanup_requirements.append(treq)
logger.debug('CLEANUP_REQUIREMENTS: %s', cleanup_requirements)
return cleanup_requirements, None
def _format_env_vars(env_vars):
ret = {}
if env_vars:
if isinstance(env_vars, dict):
for key, val in six.iteritems(env_vars):
if not isinstance(key, six.string_types):
key = str(key) # future lint: disable=blacklisted-function
if not isinstance(val, six.string_types):
val = str(val) # future lint: disable=blacklisted-function
ret[key] = val
else:
raise CommandExecutionError(
'env_vars {0} is not a dictionary'.format(env_vars))
return ret
def install(pkgs=None, # pylint: disable=R0912,R0913,R0914
requirements=None,
bin_env=None,
use_wheel=False,
no_use_wheel=False,
log=None,
proxy=None,
timeout=None,
editable=None,
find_links=None,
index_url=None,
extra_index_url=None,
no_index=False,
mirrors=None,
build=None,
target=None,
download=None,
download_cache=None,
source=None,
upgrade=False,
force_reinstall=False,
ignore_installed=False,
exists_action=None,
no_deps=False,
no_install=False,
no_download=False,
global_options=None,
install_options=None,
user=None,
cwd=None,
pre_releases=False,
cert=None,
allow_all_external=False,
allow_external=None,
allow_unverified=None,
process_dependency_links=False,
saltenv='base',
env_vars=None,
use_vt=False,
trusted_host=None,
no_cache_dir=False,
cache_dir=None,
no_binary=None,
extra_args=None,
**kwargs):
'''
Install packages with pip
Install packages individually or from a pip requirements file. Install
packages globally or to a virtualenv.
pkgs
Comma separated list of packages to install
requirements
Path to requirements
bin_env
Path to pip (or to a virtualenv). This can be used to specify the path
to the pip to use when more than one Python release is installed (e.g.
``/usr/bin/pip-2.7`` or ``/usr/bin/pip-2.6``. If a directory path is
specified, it is assumed to be a virtualenv.
.. note::
For Windows, if the pip module is being used to upgrade the pip
package, bin_env should be the path to the virtualenv or to the
python binary that should be used. The pip command is unable to
upgrade itself in Windows.
use_wheel
Prefer wheel archives (requires pip>=1.4)
no_use_wheel
Force to not use wheel archives (requires pip>=1.4,<10.0.0)
no_binary
Force to not use binary packages (requires pip >= 7.0.0)
Accepts either :all: to disable all binary packages, :none: to empty the set,
or one or more package names with commas between them
log
Log file where a complete (maximum verbosity) record will be kept
proxy
Specify a proxy in the form ``user:passwd@proxy.server:port``. Note
that the ``user:password@`` is optional and required only if you are
behind an authenticated proxy. If you provide
``user@proxy.server:port`` then you will be prompted for a password.
timeout
Set the socket timeout (default 15 seconds)
editable
install something editable (e.g.
``git+https://github.com/worldcompany/djangoembed.git#egg=djangoembed``)
find_links
URL to search for packages
index_url
Base URL of Python Package Index
extra_index_url
Extra URLs of package indexes to use in addition to ``index_url``
no_index
Ignore package index
mirrors
Specific mirror URL(s) to query (automatically adds --use-mirrors)
.. warning::
This option has been deprecated and removed in pip version 7.0.0.
Please use ``index_url`` and/or ``extra_index_url`` instead.
build
Unpack packages into ``build`` dir
target
Install packages into ``target`` dir
download
Download packages into ``download`` instead of installing them
download_cache | cache_dir
Cache downloaded packages in ``download_cache`` or ``cache_dir`` dir
source
Check out ``editable`` packages into ``source`` dir
upgrade
Upgrade all packages to the newest available version
force_reinstall
When upgrading, reinstall all packages even if they are already
up-to-date.
ignore_installed
Ignore the installed packages (reinstalling instead)
exists_action
Default action when a path already exists: (s)witch, (i)gnore, (w)ipe,
(b)ackup
no_deps
Ignore package dependencies
no_install
Download and unpack all packages, but don't actually install them
no_download
Don't download any packages, just install the ones already downloaded
(completes an install run with ``--no-install``)
install_options
Extra arguments to be supplied to the setup.py install command (e.g.
like ``--install-option='--install-scripts=/usr/local/bin'``). Use
multiple --install-option options to pass multiple options to setup.py
install. If you are using an option with a directory path, be sure to
use absolute path.
global_options
Extra global options to be supplied to the setup.py call before the
install command.
user
The user under which to run pip
cwd
Directory from which to run pip
pre_releases
Include pre-releases in the available versions
cert
Provide a path to an alternate CA bundle
allow_all_external
Allow the installation of all externally hosted files
allow_external
Allow the installation of externally hosted files (comma separated
list)
allow_unverified
Allow the installation of insecure and unverifiable files (comma
separated list)
process_dependency_links
Enable the processing of dependency links
env_vars
Set environment variables that some builds will depend on. For example,
a Python C-module may have a Makefile that needs INCLUDE_PATH set to
pick up a header file while compiling. This must be in the form of a
dictionary or a mapping.
Example:
.. code-block:: bash
salt '*' pip.install django_app env_vars="{'CUSTOM_PATH': '/opt/django_app'}"
trusted_host
Mark this host as trusted, even though it does not have valid or any
HTTPS.
use_vt
Use VT terminal emulation (see output while installing)
no_cache_dir
Disable the cache.
extra_args
pip keyword and positional arguments not yet implemented in salt
.. code-block:: yaml
salt '*' pip.install pandas extra_args="[{'--latest-pip-kwarg':'param'}, '--latest-pip-arg']"
.. warning::
If unsupported options are passed here that are not supported in a
minion's version of pip, a `No such option error` will be thrown.
Will be translated into the following pip command:
.. code-block:: bash
pip install pandas --latest-pip-kwarg param --latest-pip-arg
CLI Example:
.. code-block:: bash
salt '*' pip.install <package name>,<package2 name>
salt '*' pip.install requirements=/path/to/requirements.txt
salt '*' pip.install <package name> bin_env=/path/to/virtualenv
salt '*' pip.install <package name> bin_env=/path/to/pip_bin
Complicated CLI example::
salt '*' pip.install markdown,django \
editable=git+https://github.com/worldcompany/djangoembed.git#egg=djangoembed upgrade=True no_deps=True
'''
cmd = _get_pip_bin(bin_env)
cmd.append('install')
cleanup_requirements, error = _process_requirements(
requirements=requirements,
cmd=cmd,
cwd=cwd,
saltenv=saltenv,
user=user
)
if error:
return error
cur_version = version(bin_env)
if use_wheel:
min_version = '1.4'
max_version = '9.0.3'
too_low = salt.utils.versions.compare(ver1=cur_version, oper='<', ver2=min_version)
too_high = salt.utils.versions.compare(ver1=cur_version, oper='>', ver2=max_version)
if too_low or too_high:
logger.error(
'The --use-wheel option is only supported in pip between %s and '
'%s. The version of pip detected is %s. This option '
'will be ignored.', min_version, max_version, cur_version
)
else:
cmd.append('--use-wheel')
if no_use_wheel:
min_version = '1.4'
max_version = '9.0.3'
too_low = salt.utils.versions.compare(ver1=cur_version, oper='<', ver2=min_version)
too_high = salt.utils.versions.compare(ver1=cur_version, oper='>', ver2=max_version)
if too_low or too_high:
logger.error(
'The --no-use-wheel option is only supported in pip between %s and '
'%s. The version of pip detected is %s. This option '
'will be ignored.', min_version, max_version, cur_version
)
else:
cmd.append('--no-use-wheel')
if no_binary:
min_version = '7.0.0'
too_low = salt.utils.versions.compare(ver1=cur_version, oper='<', ver2=min_version)
if too_low:
logger.error(
'The --no-binary option is only supported in pip %s and '
'newer. The version of pip detected is %s. This option '
'will be ignored.', min_version, cur_version
)
else:
if isinstance(no_binary, list):
no_binary = ','.join(no_binary)
cmd.extend(['--no-binary', no_binary])
if log:
if os.path.isdir(log):
raise IOError(
'\'{0}\' is a directory. Use --log path_to_file'.format(log))
elif not os.access(log, os.W_OK):
raise IOError('\'{0}\' is not writeable'.format(log))
cmd.extend(['--log', log])
if proxy:
cmd.extend(['--proxy', proxy])
if timeout:
try:
if isinstance(timeout, float):
# Catch floating point input, exception will be caught in
# exception class below.
raise ValueError('Timeout cannot be a float')
int(timeout)
except ValueError:
raise ValueError(
'\'{0}\' is not a valid timeout, must be an integer'
.format(timeout)
)
cmd.extend(['--timeout', timeout])
if find_links:
if isinstance(find_links, six.string_types):
find_links = [l.strip() for l in find_links.split(',')]
for link in find_links:
if not (salt.utils.url.validate(link, VALID_PROTOS) or os.path.exists(link)):
raise CommandExecutionError(
'\'{0}\' is not a valid URL or path'.format(link)
)
cmd.extend(['--find-links', link])
if no_index and (index_url or extra_index_url):
raise CommandExecutionError(
'\'no_index\' and (\'index_url\' or \'extra_index_url\') are '
'mutually exclusive.'
)
if index_url:
if not salt.utils.url.validate(index_url, VALID_PROTOS):
raise CommandExecutionError(
'\'{0}\' is not a valid URL'.format(index_url)
)
cmd.extend(['--index-url', index_url])
if extra_index_url:
if not salt.utils.url.validate(extra_index_url, VALID_PROTOS):
raise CommandExecutionError(
'\'{0}\' is not a valid URL'.format(extra_index_url)
)
cmd.extend(['--extra-index-url', extra_index_url])
if no_index:
cmd.append('--no-index')
if mirrors:
# https://github.com/pypa/pip/pull/2641/files#diff-3ef137fb9ffdd400f117a565cd94c188L216
if salt.utils.versions.compare(ver1=cur_version, oper='>=', ver2='7.0.0'):
raise CommandExecutionError(
'pip >= 7.0.0 does not support mirror argument:'
' use index_url and/or extra_index_url instead'
)
if isinstance(mirrors, six.string_types):
mirrors = [m.strip() for m in mirrors.split(',')]
cmd.append('--use-mirrors')
for mirror in mirrors:
if not mirror.startswith('http://'):
raise CommandExecutionError(
'\'{0}\' is not a valid URL'.format(mirror)
)
cmd.extend(['--mirrors', mirror])
if build:
cmd.extend(['--build', build])
if target:
cmd.extend(['--target', target])
if download:
cmd.extend(['--download', download])
if download_cache or cache_dir:
cmd.extend(['--cache-dir' if salt.utils.versions.compare(
ver1=cur_version, oper='>=', ver2='6.0'
) else '--download-cache', download_cache or cache_dir])
if source:
cmd.extend(['--source', source])
if upgrade:
cmd.append('--upgrade')
if force_reinstall:
cmd.append('--force-reinstall')
if ignore_installed:
cmd.append('--ignore-installed')
if exists_action:
if exists_action.lower() not in ('s', 'i', 'w', 'b'):
raise CommandExecutionError(
'The exists_action pip option only supports the values '
's, i, w, and b. \'{0}\' is not valid.'.format(exists_action)
)
cmd.extend(['--exists-action', exists_action])
if no_deps:
cmd.append('--no-deps')
if no_install:
cmd.append('--no-install')
if no_download:
cmd.append('--no-download')
if no_cache_dir:
cmd.append('--no-cache-dir')
if pre_releases:
# Check the locally installed pip version
pip_version = cur_version
# From pip v1.4 the --pre flag is available
if salt.utils.versions.compare(ver1=pip_version, oper='>=', ver2='1.4'):
cmd.append('--pre')
if cert:
cmd.extend(['--cert', cert])
if global_options:
if isinstance(global_options, six.string_types):
global_options = [go.strip() for go in global_options.split(',')]
for opt in global_options:
cmd.extend(['--global-option', opt])
if install_options:
if isinstance(install_options, six.string_types):
install_options = [io.strip() for io in install_options.split(',')]
for opt in install_options:
cmd.extend(['--install-option', opt])
if pkgs:
if not isinstance(pkgs, list):
try:
pkgs = [p.strip() for p in pkgs.split(',')]
except AttributeError:
pkgs = [p.strip() for p in six.text_type(pkgs).split(',')]
pkgs = salt.utils.data.stringify(salt.utils.data.decode_list(pkgs))
# It's possible we replaced version-range commas with semicolons so
# they would survive the previous line (in the pip.installed state).
# Put the commas back in while making sure the names are contained in
# quotes, this allows for proper version spec passing salt>=0.17.0
cmd.extend([p.replace(';', ',') for p in pkgs])
elif not any([requirements, editable]):
# Starting with pip 10.0.0, if no packages are specified in the
# command, it returns a retcode 1. So instead of running the command,
# just return the output without running pip.
return {'retcode': 0, 'stdout': 'No packages to install.'}
if editable:
egg_match = re.compile(r'(?:#|#.*?&)egg=([^&]*)')
if isinstance(editable, six.string_types):
editable = [e.strip() for e in editable.split(',')]
for entry in editable:
# Is the editable local?
if not (entry == '.' or entry.startswith(('file://', '/'))):
match = egg_match.search(entry)
if not match or not match.group(1):
# Missing #egg=theEggName
raise CommandExecutionError(
'You must specify an egg for this editable'
)
cmd.extend(['--editable', entry])
if allow_all_external:
cmd.append('--allow-all-external')
if allow_external:
if isinstance(allow_external, six.string_types):
allow_external = [p.strip() for p in allow_external.split(',')]
for pkg in allow_external:
cmd.extend(['--allow-external', pkg])
if allow_unverified:
if isinstance(allow_unverified, six.string_types):
allow_unverified = \
[p.strip() for p in allow_unverified.split(',')]
for pkg in allow_unverified:
cmd.extend(['--allow-unverified', pkg])
if process_dependency_links:
cmd.append('--process-dependency-links')
if trusted_host:
cmd.extend(['--trusted-host', trusted_host])
if extra_args:
# These are arguments from the latest version of pip that
# have not yet been implemented in salt
for arg in extra_args:
# It is a keyword argument
if isinstance(arg, dict):
# There will only ever be one item in this dictionary
key, val = arg.popitem()
# Don't allow any recursion into keyword arg definitions
# Don't allow multiple definitions of a keyword
if isinstance(val, (dict, list)):
raise TypeError("Too many levels in: {}".format(key))
# This is a a normal one-to-one keyword argument
cmd.extend([key, val])
# It is a positional argument, append it to the list
else:
cmd.append(arg)
cmd_kwargs = dict(saltenv=saltenv, use_vt=use_vt, runas=user)
if kwargs:
cmd_kwargs.update(kwargs)
if env_vars:
cmd_kwargs.setdefault('env', {}).update(_format_env_vars(env_vars))
try:
if cwd:
cmd_kwargs['cwd'] = cwd
if bin_env and os.path.isdir(bin_env):
cmd_kwargs.setdefault('env', {})['VIRTUAL_ENV'] = bin_env
logger.debug(
'TRY BLOCK: end of pip.install -- cmd: %s, cmd_kwargs: %s',
cmd, cmd_kwargs
)
return __salt__['cmd.run_all'](cmd, python_shell=False, **cmd_kwargs)
finally:
_clear_context(bin_env)
for tempdir in [cr for cr in cleanup_requirements if cr is not None]:
if os.path.isdir(tempdir):
shutil.rmtree(tempdir)
def uninstall(pkgs=None,
requirements=None,
bin_env=None,
log=None,
proxy=None,
timeout=None,
user=None,
cwd=None,
saltenv='base',
use_vt=False):
'''
Uninstall packages individually or from a pip requirements file
pkgs
comma separated list of packages to install
requirements
Path to requirements file
bin_env
Path to pip (or to a virtualenv). This can be used to specify the path
to the pip to use when more than one Python release is installed (e.g.
``/usr/bin/pip-2.7`` or ``/usr/bin/pip-2.6``. If a directory path is
specified, it is assumed to be a virtualenv.
log
Log file where a complete (maximum verbosity) record will be kept
proxy
Specify a proxy in the format ``user:passwd@proxy.server:port``. Note
that the ``user:password@`` is optional and required only if you are
behind an authenticated proxy. If you provide
``user@proxy.server:port`` then you will be prompted for a password.
timeout
Set the socket timeout (default 15 seconds)
user
The user under which to run pip
cwd
Directory from which to run pip
use_vt
Use VT terminal emulation (see output while installing)
CLI Example:
.. code-block:: bash
salt '*' pip.uninstall <package name>,<package2 name>
salt '*' pip.uninstall requirements=/path/to/requirements.txt
salt '*' pip.uninstall <package name> bin_env=/path/to/virtualenv
salt '*' pip.uninstall <package name> bin_env=/path/to/pip_bin
'''
cmd = _get_pip_bin(bin_env)
cmd.extend(['uninstall', '-y'])
cleanup_requirements, error = _process_requirements(
requirements=requirements, cmd=cmd, saltenv=saltenv, user=user,
cwd=cwd
)
if error:
return error
if log:
try:
# TODO make this check if writeable
os.path.exists(log)
except IOError:
raise IOError('\'{0}\' is not writeable'.format(log))
cmd.extend(['--log', log])
if proxy:
cmd.extend(['--proxy', proxy])
if timeout:
try:
if isinstance(timeout, float):
# Catch floating point input, exception will be caught in
# exception class below.
raise ValueError('Timeout cannot be a float')
int(timeout)
except ValueError:
raise ValueError(
'\'{0}\' is not a valid timeout, must be an integer'
.format(timeout)
)
cmd.extend(['--timeout', timeout])
if pkgs:
if isinstance(pkgs, six.string_types):
pkgs = [p.strip() for p in pkgs.split(',')]
if requirements:
for requirement in requirements:
with salt.utils.files.fopen(requirement) as rq_:
for req in rq_:
req = salt.utils.stringutils.to_unicode(req)
try:
req_pkg, _ = req.split('==')
if req_pkg in pkgs:
pkgs.remove(req_pkg)
except ValueError:
pass
cmd.extend(pkgs)
cmd_kwargs = dict(python_shell=False, runas=user,
cwd=cwd, saltenv=saltenv, use_vt=use_vt)
if bin_env and os.path.isdir(bin_env):
cmd_kwargs['env'] = {'VIRTUAL_ENV': bin_env}
try:
return __salt__['cmd.run_all'](cmd, **cmd_kwargs)
finally:
_clear_context(bin_env)
for requirement in cleanup_requirements:
if requirement:
try:
os.remove(requirement)
except OSError:
pass
def freeze(bin_env=None,
user=None,
cwd=None,
use_vt=False,
env_vars=None,
**kwargs):
'''
Return a list of installed packages either globally or in the specified
virtualenv
bin_env
Path to pip (or to a virtualenv). This can be used to specify the path
to the pip to use when more than one Python release is installed (e.g.
``/usr/bin/pip-2.7`` or ``/usr/bin/pip-2.6``. If a directory path is
specified, it is assumed to be a virtualenv.
user
The user under which to run pip
cwd
Directory from which to run pip
.. note::
If the version of pip available is older than 8.0.3, the list will not
include the packages ``pip``, ``wheel``, ``setuptools``, or
``distribute`` even if they are installed.
CLI Example:
.. code-block:: bash
salt '*' pip.freeze bin_env=/home/code/path/to/virtualenv
'''
cmd = _get_pip_bin(bin_env)
cmd.append('freeze')
# Include pip, setuptools, distribute, wheel
min_version = '8.0.3'
cur_version = version(bin_env)
if salt.utils.versions.compare(ver1=cur_version, oper='<', ver2=min_version):
logger.warning(
'The version of pip installed is %s, which is older than %s. '
'The packages pip, wheel, setuptools, and distribute will not be '
'included in the output of pip.freeze', cur_version, min_version
)
else:
cmd.append('--all')
cmd_kwargs = dict(runas=user, cwd=cwd, use_vt=use_vt, python_shell=False)
if kwargs:
cmd_kwargs.update(**kwargs)
if bin_env and os.path.isdir(bin_env):
cmd_kwargs['env'] = {'VIRTUAL_ENV': bin_env}
if env_vars:
cmd_kwargs.setdefault('env', {}).update(_format_env_vars(env_vars))
result = __salt__['cmd.run_all'](cmd, **cmd_kwargs)
if result['retcode']:
raise CommandExecutionError(result['stderr'], info=result)
return result['stdout'].splitlines()
def list_(prefix=None,
bin_env=None,
user=None,
cwd=None,
env_vars=None,
**kwargs):
'''
Filter list of installed apps from ``freeze`` and check to see if
``prefix`` exists in the list of packages installed.
.. note::
If the version of pip available is older than 8.0.3, the packages
``wheel``, ``setuptools``, and ``distribute`` will not be reported by
this function even if they are installed. Unlike :py:func:`pip.freeze
<salt.modules.pip.freeze>`, this function always reports the version of
pip which is installed.
CLI Example:
.. code-block:: bash
salt '*' pip.list salt
'''
packages = {}
if prefix is None or 'pip'.startswith(prefix):
packages['pip'] = version(bin_env)
for line in freeze(bin_env=bin_env,
user=user,
cwd=cwd,
env_vars=env_vars,
**kwargs):
if line.startswith('-f') or line.startswith('#'):
# ignore -f line as it contains --find-links directory
# ignore comment lines
continue
elif line.startswith('-e hg+not trust'):
# ignore hg + not trust problem
continue
elif line.startswith('-e'):
line = line.split('-e ')[1]
if '#egg=' in line:
version_, name = line.split('#egg=')
else:
if len(line.split('===')) >= 2:
name = line.split('===')[0]
version_ = line.split('===')[1]
elif len(line.split('==')) >= 2:
name = line.split('==')[0]
version_ = line.split('==')[1]
elif len(line.split('===')) >= 2:
name = line.split('===')[0]
version_ = line.split('===')[1]
elif len(line.split('==')) >= 2:
name = line.split('==')[0]
version_ = line.split('==')[1]
else:
logger.error('Can\'t parse line \'%s\'', line)
continue
if prefix:
if name.lower().startswith(prefix.lower()):
packages[name] = version_
else:
packages[name] = version_
return packages
def version(bin_env=None):
'''
.. versionadded:: 0.17.0
Returns the version of pip. Use ``bin_env`` to specify the path to a
virtualenv and get the version of pip in that virtualenv.
If unable to detect the pip version, returns ``None``.
CLI Example:
.. code-block:: bash
salt '*' pip.version
'''
contextkey = 'pip.version'
if bin_env is not None:
contextkey = '{0}.{1}'.format(contextkey, bin_env)
if contextkey in __context__:
return __context__[contextkey]
cmd = _get_pip_bin(bin_env)[:]
cmd.append('--version')
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
if ret['retcode']:
raise CommandNotFoundError('Could not find a `pip` binary')
try:
pip_version = re.match(r'^pip (\S+)', ret['stdout']).group(1)
except AttributeError:
pip_version = None
__context__[contextkey] = pip_version
return pip_version
def list_upgrades(bin_env=None,
user=None,
cwd=None):
'''
Check whether or not an upgrade is available for all packages
CLI Example:
.. code-block:: bash
salt '*' pip.list_upgrades
'''
cmd = _get_pip_bin(bin_env)
cmd.extend(['list', '--outdated'])
pip_version = version(bin_env)
# Pip started supporting the ability to output json starting with 9.0.0
min_version = '9.0'
if salt.utils.versions.compare(ver1=pip_version,
oper='>=',
ver2=min_version):
cmd.append('--format=json')
cmd_kwargs = dict(cwd=cwd, runas=user)
if bin_env and os.path.isdir(bin_env):
cmd_kwargs['env'] = {'VIRTUAL_ENV': bin_env}
result = __salt__['cmd.run_all'](cmd, **cmd_kwargs)
if result['retcode']:
raise CommandExecutionError(result['stderr'], info=result)
packages = {}
# Pip started supporting the ability to output json starting with 9.0.0
# Older versions will have to parse stdout
if salt.utils.versions.compare(ver1=pip_version, oper='<', ver2='9.0.0'):
# Pip versions < 8.0.0 had a different output format
# Sample data:
# pip (Current: 7.1.2 Latest: 10.0.1 [wheel])
# psutil (Current: 5.2.2 Latest: 5.4.5 [wheel])
# pyasn1 (Current: 0.2.3 Latest: 0.4.2 [wheel])
# pycparser (Current: 2.17 Latest: 2.18 [sdist])
if salt.utils.versions.compare(ver1=pip_version, oper='<', ver2='8.0.0'):
logger.debug('pip module: Old output format')
pat = re.compile(r'(\S*)\s+\(.*Latest:\s+(.*)\)')
# New output format for version 8.0.0+
# Sample data:
# pip (8.0.0) - Latest: 10.0.1 [wheel]
# psutil (5.2.2) - Latest: 5.4.5 [wheel]
# pyasn1 (0.2.3) - Latest: 0.4.2 [wheel]
# pycparser (2.17) - Latest: 2.18 [sdist]
else:
logger.debug('pip module: New output format')
pat = re.compile(r'(\S*)\s+\(.*\)\s+-\s+Latest:\s+(.*)')
for line in result['stdout'].splitlines():
match = pat.search(line)
if match:
name, version_ = match.groups()
else:
logger.error('Can\'t parse line \'%s\'', line)
continue
packages[name] = version_
else:
logger.debug('pip module: JSON output format')
try:
pkgs = salt.utils.json.loads(result['stdout'], strict=False)
except ValueError:
raise CommandExecutionError('Invalid JSON', info=result)
for pkg in pkgs:
packages[pkg['name']] = '{0} [{1}]'.format(pkg['latest_version'],
pkg['latest_filetype'])
return packages
def is_installed(pkgname=None,
bin_env=None,
user=None,
cwd=None):
'''
.. versionadded:: 2018.3.0
Filter list of installed apps from ``freeze`` and return True or False if
``pkgname`` exists in the list of packages installed.
.. note::
If the version of pip available is older than 8.0.3, the packages
wheel, setuptools, and distribute will not be reported by this function
even if they are installed. Unlike :py:func:`pip.freeze
<salt.modules.pip.freeze>`, this function always reports the version of
pip which is installed.
CLI Example:
.. code-block:: bash
salt '*' pip.is_installed salt
'''
for line in freeze(bin_env=bin_env, user=user, cwd=cwd):
if line.startswith('-f') or line.startswith('#'):
# ignore -f line as it contains --find-links directory
# ignore comment lines
continue
elif line.startswith('-e hg+not trust'):
# ignore hg + not trust problem
continue
elif line.startswith('-e'):
line = line.split('-e ')[1]
version_, name = line.split('#egg=')
elif len(line.split('===')) >= 2:
name = line.split('===')[0]
version_ = line.split('===')[1]
elif len(line.split('==')) >= 2:
name = line.split('==')[0]
version_ = line.split('==')[1]
else:
logger.error('Can\'t parse line \'%s\'', line)
continue
if pkgname:
if pkgname == name.lower():
return True
return False
def upgrade_available(pkg,
bin_env=None,
user=None,
cwd=None):
'''
.. versionadded:: 2015.5.0
Check whether or not an upgrade is available for a given package
CLI Example:
.. code-block:: bash
salt '*' pip.upgrade_available <package name>
'''
return pkg in list_upgrades(bin_env=bin_env, user=user, cwd=cwd)
def upgrade(bin_env=None,
user=None,
cwd=None,
use_vt=False):
'''
.. versionadded:: 2015.5.0
Upgrades outdated pip packages.
.. note::
On Windows you can't update salt from pip using salt, so salt will be
skipped
Returns a dict containing the changes.
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
CLI Example:
.. code-block:: bash
salt '*' pip.upgrade
'''
ret = {'changes': {},
'result': True,
'comment': '',
}
cmd = _get_pip_bin(bin_env)
cmd.extend(['install', '-U'])
old = list_(bin_env=bin_env, user=user, cwd=cwd)
cmd_kwargs = dict(cwd=cwd, use_vt=use_vt)
if bin_env and os.path.isdir(bin_env):
cmd_kwargs['env'] = {'VIRTUAL_ENV': bin_env}
errors = False
for pkg in list_upgrades(bin_env=bin_env, user=user, cwd=cwd):
if pkg == 'salt':
if salt.utils.platform.is_windows():
continue
result = __salt__['cmd.run_all'](cmd + [pkg], **cmd_kwargs)
if result['retcode'] != 0:
errors = True
if 'stderr' in result:
ret['comment'] += result['stderr']
if errors:
ret['result'] = False
_clear_context(bin_env)
new = list_(bin_env=bin_env, user=user, cwd=cwd)
ret['changes'] = salt.utils.data.compare_dicts(old, new)
return ret
def list_all_versions(pkg,
bin_env=None,
include_alpha=False,
include_beta=False,
include_rc=False,
user=None,
cwd=None,
index_url=None,
extra_index_url=None):
'''
.. versionadded:: 2017.7.3
List all available versions of a pip package
pkg
The package to check
bin_env
Path to pip (or to a virtualenv). This can be used to specify the path
to the pip to use when more than one Python release is installed (e.g.
``/usr/bin/pip-2.7`` or ``/usr/bin/pip-2.6``. If a directory path is
specified, it is assumed to be a virtualenv.
include_alpha
Include alpha versions in the list
include_beta
Include beta versions in the list
include_rc
Include release candidates versions in the list
user
The user under which to run pip
cwd
Directory from which to run pip
index_url
Base URL of Python Package Index
.. versionadded:: 2019.2.0
extra_index_url
Additional URL of Python Package Index
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' pip.list_all_versions <package name>
'''
cmd = _get_pip_bin(bin_env)
cmd.extend(['install', '{0}==versions'.format(pkg)])
if index_url:
if not salt.utils.url.validate(index_url, VALID_PROTOS):
raise CommandExecutionError(
'\'{0}\' is not a valid URL'.format(index_url)
)
cmd.extend(['--index-url', index_url])
if extra_index_url:
if not salt.utils.url.validate(extra_index_url, VALID_PROTOS):
raise CommandExecutionError(
'\'{0}\' is not a valid URL'.format(extra_index_url)
)
cmd.extend(['--extra-index-url', extra_index_url])
cmd_kwargs = dict(cwd=cwd, runas=user, output_loglevel='quiet', redirect_stderr=True)
if bin_env and os.path.isdir(bin_env):
cmd_kwargs['env'] = {'VIRTUAL_ENV': bin_env}
result = __salt__['cmd.run_all'](cmd, **cmd_kwargs)
filtered = []
if not include_alpha:
filtered.append('a')
if not include_beta:
filtered.append('b')
if not include_rc:
filtered.append('rc')
if filtered:
excludes = re.compile(r'^((?!{0}).)*$'.format('|'.join(filtered)))
else:
excludes = re.compile(r'')
versions = []
for line in result['stdout'].splitlines():
match = re.search(r'\s*Could not find a version.* \(from versions: (.*)\)', line)
if match:
versions = [v for v in match.group(1).split(', ') if v and excludes.match(v)]
versions.sort(key=pkg_resources.parse_version)
break
if not versions:
return None
return versions
|
saltstack/salt
|
salt/modules/pip.py
|
_process_requirements
|
python
|
def _process_requirements(requirements, cmd, cwd, saltenv, user):
'''
Process the requirements argument
'''
cleanup_requirements = []
if requirements is not None:
if isinstance(requirements, six.string_types):
requirements = [r.strip() for r in requirements.split(',')]
elif not isinstance(requirements, list):
raise TypeError('requirements must be a string or list')
treq = None
for requirement in requirements:
logger.debug('TREQ IS: %s', treq)
if requirement.startswith('salt://'):
cached_requirements = _get_cached_requirements(
requirement, saltenv
)
if not cached_requirements:
ret = {'result': False,
'comment': 'pip requirements file \'{0}\' not found'
.format(requirement)}
return None, ret
requirement = cached_requirements
if user:
# Need to make a temporary copy since the user will, most
# likely, not have the right permissions to read the file
if not treq:
treq = tempfile.mkdtemp()
__salt__['file.chown'](treq, user, None)
# In Windows, just being owner of a file isn't enough. You also
# need permissions
if salt.utils.platform.is_windows():
__utils__['dacl.set_permissions'](
obj_name=treq,
principal=user,
permissions='read_execute')
current_directory = None
if not current_directory:
current_directory = os.path.abspath(os.curdir)
logger.info('_process_requirements from directory, '
'%s -- requirement: %s', cwd, requirement)
if cwd is None:
r = requirement
c = cwd
requirement_abspath = os.path.abspath(requirement)
cwd = os.path.dirname(requirement_abspath)
requirement = os.path.basename(requirement)
logger.debug('\n\tcwd: %s -> %s\n\trequirement: %s -> %s\n',
c, cwd, r, requirement
)
os.chdir(cwd)
reqs = _resolve_requirements_chain(requirement)
os.chdir(current_directory)
logger.info('request files: %s', reqs)
for req_file in reqs:
if not os.path.isabs(req_file):
req_file = os.path.join(cwd, req_file)
logger.debug('TREQ N CWD: %s -- %s -- for %s', treq, cwd, req_file)
target_path = os.path.join(treq, os.path.basename(req_file))
logger.debug('S: %s', req_file)
logger.debug('T: %s', target_path)
target_base = os.path.dirname(target_path)
if not os.path.exists(target_base):
os.makedirs(target_base, mode=0o755)
__salt__['file.chown'](target_base, user, None)
if not os.path.exists(target_path):
logger.debug(
'Copying %s to %s', req_file, target_path
)
__salt__['file.copy'](req_file, target_path)
logger.debug(
'Changing ownership of requirements file \'%s\' to '
'user \'%s\'', target_path, user
)
__salt__['file.chown'](target_path, user, None)
req_args = os.path.join(treq, requirement) if treq else requirement
cmd.extend(['--requirement', req_args])
cleanup_requirements.append(treq)
logger.debug('CLEANUP_REQUIREMENTS: %s', cleanup_requirements)
return cleanup_requirements, None
|
Process the requirements argument
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/pip.py#L277-L383
| null |
# -*- coding: utf-8 -*-
r'''
Install Python packages with pip to either the system or a virtualenv
Windows Support
===============
.. versionadded:: 2014.7.4
Salt now uses a portable python. As a result the entire pip module is now
functional on the salt installation itself. You can pip install dependencies
for your custom modules. You can even upgrade salt itself using pip. For this
to work properly, you must specify the Current Working Directory (``cwd``) and
the Pip Binary (``bin_env``) salt should use. The variable ``pip_bin`` can be
either a virtualenv path or the path to the pip binary itself.
For example, the following command will list all software installed using pip
to your current salt environment:
.. code-block:: bat
salt <minion> pip.list cwd='C:\salt\bin\Scripts' bin_env='C:\salt\bin\Scripts\pip.exe'
Specifying the ``cwd`` and ``bin_env`` options ensures you're modifying the
salt environment. If these are omitted, it will default to the local
installation of python. If python is not installed locally it will fail saying
it couldn't find pip.
State File Support
------------------
This functionality works in states as well. If you need to pip install colorama
with a state, for example, the following will work:
.. code-block:: yaml
install_colorama:
pip.installed:
- name: colorama
- cwd: 'C:\salt\bin\scripts'
- bin_env: 'C:\salt\bin\scripts\pip.exe'
- upgrade: True
Upgrading Salt using Pip
------------------------
You can now update salt using pip to any version from the 2014.7 branch
forward. Previous version require recompiling some of the dependencies which is
painful in windows.
To do this you just use pip with git to update to the version you want and then
restart the service. Here is a sample state file that upgrades salt to the head
of the 2015.5 branch:
.. code-block:: yaml
install_salt:
pip.installed:
- cwd: 'C:\salt\bin\scripts'
- bin_env: 'C:\salt\bin\scripts\pip.exe'
- editable: git+https://github.com/saltstack/salt@2015.5#egg=salt
- upgrade: True
restart_service:
service.running:
- name: salt-minion
- enable: True
- watch:
- pip: install_salt
.. note::
If you're having problems, you might try doubling the back slashes. For
example, cwd: 'C:\\salt\\bin\\scripts'. Sometimes python thinks the single
back slash is an escape character.
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import logging
import os
try:
import pkg_resources
except ImportError:
pkg_resources = None
import re
import shutil
import sys
import tempfile
# Import Salt libs
import salt.utils.data
import salt.utils.files
import salt.utils.json
import salt.utils.locales
import salt.utils.platform
import salt.utils.stringutils
import salt.utils.url
import salt.utils.versions
from salt.ext import six
from salt.exceptions import CommandExecutionError, CommandNotFoundError
# This needs to be named logger so we don't shadow it in pip.install
logger = logging.getLogger(__name__) # pylint: disable=C0103
# Don't shadow built-in's.
__func_alias__ = {
'list_': 'list'
}
VALID_PROTOS = ['http', 'https', 'ftp', 'file']
rex_pip_chain_read = re.compile(r'-r\s(.*)\n?', re.MULTILINE)
def __virtual__():
'''
There is no way to verify that pip is installed without inspecting the
entire filesystem. If it's not installed in a conventional location, the
user is required to provide the location of pip each time it is used.
'''
if pkg_resources is None:
ret = False, 'Package dependency "pkg_resource" is missing'
else:
ret = 'pip'
return ret
def _clear_context(bin_env=None):
'''
Remove the cached pip version
'''
contextkey = 'pip.version'
if bin_env is not None:
contextkey = '{0}.{1}'.format(contextkey, bin_env)
__context__.pop(contextkey, None)
def _get_pip_bin(bin_env):
'''
Locate the pip binary, either from `bin_env` as a virtualenv, as the
executable itself, or from searching conventional filesystem locations
'''
if not bin_env:
logger.debug('pip: Using pip from currently-running Python')
return [os.path.normpath(sys.executable), '-m', 'pip']
python_bin = 'python.exe' if salt.utils.platform.is_windows() else 'python'
def _search_paths(*basedirs):
ret = []
for path in basedirs:
ret.extend([
os.path.join(path, python_bin),
os.path.join(path, 'bin', python_bin),
os.path.join(path, 'Scripts', python_bin)
])
return ret
# try to get python bin from virtualenv (i.e. bin_env)
if os.path.isdir(bin_env):
for bin_path in _search_paths(bin_env):
if os.path.isfile(bin_path):
if os.access(bin_path, os.X_OK):
logger.debug('pip: Found python binary: %s', bin_path)
return [os.path.normpath(bin_path), '-m', 'pip']
else:
logger.debug(
'pip: Found python binary by name but it is not '
'executable: %s', bin_path
)
raise CommandNotFoundError(
'Could not find a pip binary in virtualenv {0}'.format(bin_env)
)
# bin_env is the python or pip binary
elif os.access(bin_env, os.X_OK):
if os.path.isfile(bin_env):
# If the python binary was passed, return it
if 'python' in os.path.basename(bin_env):
return [os.path.normpath(bin_env), '-m', 'pip']
# We have been passed a pip binary, use the pip binary.
return [os.path.normpath(bin_env)]
raise CommandExecutionError(
'Could not find a pip binary within {0}'.format(bin_env)
)
else:
raise CommandNotFoundError(
'Access denied to {0}, could not find a pip binary'.format(bin_env)
)
def _get_cached_requirements(requirements, saltenv):
'''
Get the location of a cached requirements file; caching if necessary.
'''
req_file, senv = salt.utils.url.parse(requirements)
if senv:
saltenv = senv
if req_file not in __salt__['cp.list_master'](saltenv):
# Requirements file does not exist in the given saltenv.
return False
cached_requirements = __salt__['cp.is_cached'](
requirements, saltenv
)
if not cached_requirements:
# It's not cached, let's cache it.
cached_requirements = __salt__['cp.cache_file'](
requirements, saltenv
)
# Check if the master version has changed.
if __salt__['cp.hash_file'](requirements, saltenv) != \
__salt__['cp.hash_file'](cached_requirements, saltenv):
cached_requirements = __salt__['cp.cache_file'](
requirements, saltenv
)
return cached_requirements
def _get_env_activate(bin_env):
'''
Return the path to the activate binary
'''
if not bin_env:
raise CommandNotFoundError('Could not find a `activate` binary')
if os.path.isdir(bin_env):
if salt.utils.platform.is_windows():
activate_bin = os.path.join(bin_env, 'Scripts', 'activate.bat')
else:
activate_bin = os.path.join(bin_env, 'bin', 'activate')
if os.path.isfile(activate_bin):
return activate_bin
raise CommandNotFoundError('Could not find a `activate` binary')
def _find_req(link):
logger.info('_find_req -- link = %s', link)
with salt.utils.files.fopen(link) as fh_link:
child_links = rex_pip_chain_read.findall(
salt.utils.stringutils.to_unicode(fh_link.read())
)
base_path = os.path.dirname(link)
child_links = [os.path.join(base_path, d) for d in child_links]
return child_links
def _resolve_requirements_chain(requirements):
'''
Return an array of requirements file paths that can be used to complete
the no_chown==False && user != None conundrum
'''
chain = []
if isinstance(requirements, six.string_types):
requirements = [requirements]
for req_file in requirements:
chain.append(req_file)
chain.extend(_resolve_requirements_chain(_find_req(req_file)))
return chain
def _format_env_vars(env_vars):
ret = {}
if env_vars:
if isinstance(env_vars, dict):
for key, val in six.iteritems(env_vars):
if not isinstance(key, six.string_types):
key = str(key) # future lint: disable=blacklisted-function
if not isinstance(val, six.string_types):
val = str(val) # future lint: disable=blacklisted-function
ret[key] = val
else:
raise CommandExecutionError(
'env_vars {0} is not a dictionary'.format(env_vars))
return ret
def install(pkgs=None, # pylint: disable=R0912,R0913,R0914
requirements=None,
bin_env=None,
use_wheel=False,
no_use_wheel=False,
log=None,
proxy=None,
timeout=None,
editable=None,
find_links=None,
index_url=None,
extra_index_url=None,
no_index=False,
mirrors=None,
build=None,
target=None,
download=None,
download_cache=None,
source=None,
upgrade=False,
force_reinstall=False,
ignore_installed=False,
exists_action=None,
no_deps=False,
no_install=False,
no_download=False,
global_options=None,
install_options=None,
user=None,
cwd=None,
pre_releases=False,
cert=None,
allow_all_external=False,
allow_external=None,
allow_unverified=None,
process_dependency_links=False,
saltenv='base',
env_vars=None,
use_vt=False,
trusted_host=None,
no_cache_dir=False,
cache_dir=None,
no_binary=None,
extra_args=None,
**kwargs):
'''
Install packages with pip
Install packages individually or from a pip requirements file. Install
packages globally or to a virtualenv.
pkgs
Comma separated list of packages to install
requirements
Path to requirements
bin_env
Path to pip (or to a virtualenv). This can be used to specify the path
to the pip to use when more than one Python release is installed (e.g.
``/usr/bin/pip-2.7`` or ``/usr/bin/pip-2.6``. If a directory path is
specified, it is assumed to be a virtualenv.
.. note::
For Windows, if the pip module is being used to upgrade the pip
package, bin_env should be the path to the virtualenv or to the
python binary that should be used. The pip command is unable to
upgrade itself in Windows.
use_wheel
Prefer wheel archives (requires pip>=1.4)
no_use_wheel
Force to not use wheel archives (requires pip>=1.4,<10.0.0)
no_binary
Force to not use binary packages (requires pip >= 7.0.0)
Accepts either :all: to disable all binary packages, :none: to empty the set,
or one or more package names with commas between them
log
Log file where a complete (maximum verbosity) record will be kept
proxy
Specify a proxy in the form ``user:passwd@proxy.server:port``. Note
that the ``user:password@`` is optional and required only if you are
behind an authenticated proxy. If you provide
``user@proxy.server:port`` then you will be prompted for a password.
timeout
Set the socket timeout (default 15 seconds)
editable
install something editable (e.g.
``git+https://github.com/worldcompany/djangoembed.git#egg=djangoembed``)
find_links
URL to search for packages
index_url
Base URL of Python Package Index
extra_index_url
Extra URLs of package indexes to use in addition to ``index_url``
no_index
Ignore package index
mirrors
Specific mirror URL(s) to query (automatically adds --use-mirrors)
.. warning::
This option has been deprecated and removed in pip version 7.0.0.
Please use ``index_url`` and/or ``extra_index_url`` instead.
build
Unpack packages into ``build`` dir
target
Install packages into ``target`` dir
download
Download packages into ``download`` instead of installing them
download_cache | cache_dir
Cache downloaded packages in ``download_cache`` or ``cache_dir`` dir
source
Check out ``editable`` packages into ``source`` dir
upgrade
Upgrade all packages to the newest available version
force_reinstall
When upgrading, reinstall all packages even if they are already
up-to-date.
ignore_installed
Ignore the installed packages (reinstalling instead)
exists_action
Default action when a path already exists: (s)witch, (i)gnore, (w)ipe,
(b)ackup
no_deps
Ignore package dependencies
no_install
Download and unpack all packages, but don't actually install them
no_download
Don't download any packages, just install the ones already downloaded
(completes an install run with ``--no-install``)
install_options
Extra arguments to be supplied to the setup.py install command (e.g.
like ``--install-option='--install-scripts=/usr/local/bin'``). Use
multiple --install-option options to pass multiple options to setup.py
install. If you are using an option with a directory path, be sure to
use absolute path.
global_options
Extra global options to be supplied to the setup.py call before the
install command.
user
The user under which to run pip
cwd
Directory from which to run pip
pre_releases
Include pre-releases in the available versions
cert
Provide a path to an alternate CA bundle
allow_all_external
Allow the installation of all externally hosted files
allow_external
Allow the installation of externally hosted files (comma separated
list)
allow_unverified
Allow the installation of insecure and unverifiable files (comma
separated list)
process_dependency_links
Enable the processing of dependency links
env_vars
Set environment variables that some builds will depend on. For example,
a Python C-module may have a Makefile that needs INCLUDE_PATH set to
pick up a header file while compiling. This must be in the form of a
dictionary or a mapping.
Example:
.. code-block:: bash
salt '*' pip.install django_app env_vars="{'CUSTOM_PATH': '/opt/django_app'}"
trusted_host
Mark this host as trusted, even though it does not have valid or any
HTTPS.
use_vt
Use VT terminal emulation (see output while installing)
no_cache_dir
Disable the cache.
extra_args
pip keyword and positional arguments not yet implemented in salt
.. code-block:: yaml
salt '*' pip.install pandas extra_args="[{'--latest-pip-kwarg':'param'}, '--latest-pip-arg']"
.. warning::
If unsupported options are passed here that are not supported in a
minion's version of pip, a `No such option error` will be thrown.
Will be translated into the following pip command:
.. code-block:: bash
pip install pandas --latest-pip-kwarg param --latest-pip-arg
CLI Example:
.. code-block:: bash
salt '*' pip.install <package name>,<package2 name>
salt '*' pip.install requirements=/path/to/requirements.txt
salt '*' pip.install <package name> bin_env=/path/to/virtualenv
salt '*' pip.install <package name> bin_env=/path/to/pip_bin
Complicated CLI example::
salt '*' pip.install markdown,django \
editable=git+https://github.com/worldcompany/djangoembed.git#egg=djangoembed upgrade=True no_deps=True
'''
cmd = _get_pip_bin(bin_env)
cmd.append('install')
cleanup_requirements, error = _process_requirements(
requirements=requirements,
cmd=cmd,
cwd=cwd,
saltenv=saltenv,
user=user
)
if error:
return error
cur_version = version(bin_env)
if use_wheel:
min_version = '1.4'
max_version = '9.0.3'
too_low = salt.utils.versions.compare(ver1=cur_version, oper='<', ver2=min_version)
too_high = salt.utils.versions.compare(ver1=cur_version, oper='>', ver2=max_version)
if too_low or too_high:
logger.error(
'The --use-wheel option is only supported in pip between %s and '
'%s. The version of pip detected is %s. This option '
'will be ignored.', min_version, max_version, cur_version
)
else:
cmd.append('--use-wheel')
if no_use_wheel:
min_version = '1.4'
max_version = '9.0.3'
too_low = salt.utils.versions.compare(ver1=cur_version, oper='<', ver2=min_version)
too_high = salt.utils.versions.compare(ver1=cur_version, oper='>', ver2=max_version)
if too_low or too_high:
logger.error(
'The --no-use-wheel option is only supported in pip between %s and '
'%s. The version of pip detected is %s. This option '
'will be ignored.', min_version, max_version, cur_version
)
else:
cmd.append('--no-use-wheel')
if no_binary:
min_version = '7.0.0'
too_low = salt.utils.versions.compare(ver1=cur_version, oper='<', ver2=min_version)
if too_low:
logger.error(
'The --no-binary option is only supported in pip %s and '
'newer. The version of pip detected is %s. This option '
'will be ignored.', min_version, cur_version
)
else:
if isinstance(no_binary, list):
no_binary = ','.join(no_binary)
cmd.extend(['--no-binary', no_binary])
if log:
if os.path.isdir(log):
raise IOError(
'\'{0}\' is a directory. Use --log path_to_file'.format(log))
elif not os.access(log, os.W_OK):
raise IOError('\'{0}\' is not writeable'.format(log))
cmd.extend(['--log', log])
if proxy:
cmd.extend(['--proxy', proxy])
if timeout:
try:
if isinstance(timeout, float):
# Catch floating point input, exception will be caught in
# exception class below.
raise ValueError('Timeout cannot be a float')
int(timeout)
except ValueError:
raise ValueError(
'\'{0}\' is not a valid timeout, must be an integer'
.format(timeout)
)
cmd.extend(['--timeout', timeout])
if find_links:
if isinstance(find_links, six.string_types):
find_links = [l.strip() for l in find_links.split(',')]
for link in find_links:
if not (salt.utils.url.validate(link, VALID_PROTOS) or os.path.exists(link)):
raise CommandExecutionError(
'\'{0}\' is not a valid URL or path'.format(link)
)
cmd.extend(['--find-links', link])
if no_index and (index_url or extra_index_url):
raise CommandExecutionError(
'\'no_index\' and (\'index_url\' or \'extra_index_url\') are '
'mutually exclusive.'
)
if index_url:
if not salt.utils.url.validate(index_url, VALID_PROTOS):
raise CommandExecutionError(
'\'{0}\' is not a valid URL'.format(index_url)
)
cmd.extend(['--index-url', index_url])
if extra_index_url:
if not salt.utils.url.validate(extra_index_url, VALID_PROTOS):
raise CommandExecutionError(
'\'{0}\' is not a valid URL'.format(extra_index_url)
)
cmd.extend(['--extra-index-url', extra_index_url])
if no_index:
cmd.append('--no-index')
if mirrors:
# https://github.com/pypa/pip/pull/2641/files#diff-3ef137fb9ffdd400f117a565cd94c188L216
if salt.utils.versions.compare(ver1=cur_version, oper='>=', ver2='7.0.0'):
raise CommandExecutionError(
'pip >= 7.0.0 does not support mirror argument:'
' use index_url and/or extra_index_url instead'
)
if isinstance(mirrors, six.string_types):
mirrors = [m.strip() for m in mirrors.split(',')]
cmd.append('--use-mirrors')
for mirror in mirrors:
if not mirror.startswith('http://'):
raise CommandExecutionError(
'\'{0}\' is not a valid URL'.format(mirror)
)
cmd.extend(['--mirrors', mirror])
if build:
cmd.extend(['--build', build])
if target:
cmd.extend(['--target', target])
if download:
cmd.extend(['--download', download])
if download_cache or cache_dir:
cmd.extend(['--cache-dir' if salt.utils.versions.compare(
ver1=cur_version, oper='>=', ver2='6.0'
) else '--download-cache', download_cache or cache_dir])
if source:
cmd.extend(['--source', source])
if upgrade:
cmd.append('--upgrade')
if force_reinstall:
cmd.append('--force-reinstall')
if ignore_installed:
cmd.append('--ignore-installed')
if exists_action:
if exists_action.lower() not in ('s', 'i', 'w', 'b'):
raise CommandExecutionError(
'The exists_action pip option only supports the values '
's, i, w, and b. \'{0}\' is not valid.'.format(exists_action)
)
cmd.extend(['--exists-action', exists_action])
if no_deps:
cmd.append('--no-deps')
if no_install:
cmd.append('--no-install')
if no_download:
cmd.append('--no-download')
if no_cache_dir:
cmd.append('--no-cache-dir')
if pre_releases:
# Check the locally installed pip version
pip_version = cur_version
# From pip v1.4 the --pre flag is available
if salt.utils.versions.compare(ver1=pip_version, oper='>=', ver2='1.4'):
cmd.append('--pre')
if cert:
cmd.extend(['--cert', cert])
if global_options:
if isinstance(global_options, six.string_types):
global_options = [go.strip() for go in global_options.split(',')]
for opt in global_options:
cmd.extend(['--global-option', opt])
if install_options:
if isinstance(install_options, six.string_types):
install_options = [io.strip() for io in install_options.split(',')]
for opt in install_options:
cmd.extend(['--install-option', opt])
if pkgs:
if not isinstance(pkgs, list):
try:
pkgs = [p.strip() for p in pkgs.split(',')]
except AttributeError:
pkgs = [p.strip() for p in six.text_type(pkgs).split(',')]
pkgs = salt.utils.data.stringify(salt.utils.data.decode_list(pkgs))
# It's possible we replaced version-range commas with semicolons so
# they would survive the previous line (in the pip.installed state).
# Put the commas back in while making sure the names are contained in
# quotes, this allows for proper version spec passing salt>=0.17.0
cmd.extend([p.replace(';', ',') for p in pkgs])
elif not any([requirements, editable]):
# Starting with pip 10.0.0, if no packages are specified in the
# command, it returns a retcode 1. So instead of running the command,
# just return the output without running pip.
return {'retcode': 0, 'stdout': 'No packages to install.'}
if editable:
egg_match = re.compile(r'(?:#|#.*?&)egg=([^&]*)')
if isinstance(editable, six.string_types):
editable = [e.strip() for e in editable.split(',')]
for entry in editable:
# Is the editable local?
if not (entry == '.' or entry.startswith(('file://', '/'))):
match = egg_match.search(entry)
if not match or not match.group(1):
# Missing #egg=theEggName
raise CommandExecutionError(
'You must specify an egg for this editable'
)
cmd.extend(['--editable', entry])
if allow_all_external:
cmd.append('--allow-all-external')
if allow_external:
if isinstance(allow_external, six.string_types):
allow_external = [p.strip() for p in allow_external.split(',')]
for pkg in allow_external:
cmd.extend(['--allow-external', pkg])
if allow_unverified:
if isinstance(allow_unverified, six.string_types):
allow_unverified = \
[p.strip() for p in allow_unverified.split(',')]
for pkg in allow_unverified:
cmd.extend(['--allow-unverified', pkg])
if process_dependency_links:
cmd.append('--process-dependency-links')
if trusted_host:
cmd.extend(['--trusted-host', trusted_host])
if extra_args:
# These are arguments from the latest version of pip that
# have not yet been implemented in salt
for arg in extra_args:
# It is a keyword argument
if isinstance(arg, dict):
# There will only ever be one item in this dictionary
key, val = arg.popitem()
# Don't allow any recursion into keyword arg definitions
# Don't allow multiple definitions of a keyword
if isinstance(val, (dict, list)):
raise TypeError("Too many levels in: {}".format(key))
# This is a a normal one-to-one keyword argument
cmd.extend([key, val])
# It is a positional argument, append it to the list
else:
cmd.append(arg)
cmd_kwargs = dict(saltenv=saltenv, use_vt=use_vt, runas=user)
if kwargs:
cmd_kwargs.update(kwargs)
if env_vars:
cmd_kwargs.setdefault('env', {}).update(_format_env_vars(env_vars))
try:
if cwd:
cmd_kwargs['cwd'] = cwd
if bin_env and os.path.isdir(bin_env):
cmd_kwargs.setdefault('env', {})['VIRTUAL_ENV'] = bin_env
logger.debug(
'TRY BLOCK: end of pip.install -- cmd: %s, cmd_kwargs: %s',
cmd, cmd_kwargs
)
return __salt__['cmd.run_all'](cmd, python_shell=False, **cmd_kwargs)
finally:
_clear_context(bin_env)
for tempdir in [cr for cr in cleanup_requirements if cr is not None]:
if os.path.isdir(tempdir):
shutil.rmtree(tempdir)
def uninstall(pkgs=None,
requirements=None,
bin_env=None,
log=None,
proxy=None,
timeout=None,
user=None,
cwd=None,
saltenv='base',
use_vt=False):
'''
Uninstall packages individually or from a pip requirements file
pkgs
comma separated list of packages to install
requirements
Path to requirements file
bin_env
Path to pip (or to a virtualenv). This can be used to specify the path
to the pip to use when more than one Python release is installed (e.g.
``/usr/bin/pip-2.7`` or ``/usr/bin/pip-2.6``. If a directory path is
specified, it is assumed to be a virtualenv.
log
Log file where a complete (maximum verbosity) record will be kept
proxy
Specify a proxy in the format ``user:passwd@proxy.server:port``. Note
that the ``user:password@`` is optional and required only if you are
behind an authenticated proxy. If you provide
``user@proxy.server:port`` then you will be prompted for a password.
timeout
Set the socket timeout (default 15 seconds)
user
The user under which to run pip
cwd
Directory from which to run pip
use_vt
Use VT terminal emulation (see output while installing)
CLI Example:
.. code-block:: bash
salt '*' pip.uninstall <package name>,<package2 name>
salt '*' pip.uninstall requirements=/path/to/requirements.txt
salt '*' pip.uninstall <package name> bin_env=/path/to/virtualenv
salt '*' pip.uninstall <package name> bin_env=/path/to/pip_bin
'''
cmd = _get_pip_bin(bin_env)
cmd.extend(['uninstall', '-y'])
cleanup_requirements, error = _process_requirements(
requirements=requirements, cmd=cmd, saltenv=saltenv, user=user,
cwd=cwd
)
if error:
return error
if log:
try:
# TODO make this check if writeable
os.path.exists(log)
except IOError:
raise IOError('\'{0}\' is not writeable'.format(log))
cmd.extend(['--log', log])
if proxy:
cmd.extend(['--proxy', proxy])
if timeout:
try:
if isinstance(timeout, float):
# Catch floating point input, exception will be caught in
# exception class below.
raise ValueError('Timeout cannot be a float')
int(timeout)
except ValueError:
raise ValueError(
'\'{0}\' is not a valid timeout, must be an integer'
.format(timeout)
)
cmd.extend(['--timeout', timeout])
if pkgs:
if isinstance(pkgs, six.string_types):
pkgs = [p.strip() for p in pkgs.split(',')]
if requirements:
for requirement in requirements:
with salt.utils.files.fopen(requirement) as rq_:
for req in rq_:
req = salt.utils.stringutils.to_unicode(req)
try:
req_pkg, _ = req.split('==')
if req_pkg in pkgs:
pkgs.remove(req_pkg)
except ValueError:
pass
cmd.extend(pkgs)
cmd_kwargs = dict(python_shell=False, runas=user,
cwd=cwd, saltenv=saltenv, use_vt=use_vt)
if bin_env and os.path.isdir(bin_env):
cmd_kwargs['env'] = {'VIRTUAL_ENV': bin_env}
try:
return __salt__['cmd.run_all'](cmd, **cmd_kwargs)
finally:
_clear_context(bin_env)
for requirement in cleanup_requirements:
if requirement:
try:
os.remove(requirement)
except OSError:
pass
def freeze(bin_env=None,
user=None,
cwd=None,
use_vt=False,
env_vars=None,
**kwargs):
'''
Return a list of installed packages either globally or in the specified
virtualenv
bin_env
Path to pip (or to a virtualenv). This can be used to specify the path
to the pip to use when more than one Python release is installed (e.g.
``/usr/bin/pip-2.7`` or ``/usr/bin/pip-2.6``. If a directory path is
specified, it is assumed to be a virtualenv.
user
The user under which to run pip
cwd
Directory from which to run pip
.. note::
If the version of pip available is older than 8.0.3, the list will not
include the packages ``pip``, ``wheel``, ``setuptools``, or
``distribute`` even if they are installed.
CLI Example:
.. code-block:: bash
salt '*' pip.freeze bin_env=/home/code/path/to/virtualenv
'''
cmd = _get_pip_bin(bin_env)
cmd.append('freeze')
# Include pip, setuptools, distribute, wheel
min_version = '8.0.3'
cur_version = version(bin_env)
if salt.utils.versions.compare(ver1=cur_version, oper='<', ver2=min_version):
logger.warning(
'The version of pip installed is %s, which is older than %s. '
'The packages pip, wheel, setuptools, and distribute will not be '
'included in the output of pip.freeze', cur_version, min_version
)
else:
cmd.append('--all')
cmd_kwargs = dict(runas=user, cwd=cwd, use_vt=use_vt, python_shell=False)
if kwargs:
cmd_kwargs.update(**kwargs)
if bin_env and os.path.isdir(bin_env):
cmd_kwargs['env'] = {'VIRTUAL_ENV': bin_env}
if env_vars:
cmd_kwargs.setdefault('env', {}).update(_format_env_vars(env_vars))
result = __salt__['cmd.run_all'](cmd, **cmd_kwargs)
if result['retcode']:
raise CommandExecutionError(result['stderr'], info=result)
return result['stdout'].splitlines()
def list_(prefix=None,
bin_env=None,
user=None,
cwd=None,
env_vars=None,
**kwargs):
'''
Filter list of installed apps from ``freeze`` and check to see if
``prefix`` exists in the list of packages installed.
.. note::
If the version of pip available is older than 8.0.3, the packages
``wheel``, ``setuptools``, and ``distribute`` will not be reported by
this function even if they are installed. Unlike :py:func:`pip.freeze
<salt.modules.pip.freeze>`, this function always reports the version of
pip which is installed.
CLI Example:
.. code-block:: bash
salt '*' pip.list salt
'''
packages = {}
if prefix is None or 'pip'.startswith(prefix):
packages['pip'] = version(bin_env)
for line in freeze(bin_env=bin_env,
user=user,
cwd=cwd,
env_vars=env_vars,
**kwargs):
if line.startswith('-f') or line.startswith('#'):
# ignore -f line as it contains --find-links directory
# ignore comment lines
continue
elif line.startswith('-e hg+not trust'):
# ignore hg + not trust problem
continue
elif line.startswith('-e'):
line = line.split('-e ')[1]
if '#egg=' in line:
version_, name = line.split('#egg=')
else:
if len(line.split('===')) >= 2:
name = line.split('===')[0]
version_ = line.split('===')[1]
elif len(line.split('==')) >= 2:
name = line.split('==')[0]
version_ = line.split('==')[1]
elif len(line.split('===')) >= 2:
name = line.split('===')[0]
version_ = line.split('===')[1]
elif len(line.split('==')) >= 2:
name = line.split('==')[0]
version_ = line.split('==')[1]
else:
logger.error('Can\'t parse line \'%s\'', line)
continue
if prefix:
if name.lower().startswith(prefix.lower()):
packages[name] = version_
else:
packages[name] = version_
return packages
def version(bin_env=None):
'''
.. versionadded:: 0.17.0
Returns the version of pip. Use ``bin_env`` to specify the path to a
virtualenv and get the version of pip in that virtualenv.
If unable to detect the pip version, returns ``None``.
CLI Example:
.. code-block:: bash
salt '*' pip.version
'''
contextkey = 'pip.version'
if bin_env is not None:
contextkey = '{0}.{1}'.format(contextkey, bin_env)
if contextkey in __context__:
return __context__[contextkey]
cmd = _get_pip_bin(bin_env)[:]
cmd.append('--version')
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
if ret['retcode']:
raise CommandNotFoundError('Could not find a `pip` binary')
try:
pip_version = re.match(r'^pip (\S+)', ret['stdout']).group(1)
except AttributeError:
pip_version = None
__context__[contextkey] = pip_version
return pip_version
def list_upgrades(bin_env=None,
user=None,
cwd=None):
'''
Check whether or not an upgrade is available for all packages
CLI Example:
.. code-block:: bash
salt '*' pip.list_upgrades
'''
cmd = _get_pip_bin(bin_env)
cmd.extend(['list', '--outdated'])
pip_version = version(bin_env)
# Pip started supporting the ability to output json starting with 9.0.0
min_version = '9.0'
if salt.utils.versions.compare(ver1=pip_version,
oper='>=',
ver2=min_version):
cmd.append('--format=json')
cmd_kwargs = dict(cwd=cwd, runas=user)
if bin_env and os.path.isdir(bin_env):
cmd_kwargs['env'] = {'VIRTUAL_ENV': bin_env}
result = __salt__['cmd.run_all'](cmd, **cmd_kwargs)
if result['retcode']:
raise CommandExecutionError(result['stderr'], info=result)
packages = {}
# Pip started supporting the ability to output json starting with 9.0.0
# Older versions will have to parse stdout
if salt.utils.versions.compare(ver1=pip_version, oper='<', ver2='9.0.0'):
# Pip versions < 8.0.0 had a different output format
# Sample data:
# pip (Current: 7.1.2 Latest: 10.0.1 [wheel])
# psutil (Current: 5.2.2 Latest: 5.4.5 [wheel])
# pyasn1 (Current: 0.2.3 Latest: 0.4.2 [wheel])
# pycparser (Current: 2.17 Latest: 2.18 [sdist])
if salt.utils.versions.compare(ver1=pip_version, oper='<', ver2='8.0.0'):
logger.debug('pip module: Old output format')
pat = re.compile(r'(\S*)\s+\(.*Latest:\s+(.*)\)')
# New output format for version 8.0.0+
# Sample data:
# pip (8.0.0) - Latest: 10.0.1 [wheel]
# psutil (5.2.2) - Latest: 5.4.5 [wheel]
# pyasn1 (0.2.3) - Latest: 0.4.2 [wheel]
# pycparser (2.17) - Latest: 2.18 [sdist]
else:
logger.debug('pip module: New output format')
pat = re.compile(r'(\S*)\s+\(.*\)\s+-\s+Latest:\s+(.*)')
for line in result['stdout'].splitlines():
match = pat.search(line)
if match:
name, version_ = match.groups()
else:
logger.error('Can\'t parse line \'%s\'', line)
continue
packages[name] = version_
else:
logger.debug('pip module: JSON output format')
try:
pkgs = salt.utils.json.loads(result['stdout'], strict=False)
except ValueError:
raise CommandExecutionError('Invalid JSON', info=result)
for pkg in pkgs:
packages[pkg['name']] = '{0} [{1}]'.format(pkg['latest_version'],
pkg['latest_filetype'])
return packages
def is_installed(pkgname=None,
bin_env=None,
user=None,
cwd=None):
'''
.. versionadded:: 2018.3.0
Filter list of installed apps from ``freeze`` and return True or False if
``pkgname`` exists in the list of packages installed.
.. note::
If the version of pip available is older than 8.0.3, the packages
wheel, setuptools, and distribute will not be reported by this function
even if they are installed. Unlike :py:func:`pip.freeze
<salt.modules.pip.freeze>`, this function always reports the version of
pip which is installed.
CLI Example:
.. code-block:: bash
salt '*' pip.is_installed salt
'''
for line in freeze(bin_env=bin_env, user=user, cwd=cwd):
if line.startswith('-f') or line.startswith('#'):
# ignore -f line as it contains --find-links directory
# ignore comment lines
continue
elif line.startswith('-e hg+not trust'):
# ignore hg + not trust problem
continue
elif line.startswith('-e'):
line = line.split('-e ')[1]
version_, name = line.split('#egg=')
elif len(line.split('===')) >= 2:
name = line.split('===')[0]
version_ = line.split('===')[1]
elif len(line.split('==')) >= 2:
name = line.split('==')[0]
version_ = line.split('==')[1]
else:
logger.error('Can\'t parse line \'%s\'', line)
continue
if pkgname:
if pkgname == name.lower():
return True
return False
def upgrade_available(pkg,
bin_env=None,
user=None,
cwd=None):
'''
.. versionadded:: 2015.5.0
Check whether or not an upgrade is available for a given package
CLI Example:
.. code-block:: bash
salt '*' pip.upgrade_available <package name>
'''
return pkg in list_upgrades(bin_env=bin_env, user=user, cwd=cwd)
def upgrade(bin_env=None,
user=None,
cwd=None,
use_vt=False):
'''
.. versionadded:: 2015.5.0
Upgrades outdated pip packages.
.. note::
On Windows you can't update salt from pip using salt, so salt will be
skipped
Returns a dict containing the changes.
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
CLI Example:
.. code-block:: bash
salt '*' pip.upgrade
'''
ret = {'changes': {},
'result': True,
'comment': '',
}
cmd = _get_pip_bin(bin_env)
cmd.extend(['install', '-U'])
old = list_(bin_env=bin_env, user=user, cwd=cwd)
cmd_kwargs = dict(cwd=cwd, use_vt=use_vt)
if bin_env and os.path.isdir(bin_env):
cmd_kwargs['env'] = {'VIRTUAL_ENV': bin_env}
errors = False
for pkg in list_upgrades(bin_env=bin_env, user=user, cwd=cwd):
if pkg == 'salt':
if salt.utils.platform.is_windows():
continue
result = __salt__['cmd.run_all'](cmd + [pkg], **cmd_kwargs)
if result['retcode'] != 0:
errors = True
if 'stderr' in result:
ret['comment'] += result['stderr']
if errors:
ret['result'] = False
_clear_context(bin_env)
new = list_(bin_env=bin_env, user=user, cwd=cwd)
ret['changes'] = salt.utils.data.compare_dicts(old, new)
return ret
def list_all_versions(pkg,
bin_env=None,
include_alpha=False,
include_beta=False,
include_rc=False,
user=None,
cwd=None,
index_url=None,
extra_index_url=None):
'''
.. versionadded:: 2017.7.3
List all available versions of a pip package
pkg
The package to check
bin_env
Path to pip (or to a virtualenv). This can be used to specify the path
to the pip to use when more than one Python release is installed (e.g.
``/usr/bin/pip-2.7`` or ``/usr/bin/pip-2.6``. If a directory path is
specified, it is assumed to be a virtualenv.
include_alpha
Include alpha versions in the list
include_beta
Include beta versions in the list
include_rc
Include release candidates versions in the list
user
The user under which to run pip
cwd
Directory from which to run pip
index_url
Base URL of Python Package Index
.. versionadded:: 2019.2.0
extra_index_url
Additional URL of Python Package Index
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' pip.list_all_versions <package name>
'''
cmd = _get_pip_bin(bin_env)
cmd.extend(['install', '{0}==versions'.format(pkg)])
if index_url:
if not salt.utils.url.validate(index_url, VALID_PROTOS):
raise CommandExecutionError(
'\'{0}\' is not a valid URL'.format(index_url)
)
cmd.extend(['--index-url', index_url])
if extra_index_url:
if not salt.utils.url.validate(extra_index_url, VALID_PROTOS):
raise CommandExecutionError(
'\'{0}\' is not a valid URL'.format(extra_index_url)
)
cmd.extend(['--extra-index-url', extra_index_url])
cmd_kwargs = dict(cwd=cwd, runas=user, output_loglevel='quiet', redirect_stderr=True)
if bin_env and os.path.isdir(bin_env):
cmd_kwargs['env'] = {'VIRTUAL_ENV': bin_env}
result = __salt__['cmd.run_all'](cmd, **cmd_kwargs)
filtered = []
if not include_alpha:
filtered.append('a')
if not include_beta:
filtered.append('b')
if not include_rc:
filtered.append('rc')
if filtered:
excludes = re.compile(r'^((?!{0}).)*$'.format('|'.join(filtered)))
else:
excludes = re.compile(r'')
versions = []
for line in result['stdout'].splitlines():
match = re.search(r'\s*Could not find a version.* \(from versions: (.*)\)', line)
if match:
versions = [v for v in match.group(1).split(', ') if v and excludes.match(v)]
versions.sort(key=pkg_resources.parse_version)
break
if not versions:
return None
return versions
|
saltstack/salt
|
salt/modules/pip.py
|
install
|
python
|
def install(pkgs=None, # pylint: disable=R0912,R0913,R0914
requirements=None,
bin_env=None,
use_wheel=False,
no_use_wheel=False,
log=None,
proxy=None,
timeout=None,
editable=None,
find_links=None,
index_url=None,
extra_index_url=None,
no_index=False,
mirrors=None,
build=None,
target=None,
download=None,
download_cache=None,
source=None,
upgrade=False,
force_reinstall=False,
ignore_installed=False,
exists_action=None,
no_deps=False,
no_install=False,
no_download=False,
global_options=None,
install_options=None,
user=None,
cwd=None,
pre_releases=False,
cert=None,
allow_all_external=False,
allow_external=None,
allow_unverified=None,
process_dependency_links=False,
saltenv='base',
env_vars=None,
use_vt=False,
trusted_host=None,
no_cache_dir=False,
cache_dir=None,
no_binary=None,
extra_args=None,
**kwargs):
'''
Install packages with pip
Install packages individually or from a pip requirements file. Install
packages globally or to a virtualenv.
pkgs
Comma separated list of packages to install
requirements
Path to requirements
bin_env
Path to pip (or to a virtualenv). This can be used to specify the path
to the pip to use when more than one Python release is installed (e.g.
``/usr/bin/pip-2.7`` or ``/usr/bin/pip-2.6``. If a directory path is
specified, it is assumed to be a virtualenv.
.. note::
For Windows, if the pip module is being used to upgrade the pip
package, bin_env should be the path to the virtualenv or to the
python binary that should be used. The pip command is unable to
upgrade itself in Windows.
use_wheel
Prefer wheel archives (requires pip>=1.4)
no_use_wheel
Force to not use wheel archives (requires pip>=1.4,<10.0.0)
no_binary
Force to not use binary packages (requires pip >= 7.0.0)
Accepts either :all: to disable all binary packages, :none: to empty the set,
or one or more package names with commas between them
log
Log file where a complete (maximum verbosity) record will be kept
proxy
Specify a proxy in the form ``user:passwd@proxy.server:port``. Note
that the ``user:password@`` is optional and required only if you are
behind an authenticated proxy. If you provide
``user@proxy.server:port`` then you will be prompted for a password.
timeout
Set the socket timeout (default 15 seconds)
editable
install something editable (e.g.
``git+https://github.com/worldcompany/djangoembed.git#egg=djangoembed``)
find_links
URL to search for packages
index_url
Base URL of Python Package Index
extra_index_url
Extra URLs of package indexes to use in addition to ``index_url``
no_index
Ignore package index
mirrors
Specific mirror URL(s) to query (automatically adds --use-mirrors)
.. warning::
This option has been deprecated and removed in pip version 7.0.0.
Please use ``index_url`` and/or ``extra_index_url`` instead.
build
Unpack packages into ``build`` dir
target
Install packages into ``target`` dir
download
Download packages into ``download`` instead of installing them
download_cache | cache_dir
Cache downloaded packages in ``download_cache`` or ``cache_dir`` dir
source
Check out ``editable`` packages into ``source`` dir
upgrade
Upgrade all packages to the newest available version
force_reinstall
When upgrading, reinstall all packages even if they are already
up-to-date.
ignore_installed
Ignore the installed packages (reinstalling instead)
exists_action
Default action when a path already exists: (s)witch, (i)gnore, (w)ipe,
(b)ackup
no_deps
Ignore package dependencies
no_install
Download and unpack all packages, but don't actually install them
no_download
Don't download any packages, just install the ones already downloaded
(completes an install run with ``--no-install``)
install_options
Extra arguments to be supplied to the setup.py install command (e.g.
like ``--install-option='--install-scripts=/usr/local/bin'``). Use
multiple --install-option options to pass multiple options to setup.py
install. If you are using an option with a directory path, be sure to
use absolute path.
global_options
Extra global options to be supplied to the setup.py call before the
install command.
user
The user under which to run pip
cwd
Directory from which to run pip
pre_releases
Include pre-releases in the available versions
cert
Provide a path to an alternate CA bundle
allow_all_external
Allow the installation of all externally hosted files
allow_external
Allow the installation of externally hosted files (comma separated
list)
allow_unverified
Allow the installation of insecure and unverifiable files (comma
separated list)
process_dependency_links
Enable the processing of dependency links
env_vars
Set environment variables that some builds will depend on. For example,
a Python C-module may have a Makefile that needs INCLUDE_PATH set to
pick up a header file while compiling. This must be in the form of a
dictionary or a mapping.
Example:
.. code-block:: bash
salt '*' pip.install django_app env_vars="{'CUSTOM_PATH': '/opt/django_app'}"
trusted_host
Mark this host as trusted, even though it does not have valid or any
HTTPS.
use_vt
Use VT terminal emulation (see output while installing)
no_cache_dir
Disable the cache.
extra_args
pip keyword and positional arguments not yet implemented in salt
.. code-block:: yaml
salt '*' pip.install pandas extra_args="[{'--latest-pip-kwarg':'param'}, '--latest-pip-arg']"
.. warning::
If unsupported options are passed here that are not supported in a
minion's version of pip, a `No such option error` will be thrown.
Will be translated into the following pip command:
.. code-block:: bash
pip install pandas --latest-pip-kwarg param --latest-pip-arg
CLI Example:
.. code-block:: bash
salt '*' pip.install <package name>,<package2 name>
salt '*' pip.install requirements=/path/to/requirements.txt
salt '*' pip.install <package name> bin_env=/path/to/virtualenv
salt '*' pip.install <package name> bin_env=/path/to/pip_bin
Complicated CLI example::
salt '*' pip.install markdown,django \
editable=git+https://github.com/worldcompany/djangoembed.git#egg=djangoembed upgrade=True no_deps=True
'''
cmd = _get_pip_bin(bin_env)
cmd.append('install')
cleanup_requirements, error = _process_requirements(
requirements=requirements,
cmd=cmd,
cwd=cwd,
saltenv=saltenv,
user=user
)
if error:
return error
cur_version = version(bin_env)
if use_wheel:
min_version = '1.4'
max_version = '9.0.3'
too_low = salt.utils.versions.compare(ver1=cur_version, oper='<', ver2=min_version)
too_high = salt.utils.versions.compare(ver1=cur_version, oper='>', ver2=max_version)
if too_low or too_high:
logger.error(
'The --use-wheel option is only supported in pip between %s and '
'%s. The version of pip detected is %s. This option '
'will be ignored.', min_version, max_version, cur_version
)
else:
cmd.append('--use-wheel')
if no_use_wheel:
min_version = '1.4'
max_version = '9.0.3'
too_low = salt.utils.versions.compare(ver1=cur_version, oper='<', ver2=min_version)
too_high = salt.utils.versions.compare(ver1=cur_version, oper='>', ver2=max_version)
if too_low or too_high:
logger.error(
'The --no-use-wheel option is only supported in pip between %s and '
'%s. The version of pip detected is %s. This option '
'will be ignored.', min_version, max_version, cur_version
)
else:
cmd.append('--no-use-wheel')
if no_binary:
min_version = '7.0.0'
too_low = salt.utils.versions.compare(ver1=cur_version, oper='<', ver2=min_version)
if too_low:
logger.error(
'The --no-binary option is only supported in pip %s and '
'newer. The version of pip detected is %s. This option '
'will be ignored.', min_version, cur_version
)
else:
if isinstance(no_binary, list):
no_binary = ','.join(no_binary)
cmd.extend(['--no-binary', no_binary])
if log:
if os.path.isdir(log):
raise IOError(
'\'{0}\' is a directory. Use --log path_to_file'.format(log))
elif not os.access(log, os.W_OK):
raise IOError('\'{0}\' is not writeable'.format(log))
cmd.extend(['--log', log])
if proxy:
cmd.extend(['--proxy', proxy])
if timeout:
try:
if isinstance(timeout, float):
# Catch floating point input, exception will be caught in
# exception class below.
raise ValueError('Timeout cannot be a float')
int(timeout)
except ValueError:
raise ValueError(
'\'{0}\' is not a valid timeout, must be an integer'
.format(timeout)
)
cmd.extend(['--timeout', timeout])
if find_links:
if isinstance(find_links, six.string_types):
find_links = [l.strip() for l in find_links.split(',')]
for link in find_links:
if not (salt.utils.url.validate(link, VALID_PROTOS) or os.path.exists(link)):
raise CommandExecutionError(
'\'{0}\' is not a valid URL or path'.format(link)
)
cmd.extend(['--find-links', link])
if no_index and (index_url or extra_index_url):
raise CommandExecutionError(
'\'no_index\' and (\'index_url\' or \'extra_index_url\') are '
'mutually exclusive.'
)
if index_url:
if not salt.utils.url.validate(index_url, VALID_PROTOS):
raise CommandExecutionError(
'\'{0}\' is not a valid URL'.format(index_url)
)
cmd.extend(['--index-url', index_url])
if extra_index_url:
if not salt.utils.url.validate(extra_index_url, VALID_PROTOS):
raise CommandExecutionError(
'\'{0}\' is not a valid URL'.format(extra_index_url)
)
cmd.extend(['--extra-index-url', extra_index_url])
if no_index:
cmd.append('--no-index')
if mirrors:
# https://github.com/pypa/pip/pull/2641/files#diff-3ef137fb9ffdd400f117a565cd94c188L216
if salt.utils.versions.compare(ver1=cur_version, oper='>=', ver2='7.0.0'):
raise CommandExecutionError(
'pip >= 7.0.0 does not support mirror argument:'
' use index_url and/or extra_index_url instead'
)
if isinstance(mirrors, six.string_types):
mirrors = [m.strip() for m in mirrors.split(',')]
cmd.append('--use-mirrors')
for mirror in mirrors:
if not mirror.startswith('http://'):
raise CommandExecutionError(
'\'{0}\' is not a valid URL'.format(mirror)
)
cmd.extend(['--mirrors', mirror])
if build:
cmd.extend(['--build', build])
if target:
cmd.extend(['--target', target])
if download:
cmd.extend(['--download', download])
if download_cache or cache_dir:
cmd.extend(['--cache-dir' if salt.utils.versions.compare(
ver1=cur_version, oper='>=', ver2='6.0'
) else '--download-cache', download_cache or cache_dir])
if source:
cmd.extend(['--source', source])
if upgrade:
cmd.append('--upgrade')
if force_reinstall:
cmd.append('--force-reinstall')
if ignore_installed:
cmd.append('--ignore-installed')
if exists_action:
if exists_action.lower() not in ('s', 'i', 'w', 'b'):
raise CommandExecutionError(
'The exists_action pip option only supports the values '
's, i, w, and b. \'{0}\' is not valid.'.format(exists_action)
)
cmd.extend(['--exists-action', exists_action])
if no_deps:
cmd.append('--no-deps')
if no_install:
cmd.append('--no-install')
if no_download:
cmd.append('--no-download')
if no_cache_dir:
cmd.append('--no-cache-dir')
if pre_releases:
# Check the locally installed pip version
pip_version = cur_version
# From pip v1.4 the --pre flag is available
if salt.utils.versions.compare(ver1=pip_version, oper='>=', ver2='1.4'):
cmd.append('--pre')
if cert:
cmd.extend(['--cert', cert])
if global_options:
if isinstance(global_options, six.string_types):
global_options = [go.strip() for go in global_options.split(',')]
for opt in global_options:
cmd.extend(['--global-option', opt])
if install_options:
if isinstance(install_options, six.string_types):
install_options = [io.strip() for io in install_options.split(',')]
for opt in install_options:
cmd.extend(['--install-option', opt])
if pkgs:
if not isinstance(pkgs, list):
try:
pkgs = [p.strip() for p in pkgs.split(',')]
except AttributeError:
pkgs = [p.strip() for p in six.text_type(pkgs).split(',')]
pkgs = salt.utils.data.stringify(salt.utils.data.decode_list(pkgs))
# It's possible we replaced version-range commas with semicolons so
# they would survive the previous line (in the pip.installed state).
# Put the commas back in while making sure the names are contained in
# quotes, this allows for proper version spec passing salt>=0.17.0
cmd.extend([p.replace(';', ',') for p in pkgs])
elif not any([requirements, editable]):
# Starting with pip 10.0.0, if no packages are specified in the
# command, it returns a retcode 1. So instead of running the command,
# just return the output without running pip.
return {'retcode': 0, 'stdout': 'No packages to install.'}
if editable:
egg_match = re.compile(r'(?:#|#.*?&)egg=([^&]*)')
if isinstance(editable, six.string_types):
editable = [e.strip() for e in editable.split(',')]
for entry in editable:
# Is the editable local?
if not (entry == '.' or entry.startswith(('file://', '/'))):
match = egg_match.search(entry)
if not match or not match.group(1):
# Missing #egg=theEggName
raise CommandExecutionError(
'You must specify an egg for this editable'
)
cmd.extend(['--editable', entry])
if allow_all_external:
cmd.append('--allow-all-external')
if allow_external:
if isinstance(allow_external, six.string_types):
allow_external = [p.strip() for p in allow_external.split(',')]
for pkg in allow_external:
cmd.extend(['--allow-external', pkg])
if allow_unverified:
if isinstance(allow_unverified, six.string_types):
allow_unverified = \
[p.strip() for p in allow_unverified.split(',')]
for pkg in allow_unverified:
cmd.extend(['--allow-unverified', pkg])
if process_dependency_links:
cmd.append('--process-dependency-links')
if trusted_host:
cmd.extend(['--trusted-host', trusted_host])
if extra_args:
# These are arguments from the latest version of pip that
# have not yet been implemented in salt
for arg in extra_args:
# It is a keyword argument
if isinstance(arg, dict):
# There will only ever be one item in this dictionary
key, val = arg.popitem()
# Don't allow any recursion into keyword arg definitions
# Don't allow multiple definitions of a keyword
if isinstance(val, (dict, list)):
raise TypeError("Too many levels in: {}".format(key))
# This is a a normal one-to-one keyword argument
cmd.extend([key, val])
# It is a positional argument, append it to the list
else:
cmd.append(arg)
cmd_kwargs = dict(saltenv=saltenv, use_vt=use_vt, runas=user)
if kwargs:
cmd_kwargs.update(kwargs)
if env_vars:
cmd_kwargs.setdefault('env', {}).update(_format_env_vars(env_vars))
try:
if cwd:
cmd_kwargs['cwd'] = cwd
if bin_env and os.path.isdir(bin_env):
cmd_kwargs.setdefault('env', {})['VIRTUAL_ENV'] = bin_env
logger.debug(
'TRY BLOCK: end of pip.install -- cmd: %s, cmd_kwargs: %s',
cmd, cmd_kwargs
)
return __salt__['cmd.run_all'](cmd, python_shell=False, **cmd_kwargs)
finally:
_clear_context(bin_env)
for tempdir in [cr for cr in cleanup_requirements if cr is not None]:
if os.path.isdir(tempdir):
shutil.rmtree(tempdir)
|
Install packages with pip
Install packages individually or from a pip requirements file. Install
packages globally or to a virtualenv.
pkgs
Comma separated list of packages to install
requirements
Path to requirements
bin_env
Path to pip (or to a virtualenv). This can be used to specify the path
to the pip to use when more than one Python release is installed (e.g.
``/usr/bin/pip-2.7`` or ``/usr/bin/pip-2.6``. If a directory path is
specified, it is assumed to be a virtualenv.
.. note::
For Windows, if the pip module is being used to upgrade the pip
package, bin_env should be the path to the virtualenv or to the
python binary that should be used. The pip command is unable to
upgrade itself in Windows.
use_wheel
Prefer wheel archives (requires pip>=1.4)
no_use_wheel
Force to not use wheel archives (requires pip>=1.4,<10.0.0)
no_binary
Force to not use binary packages (requires pip >= 7.0.0)
Accepts either :all: to disable all binary packages, :none: to empty the set,
or one or more package names with commas between them
log
Log file where a complete (maximum verbosity) record will be kept
proxy
Specify a proxy in the form ``user:passwd@proxy.server:port``. Note
that the ``user:password@`` is optional and required only if you are
behind an authenticated proxy. If you provide
``user@proxy.server:port`` then you will be prompted for a password.
timeout
Set the socket timeout (default 15 seconds)
editable
install something editable (e.g.
``git+https://github.com/worldcompany/djangoembed.git#egg=djangoembed``)
find_links
URL to search for packages
index_url
Base URL of Python Package Index
extra_index_url
Extra URLs of package indexes to use in addition to ``index_url``
no_index
Ignore package index
mirrors
Specific mirror URL(s) to query (automatically adds --use-mirrors)
.. warning::
This option has been deprecated and removed in pip version 7.0.0.
Please use ``index_url`` and/or ``extra_index_url`` instead.
build
Unpack packages into ``build`` dir
target
Install packages into ``target`` dir
download
Download packages into ``download`` instead of installing them
download_cache | cache_dir
Cache downloaded packages in ``download_cache`` or ``cache_dir`` dir
source
Check out ``editable`` packages into ``source`` dir
upgrade
Upgrade all packages to the newest available version
force_reinstall
When upgrading, reinstall all packages even if they are already
up-to-date.
ignore_installed
Ignore the installed packages (reinstalling instead)
exists_action
Default action when a path already exists: (s)witch, (i)gnore, (w)ipe,
(b)ackup
no_deps
Ignore package dependencies
no_install
Download and unpack all packages, but don't actually install them
no_download
Don't download any packages, just install the ones already downloaded
(completes an install run with ``--no-install``)
install_options
Extra arguments to be supplied to the setup.py install command (e.g.
like ``--install-option='--install-scripts=/usr/local/bin'``). Use
multiple --install-option options to pass multiple options to setup.py
install. If you are using an option with a directory path, be sure to
use absolute path.
global_options
Extra global options to be supplied to the setup.py call before the
install command.
user
The user under which to run pip
cwd
Directory from which to run pip
pre_releases
Include pre-releases in the available versions
cert
Provide a path to an alternate CA bundle
allow_all_external
Allow the installation of all externally hosted files
allow_external
Allow the installation of externally hosted files (comma separated
list)
allow_unverified
Allow the installation of insecure and unverifiable files (comma
separated list)
process_dependency_links
Enable the processing of dependency links
env_vars
Set environment variables that some builds will depend on. For example,
a Python C-module may have a Makefile that needs INCLUDE_PATH set to
pick up a header file while compiling. This must be in the form of a
dictionary or a mapping.
Example:
.. code-block:: bash
salt '*' pip.install django_app env_vars="{'CUSTOM_PATH': '/opt/django_app'}"
trusted_host
Mark this host as trusted, even though it does not have valid or any
HTTPS.
use_vt
Use VT terminal emulation (see output while installing)
no_cache_dir
Disable the cache.
extra_args
pip keyword and positional arguments not yet implemented in salt
.. code-block:: yaml
salt '*' pip.install pandas extra_args="[{'--latest-pip-kwarg':'param'}, '--latest-pip-arg']"
.. warning::
If unsupported options are passed here that are not supported in a
minion's version of pip, a `No such option error` will be thrown.
Will be translated into the following pip command:
.. code-block:: bash
pip install pandas --latest-pip-kwarg param --latest-pip-arg
CLI Example:
.. code-block:: bash
salt '*' pip.install <package name>,<package2 name>
salt '*' pip.install requirements=/path/to/requirements.txt
salt '*' pip.install <package name> bin_env=/path/to/virtualenv
salt '*' pip.install <package name> bin_env=/path/to/pip_bin
Complicated CLI example::
salt '*' pip.install markdown,django \
editable=git+https://github.com/worldcompany/djangoembed.git#egg=djangoembed upgrade=True no_deps=True
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/pip.py#L402-L961
|
[
"def version(bin_env=None):\n '''\n .. versionadded:: 0.17.0\n\n Returns the version of pip. Use ``bin_env`` to specify the path to a\n virtualenv and get the version of pip in that virtualenv.\n\n If unable to detect the pip version, returns ``None``.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' pip.version\n '''\n contextkey = 'pip.version'\n if bin_env is not None:\n contextkey = '{0}.{1}'.format(contextkey, bin_env)\n\n if contextkey in __context__:\n return __context__[contextkey]\n\n cmd = _get_pip_bin(bin_env)[:]\n cmd.append('--version')\n\n ret = __salt__['cmd.run_all'](cmd, python_shell=False)\n if ret['retcode']:\n raise CommandNotFoundError('Could not find a `pip` binary')\n\n try:\n pip_version = re.match(r'^pip (\\S+)', ret['stdout']).group(1)\n except AttributeError:\n pip_version = None\n\n __context__[contextkey] = pip_version\n return pip_version\n",
"def validate(url, protos):\n '''\n Return true if the passed URL scheme is in the list of accepted protos\n '''\n if urlparse(url).scheme in protos:\n return True\n return False\n",
"def compare(ver1='', oper='==', ver2='', cmp_func=None, ignore_epoch=False):\n '''\n Compares two version numbers. Accepts a custom function to perform the\n cmp-style version comparison, otherwise uses version_cmp().\n '''\n cmp_map = {'<': (-1,), '<=': (-1, 0), '==': (0,),\n '>=': (0, 1), '>': (1,)}\n if oper not in ('!=',) and oper not in cmp_map:\n log.error('Invalid operator \\'%s\\' for version comparison', oper)\n return False\n\n if cmp_func is None:\n cmp_func = version_cmp\n\n cmp_result = cmp_func(ver1, ver2, ignore_epoch=ignore_epoch)\n if cmp_result is None:\n return False\n\n # Check if integer/long\n if not isinstance(cmp_result, numbers.Integral):\n log.error('The version comparison function did not return an '\n 'integer/long.')\n return False\n\n if oper == '!=':\n return cmp_result not in cmp_map['==']\n else:\n # Gracefully handle cmp_result not in (-1, 0, 1).\n if cmp_result < -1:\n cmp_result = -1\n elif cmp_result > 1:\n cmp_result = 1\n\n return cmp_result in cmp_map[oper]\n",
"def decode_list(data, encoding=None, errors='strict', keep=False,\n normalize=False, preserve_dict_class=False,\n preserve_tuples=False, to_str=False):\n '''\n Decode all string values to Unicode. Optionally use to_str=True to ensure\n strings are str types and not unicode on Python 2.\n '''\n _decode_func = salt.utils.stringutils.to_unicode \\\n if not to_str \\\n else salt.utils.stringutils.to_str\n rv = []\n for item in data:\n if isinstance(item, list):\n item = decode_list(item, encoding, errors, keep, normalize,\n preserve_dict_class, preserve_tuples, to_str)\n elif isinstance(item, tuple):\n item = decode_tuple(item, encoding, errors, keep, normalize,\n preserve_dict_class, to_str) \\\n if preserve_tuples \\\n else decode_list(item, encoding, errors, keep, normalize,\n preserve_dict_class, preserve_tuples, to_str)\n elif isinstance(item, Mapping):\n item = decode_dict(item, encoding, errors, keep, normalize,\n preserve_dict_class, preserve_tuples, to_str)\n else:\n try:\n item = _decode_func(item, encoding, errors, normalize)\n except TypeError:\n # to_unicode raises a TypeError when input is not a\n # string/bytestring/bytearray. This is expected and simply\n # means we are going to leave the value as-is.\n pass\n except UnicodeDecodeError:\n if not keep:\n raise\n\n rv.append(item)\n return rv\n",
"def stringify(data):\n '''\n Given an iterable, returns its items as a list, with any non-string items\n converted to unicode strings.\n '''\n ret = []\n for item in data:\n if six.PY2 and isinstance(item, str):\n item = salt.utils.stringutils.to_unicode(item)\n elif not isinstance(item, six.string_types):\n item = six.text_type(item)\n ret.append(item)\n return ret\n",
"def _clear_context(bin_env=None):\n '''\n Remove the cached pip version\n '''\n contextkey = 'pip.version'\n if bin_env is not None:\n contextkey = '{0}.{1}'.format(contextkey, bin_env)\n __context__.pop(contextkey, None)\n",
"def _get_pip_bin(bin_env):\n '''\n Locate the pip binary, either from `bin_env` as a virtualenv, as the\n executable itself, or from searching conventional filesystem locations\n '''\n if not bin_env:\n logger.debug('pip: Using pip from currently-running Python')\n return [os.path.normpath(sys.executable), '-m', 'pip']\n\n python_bin = 'python.exe' if salt.utils.platform.is_windows() else 'python'\n\n def _search_paths(*basedirs):\n ret = []\n for path in basedirs:\n ret.extend([\n os.path.join(path, python_bin),\n os.path.join(path, 'bin', python_bin),\n os.path.join(path, 'Scripts', python_bin)\n ])\n return ret\n\n # try to get python bin from virtualenv (i.e. bin_env)\n if os.path.isdir(bin_env):\n for bin_path in _search_paths(bin_env):\n if os.path.isfile(bin_path):\n if os.access(bin_path, os.X_OK):\n logger.debug('pip: Found python binary: %s', bin_path)\n return [os.path.normpath(bin_path), '-m', 'pip']\n else:\n logger.debug(\n 'pip: Found python binary by name but it is not '\n 'executable: %s', bin_path\n )\n raise CommandNotFoundError(\n 'Could not find a pip binary in virtualenv {0}'.format(bin_env)\n )\n\n # bin_env is the python or pip binary\n elif os.access(bin_env, os.X_OK):\n if os.path.isfile(bin_env):\n # If the python binary was passed, return it\n if 'python' in os.path.basename(bin_env):\n return [os.path.normpath(bin_env), '-m', 'pip']\n # We have been passed a pip binary, use the pip binary.\n return [os.path.normpath(bin_env)]\n\n raise CommandExecutionError(\n 'Could not find a pip binary within {0}'.format(bin_env)\n )\n else:\n raise CommandNotFoundError(\n 'Access denied to {0}, could not find a pip binary'.format(bin_env)\n )\n",
"def _process_requirements(requirements, cmd, cwd, saltenv, user):\n '''\n Process the requirements argument\n '''\n cleanup_requirements = []\n\n if requirements is not None:\n if isinstance(requirements, six.string_types):\n requirements = [r.strip() for r in requirements.split(',')]\n elif not isinstance(requirements, list):\n raise TypeError('requirements must be a string or list')\n\n treq = None\n\n for requirement in requirements:\n logger.debug('TREQ IS: %s', treq)\n if requirement.startswith('salt://'):\n cached_requirements = _get_cached_requirements(\n requirement, saltenv\n )\n if not cached_requirements:\n ret = {'result': False,\n 'comment': 'pip requirements file \\'{0}\\' not found'\n .format(requirement)}\n return None, ret\n requirement = cached_requirements\n\n if user:\n # Need to make a temporary copy since the user will, most\n # likely, not have the right permissions to read the file\n\n if not treq:\n treq = tempfile.mkdtemp()\n\n __salt__['file.chown'](treq, user, None)\n # In Windows, just being owner of a file isn't enough. You also\n # need permissions\n if salt.utils.platform.is_windows():\n __utils__['dacl.set_permissions'](\n obj_name=treq,\n principal=user,\n permissions='read_execute')\n\n current_directory = None\n\n if not current_directory:\n current_directory = os.path.abspath(os.curdir)\n\n logger.info('_process_requirements from directory, '\n '%s -- requirement: %s', cwd, requirement)\n\n if cwd is None:\n r = requirement\n c = cwd\n\n requirement_abspath = os.path.abspath(requirement)\n cwd = os.path.dirname(requirement_abspath)\n requirement = os.path.basename(requirement)\n\n logger.debug('\\n\\tcwd: %s -> %s\\n\\trequirement: %s -> %s\\n',\n c, cwd, r, requirement\n )\n\n os.chdir(cwd)\n\n reqs = _resolve_requirements_chain(requirement)\n\n os.chdir(current_directory)\n\n logger.info('request files: %s', reqs)\n\n for req_file in reqs:\n if not os.path.isabs(req_file):\n req_file = os.path.join(cwd, req_file)\n\n logger.debug('TREQ N CWD: %s -- %s -- for %s', treq, cwd, req_file)\n target_path = os.path.join(treq, os.path.basename(req_file))\n\n logger.debug('S: %s', req_file)\n logger.debug('T: %s', target_path)\n\n target_base = os.path.dirname(target_path)\n\n if not os.path.exists(target_base):\n os.makedirs(target_base, mode=0o755)\n __salt__['file.chown'](target_base, user, None)\n\n if not os.path.exists(target_path):\n logger.debug(\n 'Copying %s to %s', req_file, target_path\n )\n __salt__['file.copy'](req_file, target_path)\n\n logger.debug(\n 'Changing ownership of requirements file \\'%s\\' to '\n 'user \\'%s\\'', target_path, user\n )\n\n __salt__['file.chown'](target_path, user, None)\n\n req_args = os.path.join(treq, requirement) if treq else requirement\n cmd.extend(['--requirement', req_args])\n\n cleanup_requirements.append(treq)\n\n logger.debug('CLEANUP_REQUIREMENTS: %s', cleanup_requirements)\n return cleanup_requirements, None\n",
"def _format_env_vars(env_vars):\n ret = {}\n if env_vars:\n if isinstance(env_vars, dict):\n for key, val in six.iteritems(env_vars):\n if not isinstance(key, six.string_types):\n key = str(key) # future lint: disable=blacklisted-function\n if not isinstance(val, six.string_types):\n val = str(val) # future lint: disable=blacklisted-function\n ret[key] = val\n else:\n raise CommandExecutionError(\n 'env_vars {0} is not a dictionary'.format(env_vars))\n return ret\n"
] |
# -*- coding: utf-8 -*-
r'''
Install Python packages with pip to either the system or a virtualenv
Windows Support
===============
.. versionadded:: 2014.7.4
Salt now uses a portable python. As a result the entire pip module is now
functional on the salt installation itself. You can pip install dependencies
for your custom modules. You can even upgrade salt itself using pip. For this
to work properly, you must specify the Current Working Directory (``cwd``) and
the Pip Binary (``bin_env``) salt should use. The variable ``pip_bin`` can be
either a virtualenv path or the path to the pip binary itself.
For example, the following command will list all software installed using pip
to your current salt environment:
.. code-block:: bat
salt <minion> pip.list cwd='C:\salt\bin\Scripts' bin_env='C:\salt\bin\Scripts\pip.exe'
Specifying the ``cwd`` and ``bin_env`` options ensures you're modifying the
salt environment. If these are omitted, it will default to the local
installation of python. If python is not installed locally it will fail saying
it couldn't find pip.
State File Support
------------------
This functionality works in states as well. If you need to pip install colorama
with a state, for example, the following will work:
.. code-block:: yaml
install_colorama:
pip.installed:
- name: colorama
- cwd: 'C:\salt\bin\scripts'
- bin_env: 'C:\salt\bin\scripts\pip.exe'
- upgrade: True
Upgrading Salt using Pip
------------------------
You can now update salt using pip to any version from the 2014.7 branch
forward. Previous version require recompiling some of the dependencies which is
painful in windows.
To do this you just use pip with git to update to the version you want and then
restart the service. Here is a sample state file that upgrades salt to the head
of the 2015.5 branch:
.. code-block:: yaml
install_salt:
pip.installed:
- cwd: 'C:\salt\bin\scripts'
- bin_env: 'C:\salt\bin\scripts\pip.exe'
- editable: git+https://github.com/saltstack/salt@2015.5#egg=salt
- upgrade: True
restart_service:
service.running:
- name: salt-minion
- enable: True
- watch:
- pip: install_salt
.. note::
If you're having problems, you might try doubling the back slashes. For
example, cwd: 'C:\\salt\\bin\\scripts'. Sometimes python thinks the single
back slash is an escape character.
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import logging
import os
try:
import pkg_resources
except ImportError:
pkg_resources = None
import re
import shutil
import sys
import tempfile
# Import Salt libs
import salt.utils.data
import salt.utils.files
import salt.utils.json
import salt.utils.locales
import salt.utils.platform
import salt.utils.stringutils
import salt.utils.url
import salt.utils.versions
from salt.ext import six
from salt.exceptions import CommandExecutionError, CommandNotFoundError
# This needs to be named logger so we don't shadow it in pip.install
logger = logging.getLogger(__name__) # pylint: disable=C0103
# Don't shadow built-in's.
__func_alias__ = {
'list_': 'list'
}
VALID_PROTOS = ['http', 'https', 'ftp', 'file']
rex_pip_chain_read = re.compile(r'-r\s(.*)\n?', re.MULTILINE)
def __virtual__():
'''
There is no way to verify that pip is installed without inspecting the
entire filesystem. If it's not installed in a conventional location, the
user is required to provide the location of pip each time it is used.
'''
if pkg_resources is None:
ret = False, 'Package dependency "pkg_resource" is missing'
else:
ret = 'pip'
return ret
def _clear_context(bin_env=None):
'''
Remove the cached pip version
'''
contextkey = 'pip.version'
if bin_env is not None:
contextkey = '{0}.{1}'.format(contextkey, bin_env)
__context__.pop(contextkey, None)
def _get_pip_bin(bin_env):
'''
Locate the pip binary, either from `bin_env` as a virtualenv, as the
executable itself, or from searching conventional filesystem locations
'''
if not bin_env:
logger.debug('pip: Using pip from currently-running Python')
return [os.path.normpath(sys.executable), '-m', 'pip']
python_bin = 'python.exe' if salt.utils.platform.is_windows() else 'python'
def _search_paths(*basedirs):
ret = []
for path in basedirs:
ret.extend([
os.path.join(path, python_bin),
os.path.join(path, 'bin', python_bin),
os.path.join(path, 'Scripts', python_bin)
])
return ret
# try to get python bin from virtualenv (i.e. bin_env)
if os.path.isdir(bin_env):
for bin_path in _search_paths(bin_env):
if os.path.isfile(bin_path):
if os.access(bin_path, os.X_OK):
logger.debug('pip: Found python binary: %s', bin_path)
return [os.path.normpath(bin_path), '-m', 'pip']
else:
logger.debug(
'pip: Found python binary by name but it is not '
'executable: %s', bin_path
)
raise CommandNotFoundError(
'Could not find a pip binary in virtualenv {0}'.format(bin_env)
)
# bin_env is the python or pip binary
elif os.access(bin_env, os.X_OK):
if os.path.isfile(bin_env):
# If the python binary was passed, return it
if 'python' in os.path.basename(bin_env):
return [os.path.normpath(bin_env), '-m', 'pip']
# We have been passed a pip binary, use the pip binary.
return [os.path.normpath(bin_env)]
raise CommandExecutionError(
'Could not find a pip binary within {0}'.format(bin_env)
)
else:
raise CommandNotFoundError(
'Access denied to {0}, could not find a pip binary'.format(bin_env)
)
def _get_cached_requirements(requirements, saltenv):
'''
Get the location of a cached requirements file; caching if necessary.
'''
req_file, senv = salt.utils.url.parse(requirements)
if senv:
saltenv = senv
if req_file not in __salt__['cp.list_master'](saltenv):
# Requirements file does not exist in the given saltenv.
return False
cached_requirements = __salt__['cp.is_cached'](
requirements, saltenv
)
if not cached_requirements:
# It's not cached, let's cache it.
cached_requirements = __salt__['cp.cache_file'](
requirements, saltenv
)
# Check if the master version has changed.
if __salt__['cp.hash_file'](requirements, saltenv) != \
__salt__['cp.hash_file'](cached_requirements, saltenv):
cached_requirements = __salt__['cp.cache_file'](
requirements, saltenv
)
return cached_requirements
def _get_env_activate(bin_env):
'''
Return the path to the activate binary
'''
if not bin_env:
raise CommandNotFoundError('Could not find a `activate` binary')
if os.path.isdir(bin_env):
if salt.utils.platform.is_windows():
activate_bin = os.path.join(bin_env, 'Scripts', 'activate.bat')
else:
activate_bin = os.path.join(bin_env, 'bin', 'activate')
if os.path.isfile(activate_bin):
return activate_bin
raise CommandNotFoundError('Could not find a `activate` binary')
def _find_req(link):
logger.info('_find_req -- link = %s', link)
with salt.utils.files.fopen(link) as fh_link:
child_links = rex_pip_chain_read.findall(
salt.utils.stringutils.to_unicode(fh_link.read())
)
base_path = os.path.dirname(link)
child_links = [os.path.join(base_path, d) for d in child_links]
return child_links
def _resolve_requirements_chain(requirements):
'''
Return an array of requirements file paths that can be used to complete
the no_chown==False && user != None conundrum
'''
chain = []
if isinstance(requirements, six.string_types):
requirements = [requirements]
for req_file in requirements:
chain.append(req_file)
chain.extend(_resolve_requirements_chain(_find_req(req_file)))
return chain
def _process_requirements(requirements, cmd, cwd, saltenv, user):
'''
Process the requirements argument
'''
cleanup_requirements = []
if requirements is not None:
if isinstance(requirements, six.string_types):
requirements = [r.strip() for r in requirements.split(',')]
elif not isinstance(requirements, list):
raise TypeError('requirements must be a string or list')
treq = None
for requirement in requirements:
logger.debug('TREQ IS: %s', treq)
if requirement.startswith('salt://'):
cached_requirements = _get_cached_requirements(
requirement, saltenv
)
if not cached_requirements:
ret = {'result': False,
'comment': 'pip requirements file \'{0}\' not found'
.format(requirement)}
return None, ret
requirement = cached_requirements
if user:
# Need to make a temporary copy since the user will, most
# likely, not have the right permissions to read the file
if not treq:
treq = tempfile.mkdtemp()
__salt__['file.chown'](treq, user, None)
# In Windows, just being owner of a file isn't enough. You also
# need permissions
if salt.utils.platform.is_windows():
__utils__['dacl.set_permissions'](
obj_name=treq,
principal=user,
permissions='read_execute')
current_directory = None
if not current_directory:
current_directory = os.path.abspath(os.curdir)
logger.info('_process_requirements from directory, '
'%s -- requirement: %s', cwd, requirement)
if cwd is None:
r = requirement
c = cwd
requirement_abspath = os.path.abspath(requirement)
cwd = os.path.dirname(requirement_abspath)
requirement = os.path.basename(requirement)
logger.debug('\n\tcwd: %s -> %s\n\trequirement: %s -> %s\n',
c, cwd, r, requirement
)
os.chdir(cwd)
reqs = _resolve_requirements_chain(requirement)
os.chdir(current_directory)
logger.info('request files: %s', reqs)
for req_file in reqs:
if not os.path.isabs(req_file):
req_file = os.path.join(cwd, req_file)
logger.debug('TREQ N CWD: %s -- %s -- for %s', treq, cwd, req_file)
target_path = os.path.join(treq, os.path.basename(req_file))
logger.debug('S: %s', req_file)
logger.debug('T: %s', target_path)
target_base = os.path.dirname(target_path)
if not os.path.exists(target_base):
os.makedirs(target_base, mode=0o755)
__salt__['file.chown'](target_base, user, None)
if not os.path.exists(target_path):
logger.debug(
'Copying %s to %s', req_file, target_path
)
__salt__['file.copy'](req_file, target_path)
logger.debug(
'Changing ownership of requirements file \'%s\' to '
'user \'%s\'', target_path, user
)
__salt__['file.chown'](target_path, user, None)
req_args = os.path.join(treq, requirement) if treq else requirement
cmd.extend(['--requirement', req_args])
cleanup_requirements.append(treq)
logger.debug('CLEANUP_REQUIREMENTS: %s', cleanup_requirements)
return cleanup_requirements, None
def _format_env_vars(env_vars):
ret = {}
if env_vars:
if isinstance(env_vars, dict):
for key, val in six.iteritems(env_vars):
if not isinstance(key, six.string_types):
key = str(key) # future lint: disable=blacklisted-function
if not isinstance(val, six.string_types):
val = str(val) # future lint: disable=blacklisted-function
ret[key] = val
else:
raise CommandExecutionError(
'env_vars {0} is not a dictionary'.format(env_vars))
return ret
def uninstall(pkgs=None,
requirements=None,
bin_env=None,
log=None,
proxy=None,
timeout=None,
user=None,
cwd=None,
saltenv='base',
use_vt=False):
'''
Uninstall packages individually or from a pip requirements file
pkgs
comma separated list of packages to install
requirements
Path to requirements file
bin_env
Path to pip (or to a virtualenv). This can be used to specify the path
to the pip to use when more than one Python release is installed (e.g.
``/usr/bin/pip-2.7`` or ``/usr/bin/pip-2.6``. If a directory path is
specified, it is assumed to be a virtualenv.
log
Log file where a complete (maximum verbosity) record will be kept
proxy
Specify a proxy in the format ``user:passwd@proxy.server:port``. Note
that the ``user:password@`` is optional and required only if you are
behind an authenticated proxy. If you provide
``user@proxy.server:port`` then you will be prompted for a password.
timeout
Set the socket timeout (default 15 seconds)
user
The user under which to run pip
cwd
Directory from which to run pip
use_vt
Use VT terminal emulation (see output while installing)
CLI Example:
.. code-block:: bash
salt '*' pip.uninstall <package name>,<package2 name>
salt '*' pip.uninstall requirements=/path/to/requirements.txt
salt '*' pip.uninstall <package name> bin_env=/path/to/virtualenv
salt '*' pip.uninstall <package name> bin_env=/path/to/pip_bin
'''
cmd = _get_pip_bin(bin_env)
cmd.extend(['uninstall', '-y'])
cleanup_requirements, error = _process_requirements(
requirements=requirements, cmd=cmd, saltenv=saltenv, user=user,
cwd=cwd
)
if error:
return error
if log:
try:
# TODO make this check if writeable
os.path.exists(log)
except IOError:
raise IOError('\'{0}\' is not writeable'.format(log))
cmd.extend(['--log', log])
if proxy:
cmd.extend(['--proxy', proxy])
if timeout:
try:
if isinstance(timeout, float):
# Catch floating point input, exception will be caught in
# exception class below.
raise ValueError('Timeout cannot be a float')
int(timeout)
except ValueError:
raise ValueError(
'\'{0}\' is not a valid timeout, must be an integer'
.format(timeout)
)
cmd.extend(['--timeout', timeout])
if pkgs:
if isinstance(pkgs, six.string_types):
pkgs = [p.strip() for p in pkgs.split(',')]
if requirements:
for requirement in requirements:
with salt.utils.files.fopen(requirement) as rq_:
for req in rq_:
req = salt.utils.stringutils.to_unicode(req)
try:
req_pkg, _ = req.split('==')
if req_pkg in pkgs:
pkgs.remove(req_pkg)
except ValueError:
pass
cmd.extend(pkgs)
cmd_kwargs = dict(python_shell=False, runas=user,
cwd=cwd, saltenv=saltenv, use_vt=use_vt)
if bin_env and os.path.isdir(bin_env):
cmd_kwargs['env'] = {'VIRTUAL_ENV': bin_env}
try:
return __salt__['cmd.run_all'](cmd, **cmd_kwargs)
finally:
_clear_context(bin_env)
for requirement in cleanup_requirements:
if requirement:
try:
os.remove(requirement)
except OSError:
pass
def freeze(bin_env=None,
user=None,
cwd=None,
use_vt=False,
env_vars=None,
**kwargs):
'''
Return a list of installed packages either globally or in the specified
virtualenv
bin_env
Path to pip (or to a virtualenv). This can be used to specify the path
to the pip to use when more than one Python release is installed (e.g.
``/usr/bin/pip-2.7`` or ``/usr/bin/pip-2.6``. If a directory path is
specified, it is assumed to be a virtualenv.
user
The user under which to run pip
cwd
Directory from which to run pip
.. note::
If the version of pip available is older than 8.0.3, the list will not
include the packages ``pip``, ``wheel``, ``setuptools``, or
``distribute`` even if they are installed.
CLI Example:
.. code-block:: bash
salt '*' pip.freeze bin_env=/home/code/path/to/virtualenv
'''
cmd = _get_pip_bin(bin_env)
cmd.append('freeze')
# Include pip, setuptools, distribute, wheel
min_version = '8.0.3'
cur_version = version(bin_env)
if salt.utils.versions.compare(ver1=cur_version, oper='<', ver2=min_version):
logger.warning(
'The version of pip installed is %s, which is older than %s. '
'The packages pip, wheel, setuptools, and distribute will not be '
'included in the output of pip.freeze', cur_version, min_version
)
else:
cmd.append('--all')
cmd_kwargs = dict(runas=user, cwd=cwd, use_vt=use_vt, python_shell=False)
if kwargs:
cmd_kwargs.update(**kwargs)
if bin_env and os.path.isdir(bin_env):
cmd_kwargs['env'] = {'VIRTUAL_ENV': bin_env}
if env_vars:
cmd_kwargs.setdefault('env', {}).update(_format_env_vars(env_vars))
result = __salt__['cmd.run_all'](cmd, **cmd_kwargs)
if result['retcode']:
raise CommandExecutionError(result['stderr'], info=result)
return result['stdout'].splitlines()
def list_(prefix=None,
bin_env=None,
user=None,
cwd=None,
env_vars=None,
**kwargs):
'''
Filter list of installed apps from ``freeze`` and check to see if
``prefix`` exists in the list of packages installed.
.. note::
If the version of pip available is older than 8.0.3, the packages
``wheel``, ``setuptools``, and ``distribute`` will not be reported by
this function even if they are installed. Unlike :py:func:`pip.freeze
<salt.modules.pip.freeze>`, this function always reports the version of
pip which is installed.
CLI Example:
.. code-block:: bash
salt '*' pip.list salt
'''
packages = {}
if prefix is None or 'pip'.startswith(prefix):
packages['pip'] = version(bin_env)
for line in freeze(bin_env=bin_env,
user=user,
cwd=cwd,
env_vars=env_vars,
**kwargs):
if line.startswith('-f') or line.startswith('#'):
# ignore -f line as it contains --find-links directory
# ignore comment lines
continue
elif line.startswith('-e hg+not trust'):
# ignore hg + not trust problem
continue
elif line.startswith('-e'):
line = line.split('-e ')[1]
if '#egg=' in line:
version_, name = line.split('#egg=')
else:
if len(line.split('===')) >= 2:
name = line.split('===')[0]
version_ = line.split('===')[1]
elif len(line.split('==')) >= 2:
name = line.split('==')[0]
version_ = line.split('==')[1]
elif len(line.split('===')) >= 2:
name = line.split('===')[0]
version_ = line.split('===')[1]
elif len(line.split('==')) >= 2:
name = line.split('==')[0]
version_ = line.split('==')[1]
else:
logger.error('Can\'t parse line \'%s\'', line)
continue
if prefix:
if name.lower().startswith(prefix.lower()):
packages[name] = version_
else:
packages[name] = version_
return packages
def version(bin_env=None):
'''
.. versionadded:: 0.17.0
Returns the version of pip. Use ``bin_env`` to specify the path to a
virtualenv and get the version of pip in that virtualenv.
If unable to detect the pip version, returns ``None``.
CLI Example:
.. code-block:: bash
salt '*' pip.version
'''
contextkey = 'pip.version'
if bin_env is not None:
contextkey = '{0}.{1}'.format(contextkey, bin_env)
if contextkey in __context__:
return __context__[contextkey]
cmd = _get_pip_bin(bin_env)[:]
cmd.append('--version')
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
if ret['retcode']:
raise CommandNotFoundError('Could not find a `pip` binary')
try:
pip_version = re.match(r'^pip (\S+)', ret['stdout']).group(1)
except AttributeError:
pip_version = None
__context__[contextkey] = pip_version
return pip_version
def list_upgrades(bin_env=None,
user=None,
cwd=None):
'''
Check whether or not an upgrade is available for all packages
CLI Example:
.. code-block:: bash
salt '*' pip.list_upgrades
'''
cmd = _get_pip_bin(bin_env)
cmd.extend(['list', '--outdated'])
pip_version = version(bin_env)
# Pip started supporting the ability to output json starting with 9.0.0
min_version = '9.0'
if salt.utils.versions.compare(ver1=pip_version,
oper='>=',
ver2=min_version):
cmd.append('--format=json')
cmd_kwargs = dict(cwd=cwd, runas=user)
if bin_env and os.path.isdir(bin_env):
cmd_kwargs['env'] = {'VIRTUAL_ENV': bin_env}
result = __salt__['cmd.run_all'](cmd, **cmd_kwargs)
if result['retcode']:
raise CommandExecutionError(result['stderr'], info=result)
packages = {}
# Pip started supporting the ability to output json starting with 9.0.0
# Older versions will have to parse stdout
if salt.utils.versions.compare(ver1=pip_version, oper='<', ver2='9.0.0'):
# Pip versions < 8.0.0 had a different output format
# Sample data:
# pip (Current: 7.1.2 Latest: 10.0.1 [wheel])
# psutil (Current: 5.2.2 Latest: 5.4.5 [wheel])
# pyasn1 (Current: 0.2.3 Latest: 0.4.2 [wheel])
# pycparser (Current: 2.17 Latest: 2.18 [sdist])
if salt.utils.versions.compare(ver1=pip_version, oper='<', ver2='8.0.0'):
logger.debug('pip module: Old output format')
pat = re.compile(r'(\S*)\s+\(.*Latest:\s+(.*)\)')
# New output format for version 8.0.0+
# Sample data:
# pip (8.0.0) - Latest: 10.0.1 [wheel]
# psutil (5.2.2) - Latest: 5.4.5 [wheel]
# pyasn1 (0.2.3) - Latest: 0.4.2 [wheel]
# pycparser (2.17) - Latest: 2.18 [sdist]
else:
logger.debug('pip module: New output format')
pat = re.compile(r'(\S*)\s+\(.*\)\s+-\s+Latest:\s+(.*)')
for line in result['stdout'].splitlines():
match = pat.search(line)
if match:
name, version_ = match.groups()
else:
logger.error('Can\'t parse line \'%s\'', line)
continue
packages[name] = version_
else:
logger.debug('pip module: JSON output format')
try:
pkgs = salt.utils.json.loads(result['stdout'], strict=False)
except ValueError:
raise CommandExecutionError('Invalid JSON', info=result)
for pkg in pkgs:
packages[pkg['name']] = '{0} [{1}]'.format(pkg['latest_version'],
pkg['latest_filetype'])
return packages
def is_installed(pkgname=None,
bin_env=None,
user=None,
cwd=None):
'''
.. versionadded:: 2018.3.0
Filter list of installed apps from ``freeze`` and return True or False if
``pkgname`` exists in the list of packages installed.
.. note::
If the version of pip available is older than 8.0.3, the packages
wheel, setuptools, and distribute will not be reported by this function
even if they are installed. Unlike :py:func:`pip.freeze
<salt.modules.pip.freeze>`, this function always reports the version of
pip which is installed.
CLI Example:
.. code-block:: bash
salt '*' pip.is_installed salt
'''
for line in freeze(bin_env=bin_env, user=user, cwd=cwd):
if line.startswith('-f') or line.startswith('#'):
# ignore -f line as it contains --find-links directory
# ignore comment lines
continue
elif line.startswith('-e hg+not trust'):
# ignore hg + not trust problem
continue
elif line.startswith('-e'):
line = line.split('-e ')[1]
version_, name = line.split('#egg=')
elif len(line.split('===')) >= 2:
name = line.split('===')[0]
version_ = line.split('===')[1]
elif len(line.split('==')) >= 2:
name = line.split('==')[0]
version_ = line.split('==')[1]
else:
logger.error('Can\'t parse line \'%s\'', line)
continue
if pkgname:
if pkgname == name.lower():
return True
return False
def upgrade_available(pkg,
bin_env=None,
user=None,
cwd=None):
'''
.. versionadded:: 2015.5.0
Check whether or not an upgrade is available for a given package
CLI Example:
.. code-block:: bash
salt '*' pip.upgrade_available <package name>
'''
return pkg in list_upgrades(bin_env=bin_env, user=user, cwd=cwd)
def upgrade(bin_env=None,
user=None,
cwd=None,
use_vt=False):
'''
.. versionadded:: 2015.5.0
Upgrades outdated pip packages.
.. note::
On Windows you can't update salt from pip using salt, so salt will be
skipped
Returns a dict containing the changes.
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
CLI Example:
.. code-block:: bash
salt '*' pip.upgrade
'''
ret = {'changes': {},
'result': True,
'comment': '',
}
cmd = _get_pip_bin(bin_env)
cmd.extend(['install', '-U'])
old = list_(bin_env=bin_env, user=user, cwd=cwd)
cmd_kwargs = dict(cwd=cwd, use_vt=use_vt)
if bin_env and os.path.isdir(bin_env):
cmd_kwargs['env'] = {'VIRTUAL_ENV': bin_env}
errors = False
for pkg in list_upgrades(bin_env=bin_env, user=user, cwd=cwd):
if pkg == 'salt':
if salt.utils.platform.is_windows():
continue
result = __salt__['cmd.run_all'](cmd + [pkg], **cmd_kwargs)
if result['retcode'] != 0:
errors = True
if 'stderr' in result:
ret['comment'] += result['stderr']
if errors:
ret['result'] = False
_clear_context(bin_env)
new = list_(bin_env=bin_env, user=user, cwd=cwd)
ret['changes'] = salt.utils.data.compare_dicts(old, new)
return ret
def list_all_versions(pkg,
bin_env=None,
include_alpha=False,
include_beta=False,
include_rc=False,
user=None,
cwd=None,
index_url=None,
extra_index_url=None):
'''
.. versionadded:: 2017.7.3
List all available versions of a pip package
pkg
The package to check
bin_env
Path to pip (or to a virtualenv). This can be used to specify the path
to the pip to use when more than one Python release is installed (e.g.
``/usr/bin/pip-2.7`` or ``/usr/bin/pip-2.6``. If a directory path is
specified, it is assumed to be a virtualenv.
include_alpha
Include alpha versions in the list
include_beta
Include beta versions in the list
include_rc
Include release candidates versions in the list
user
The user under which to run pip
cwd
Directory from which to run pip
index_url
Base URL of Python Package Index
.. versionadded:: 2019.2.0
extra_index_url
Additional URL of Python Package Index
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' pip.list_all_versions <package name>
'''
cmd = _get_pip_bin(bin_env)
cmd.extend(['install', '{0}==versions'.format(pkg)])
if index_url:
if not salt.utils.url.validate(index_url, VALID_PROTOS):
raise CommandExecutionError(
'\'{0}\' is not a valid URL'.format(index_url)
)
cmd.extend(['--index-url', index_url])
if extra_index_url:
if not salt.utils.url.validate(extra_index_url, VALID_PROTOS):
raise CommandExecutionError(
'\'{0}\' is not a valid URL'.format(extra_index_url)
)
cmd.extend(['--extra-index-url', extra_index_url])
cmd_kwargs = dict(cwd=cwd, runas=user, output_loglevel='quiet', redirect_stderr=True)
if bin_env and os.path.isdir(bin_env):
cmd_kwargs['env'] = {'VIRTUAL_ENV': bin_env}
result = __salt__['cmd.run_all'](cmd, **cmd_kwargs)
filtered = []
if not include_alpha:
filtered.append('a')
if not include_beta:
filtered.append('b')
if not include_rc:
filtered.append('rc')
if filtered:
excludes = re.compile(r'^((?!{0}).)*$'.format('|'.join(filtered)))
else:
excludes = re.compile(r'')
versions = []
for line in result['stdout'].splitlines():
match = re.search(r'\s*Could not find a version.* \(from versions: (.*)\)', line)
if match:
versions = [v for v in match.group(1).split(', ') if v and excludes.match(v)]
versions.sort(key=pkg_resources.parse_version)
break
if not versions:
return None
return versions
|
saltstack/salt
|
salt/modules/pip.py
|
uninstall
|
python
|
def uninstall(pkgs=None,
requirements=None,
bin_env=None,
log=None,
proxy=None,
timeout=None,
user=None,
cwd=None,
saltenv='base',
use_vt=False):
'''
Uninstall packages individually or from a pip requirements file
pkgs
comma separated list of packages to install
requirements
Path to requirements file
bin_env
Path to pip (or to a virtualenv). This can be used to specify the path
to the pip to use when more than one Python release is installed (e.g.
``/usr/bin/pip-2.7`` or ``/usr/bin/pip-2.6``. If a directory path is
specified, it is assumed to be a virtualenv.
log
Log file where a complete (maximum verbosity) record will be kept
proxy
Specify a proxy in the format ``user:passwd@proxy.server:port``. Note
that the ``user:password@`` is optional and required only if you are
behind an authenticated proxy. If you provide
``user@proxy.server:port`` then you will be prompted for a password.
timeout
Set the socket timeout (default 15 seconds)
user
The user under which to run pip
cwd
Directory from which to run pip
use_vt
Use VT terminal emulation (see output while installing)
CLI Example:
.. code-block:: bash
salt '*' pip.uninstall <package name>,<package2 name>
salt '*' pip.uninstall requirements=/path/to/requirements.txt
salt '*' pip.uninstall <package name> bin_env=/path/to/virtualenv
salt '*' pip.uninstall <package name> bin_env=/path/to/pip_bin
'''
cmd = _get_pip_bin(bin_env)
cmd.extend(['uninstall', '-y'])
cleanup_requirements, error = _process_requirements(
requirements=requirements, cmd=cmd, saltenv=saltenv, user=user,
cwd=cwd
)
if error:
return error
if log:
try:
# TODO make this check if writeable
os.path.exists(log)
except IOError:
raise IOError('\'{0}\' is not writeable'.format(log))
cmd.extend(['--log', log])
if proxy:
cmd.extend(['--proxy', proxy])
if timeout:
try:
if isinstance(timeout, float):
# Catch floating point input, exception will be caught in
# exception class below.
raise ValueError('Timeout cannot be a float')
int(timeout)
except ValueError:
raise ValueError(
'\'{0}\' is not a valid timeout, must be an integer'
.format(timeout)
)
cmd.extend(['--timeout', timeout])
if pkgs:
if isinstance(pkgs, six.string_types):
pkgs = [p.strip() for p in pkgs.split(',')]
if requirements:
for requirement in requirements:
with salt.utils.files.fopen(requirement) as rq_:
for req in rq_:
req = salt.utils.stringutils.to_unicode(req)
try:
req_pkg, _ = req.split('==')
if req_pkg in pkgs:
pkgs.remove(req_pkg)
except ValueError:
pass
cmd.extend(pkgs)
cmd_kwargs = dict(python_shell=False, runas=user,
cwd=cwd, saltenv=saltenv, use_vt=use_vt)
if bin_env and os.path.isdir(bin_env):
cmd_kwargs['env'] = {'VIRTUAL_ENV': bin_env}
try:
return __salt__['cmd.run_all'](cmd, **cmd_kwargs)
finally:
_clear_context(bin_env)
for requirement in cleanup_requirements:
if requirement:
try:
os.remove(requirement)
except OSError:
pass
|
Uninstall packages individually or from a pip requirements file
pkgs
comma separated list of packages to install
requirements
Path to requirements file
bin_env
Path to pip (or to a virtualenv). This can be used to specify the path
to the pip to use when more than one Python release is installed (e.g.
``/usr/bin/pip-2.7`` or ``/usr/bin/pip-2.6``. If a directory path is
specified, it is assumed to be a virtualenv.
log
Log file where a complete (maximum verbosity) record will be kept
proxy
Specify a proxy in the format ``user:passwd@proxy.server:port``. Note
that the ``user:password@`` is optional and required only if you are
behind an authenticated proxy. If you provide
``user@proxy.server:port`` then you will be prompted for a password.
timeout
Set the socket timeout (default 15 seconds)
user
The user under which to run pip
cwd
Directory from which to run pip
use_vt
Use VT terminal emulation (see output while installing)
CLI Example:
.. code-block:: bash
salt '*' pip.uninstall <package name>,<package2 name>
salt '*' pip.uninstall requirements=/path/to/requirements.txt
salt '*' pip.uninstall <package name> bin_env=/path/to/virtualenv
salt '*' pip.uninstall <package name> bin_env=/path/to/pip_bin
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/pip.py#L964-L1086
|
[
"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",
"def _clear_context(bin_env=None):\n '''\n Remove the cached pip version\n '''\n contextkey = 'pip.version'\n if bin_env is not None:\n contextkey = '{0}.{1}'.format(contextkey, bin_env)\n __context__.pop(contextkey, None)\n",
"def _get_pip_bin(bin_env):\n '''\n Locate the pip binary, either from `bin_env` as a virtualenv, as the\n executable itself, or from searching conventional filesystem locations\n '''\n if not bin_env:\n logger.debug('pip: Using pip from currently-running Python')\n return [os.path.normpath(sys.executable), '-m', 'pip']\n\n python_bin = 'python.exe' if salt.utils.platform.is_windows() else 'python'\n\n def _search_paths(*basedirs):\n ret = []\n for path in basedirs:\n ret.extend([\n os.path.join(path, python_bin),\n os.path.join(path, 'bin', python_bin),\n os.path.join(path, 'Scripts', python_bin)\n ])\n return ret\n\n # try to get python bin from virtualenv (i.e. bin_env)\n if os.path.isdir(bin_env):\n for bin_path in _search_paths(bin_env):\n if os.path.isfile(bin_path):\n if os.access(bin_path, os.X_OK):\n logger.debug('pip: Found python binary: %s', bin_path)\n return [os.path.normpath(bin_path), '-m', 'pip']\n else:\n logger.debug(\n 'pip: Found python binary by name but it is not '\n 'executable: %s', bin_path\n )\n raise CommandNotFoundError(\n 'Could not find a pip binary in virtualenv {0}'.format(bin_env)\n )\n\n # bin_env is the python or pip binary\n elif os.access(bin_env, os.X_OK):\n if os.path.isfile(bin_env):\n # If the python binary was passed, return it\n if 'python' in os.path.basename(bin_env):\n return [os.path.normpath(bin_env), '-m', 'pip']\n # We have been passed a pip binary, use the pip binary.\n return [os.path.normpath(bin_env)]\n\n raise CommandExecutionError(\n 'Could not find a pip binary within {0}'.format(bin_env)\n )\n else:\n raise CommandNotFoundError(\n 'Access denied to {0}, could not find a pip binary'.format(bin_env)\n )\n",
"def _process_requirements(requirements, cmd, cwd, saltenv, user):\n '''\n Process the requirements argument\n '''\n cleanup_requirements = []\n\n if requirements is not None:\n if isinstance(requirements, six.string_types):\n requirements = [r.strip() for r in requirements.split(',')]\n elif not isinstance(requirements, list):\n raise TypeError('requirements must be a string or list')\n\n treq = None\n\n for requirement in requirements:\n logger.debug('TREQ IS: %s', treq)\n if requirement.startswith('salt://'):\n cached_requirements = _get_cached_requirements(\n requirement, saltenv\n )\n if not cached_requirements:\n ret = {'result': False,\n 'comment': 'pip requirements file \\'{0}\\' not found'\n .format(requirement)}\n return None, ret\n requirement = cached_requirements\n\n if user:\n # Need to make a temporary copy since the user will, most\n # likely, not have the right permissions to read the file\n\n if not treq:\n treq = tempfile.mkdtemp()\n\n __salt__['file.chown'](treq, user, None)\n # In Windows, just being owner of a file isn't enough. You also\n # need permissions\n if salt.utils.platform.is_windows():\n __utils__['dacl.set_permissions'](\n obj_name=treq,\n principal=user,\n permissions='read_execute')\n\n current_directory = None\n\n if not current_directory:\n current_directory = os.path.abspath(os.curdir)\n\n logger.info('_process_requirements from directory, '\n '%s -- requirement: %s', cwd, requirement)\n\n if cwd is None:\n r = requirement\n c = cwd\n\n requirement_abspath = os.path.abspath(requirement)\n cwd = os.path.dirname(requirement_abspath)\n requirement = os.path.basename(requirement)\n\n logger.debug('\\n\\tcwd: %s -> %s\\n\\trequirement: %s -> %s\\n',\n c, cwd, r, requirement\n )\n\n os.chdir(cwd)\n\n reqs = _resolve_requirements_chain(requirement)\n\n os.chdir(current_directory)\n\n logger.info('request files: %s', reqs)\n\n for req_file in reqs:\n if not os.path.isabs(req_file):\n req_file = os.path.join(cwd, req_file)\n\n logger.debug('TREQ N CWD: %s -- %s -- for %s', treq, cwd, req_file)\n target_path = os.path.join(treq, os.path.basename(req_file))\n\n logger.debug('S: %s', req_file)\n logger.debug('T: %s', target_path)\n\n target_base = os.path.dirname(target_path)\n\n if not os.path.exists(target_base):\n os.makedirs(target_base, mode=0o755)\n __salt__['file.chown'](target_base, user, None)\n\n if not os.path.exists(target_path):\n logger.debug(\n 'Copying %s to %s', req_file, target_path\n )\n __salt__['file.copy'](req_file, target_path)\n\n logger.debug(\n 'Changing ownership of requirements file \\'%s\\' to '\n 'user \\'%s\\'', target_path, user\n )\n\n __salt__['file.chown'](target_path, user, None)\n\n req_args = os.path.join(treq, requirement) if treq else requirement\n cmd.extend(['--requirement', req_args])\n\n cleanup_requirements.append(treq)\n\n logger.debug('CLEANUP_REQUIREMENTS: %s', cleanup_requirements)\n return cleanup_requirements, None\n"
] |
# -*- coding: utf-8 -*-
r'''
Install Python packages with pip to either the system or a virtualenv
Windows Support
===============
.. versionadded:: 2014.7.4
Salt now uses a portable python. As a result the entire pip module is now
functional on the salt installation itself. You can pip install dependencies
for your custom modules. You can even upgrade salt itself using pip. For this
to work properly, you must specify the Current Working Directory (``cwd``) and
the Pip Binary (``bin_env``) salt should use. The variable ``pip_bin`` can be
either a virtualenv path or the path to the pip binary itself.
For example, the following command will list all software installed using pip
to your current salt environment:
.. code-block:: bat
salt <minion> pip.list cwd='C:\salt\bin\Scripts' bin_env='C:\salt\bin\Scripts\pip.exe'
Specifying the ``cwd`` and ``bin_env`` options ensures you're modifying the
salt environment. If these are omitted, it will default to the local
installation of python. If python is not installed locally it will fail saying
it couldn't find pip.
State File Support
------------------
This functionality works in states as well. If you need to pip install colorama
with a state, for example, the following will work:
.. code-block:: yaml
install_colorama:
pip.installed:
- name: colorama
- cwd: 'C:\salt\bin\scripts'
- bin_env: 'C:\salt\bin\scripts\pip.exe'
- upgrade: True
Upgrading Salt using Pip
------------------------
You can now update salt using pip to any version from the 2014.7 branch
forward. Previous version require recompiling some of the dependencies which is
painful in windows.
To do this you just use pip with git to update to the version you want and then
restart the service. Here is a sample state file that upgrades salt to the head
of the 2015.5 branch:
.. code-block:: yaml
install_salt:
pip.installed:
- cwd: 'C:\salt\bin\scripts'
- bin_env: 'C:\salt\bin\scripts\pip.exe'
- editable: git+https://github.com/saltstack/salt@2015.5#egg=salt
- upgrade: True
restart_service:
service.running:
- name: salt-minion
- enable: True
- watch:
- pip: install_salt
.. note::
If you're having problems, you might try doubling the back slashes. For
example, cwd: 'C:\\salt\\bin\\scripts'. Sometimes python thinks the single
back slash is an escape character.
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import logging
import os
try:
import pkg_resources
except ImportError:
pkg_resources = None
import re
import shutil
import sys
import tempfile
# Import Salt libs
import salt.utils.data
import salt.utils.files
import salt.utils.json
import salt.utils.locales
import salt.utils.platform
import salt.utils.stringutils
import salt.utils.url
import salt.utils.versions
from salt.ext import six
from salt.exceptions import CommandExecutionError, CommandNotFoundError
# This needs to be named logger so we don't shadow it in pip.install
logger = logging.getLogger(__name__) # pylint: disable=C0103
# Don't shadow built-in's.
__func_alias__ = {
'list_': 'list'
}
VALID_PROTOS = ['http', 'https', 'ftp', 'file']
rex_pip_chain_read = re.compile(r'-r\s(.*)\n?', re.MULTILINE)
def __virtual__():
'''
There is no way to verify that pip is installed without inspecting the
entire filesystem. If it's not installed in a conventional location, the
user is required to provide the location of pip each time it is used.
'''
if pkg_resources is None:
ret = False, 'Package dependency "pkg_resource" is missing'
else:
ret = 'pip'
return ret
def _clear_context(bin_env=None):
'''
Remove the cached pip version
'''
contextkey = 'pip.version'
if bin_env is not None:
contextkey = '{0}.{1}'.format(contextkey, bin_env)
__context__.pop(contextkey, None)
def _get_pip_bin(bin_env):
'''
Locate the pip binary, either from `bin_env` as a virtualenv, as the
executable itself, or from searching conventional filesystem locations
'''
if not bin_env:
logger.debug('pip: Using pip from currently-running Python')
return [os.path.normpath(sys.executable), '-m', 'pip']
python_bin = 'python.exe' if salt.utils.platform.is_windows() else 'python'
def _search_paths(*basedirs):
ret = []
for path in basedirs:
ret.extend([
os.path.join(path, python_bin),
os.path.join(path, 'bin', python_bin),
os.path.join(path, 'Scripts', python_bin)
])
return ret
# try to get python bin from virtualenv (i.e. bin_env)
if os.path.isdir(bin_env):
for bin_path in _search_paths(bin_env):
if os.path.isfile(bin_path):
if os.access(bin_path, os.X_OK):
logger.debug('pip: Found python binary: %s', bin_path)
return [os.path.normpath(bin_path), '-m', 'pip']
else:
logger.debug(
'pip: Found python binary by name but it is not '
'executable: %s', bin_path
)
raise CommandNotFoundError(
'Could not find a pip binary in virtualenv {0}'.format(bin_env)
)
# bin_env is the python or pip binary
elif os.access(bin_env, os.X_OK):
if os.path.isfile(bin_env):
# If the python binary was passed, return it
if 'python' in os.path.basename(bin_env):
return [os.path.normpath(bin_env), '-m', 'pip']
# We have been passed a pip binary, use the pip binary.
return [os.path.normpath(bin_env)]
raise CommandExecutionError(
'Could not find a pip binary within {0}'.format(bin_env)
)
else:
raise CommandNotFoundError(
'Access denied to {0}, could not find a pip binary'.format(bin_env)
)
def _get_cached_requirements(requirements, saltenv):
'''
Get the location of a cached requirements file; caching if necessary.
'''
req_file, senv = salt.utils.url.parse(requirements)
if senv:
saltenv = senv
if req_file not in __salt__['cp.list_master'](saltenv):
# Requirements file does not exist in the given saltenv.
return False
cached_requirements = __salt__['cp.is_cached'](
requirements, saltenv
)
if not cached_requirements:
# It's not cached, let's cache it.
cached_requirements = __salt__['cp.cache_file'](
requirements, saltenv
)
# Check if the master version has changed.
if __salt__['cp.hash_file'](requirements, saltenv) != \
__salt__['cp.hash_file'](cached_requirements, saltenv):
cached_requirements = __salt__['cp.cache_file'](
requirements, saltenv
)
return cached_requirements
def _get_env_activate(bin_env):
'''
Return the path to the activate binary
'''
if not bin_env:
raise CommandNotFoundError('Could not find a `activate` binary')
if os.path.isdir(bin_env):
if salt.utils.platform.is_windows():
activate_bin = os.path.join(bin_env, 'Scripts', 'activate.bat')
else:
activate_bin = os.path.join(bin_env, 'bin', 'activate')
if os.path.isfile(activate_bin):
return activate_bin
raise CommandNotFoundError('Could not find a `activate` binary')
def _find_req(link):
logger.info('_find_req -- link = %s', link)
with salt.utils.files.fopen(link) as fh_link:
child_links = rex_pip_chain_read.findall(
salt.utils.stringutils.to_unicode(fh_link.read())
)
base_path = os.path.dirname(link)
child_links = [os.path.join(base_path, d) for d in child_links]
return child_links
def _resolve_requirements_chain(requirements):
'''
Return an array of requirements file paths that can be used to complete
the no_chown==False && user != None conundrum
'''
chain = []
if isinstance(requirements, six.string_types):
requirements = [requirements]
for req_file in requirements:
chain.append(req_file)
chain.extend(_resolve_requirements_chain(_find_req(req_file)))
return chain
def _process_requirements(requirements, cmd, cwd, saltenv, user):
'''
Process the requirements argument
'''
cleanup_requirements = []
if requirements is not None:
if isinstance(requirements, six.string_types):
requirements = [r.strip() for r in requirements.split(',')]
elif not isinstance(requirements, list):
raise TypeError('requirements must be a string or list')
treq = None
for requirement in requirements:
logger.debug('TREQ IS: %s', treq)
if requirement.startswith('salt://'):
cached_requirements = _get_cached_requirements(
requirement, saltenv
)
if not cached_requirements:
ret = {'result': False,
'comment': 'pip requirements file \'{0}\' not found'
.format(requirement)}
return None, ret
requirement = cached_requirements
if user:
# Need to make a temporary copy since the user will, most
# likely, not have the right permissions to read the file
if not treq:
treq = tempfile.mkdtemp()
__salt__['file.chown'](treq, user, None)
# In Windows, just being owner of a file isn't enough. You also
# need permissions
if salt.utils.platform.is_windows():
__utils__['dacl.set_permissions'](
obj_name=treq,
principal=user,
permissions='read_execute')
current_directory = None
if not current_directory:
current_directory = os.path.abspath(os.curdir)
logger.info('_process_requirements from directory, '
'%s -- requirement: %s', cwd, requirement)
if cwd is None:
r = requirement
c = cwd
requirement_abspath = os.path.abspath(requirement)
cwd = os.path.dirname(requirement_abspath)
requirement = os.path.basename(requirement)
logger.debug('\n\tcwd: %s -> %s\n\trequirement: %s -> %s\n',
c, cwd, r, requirement
)
os.chdir(cwd)
reqs = _resolve_requirements_chain(requirement)
os.chdir(current_directory)
logger.info('request files: %s', reqs)
for req_file in reqs:
if not os.path.isabs(req_file):
req_file = os.path.join(cwd, req_file)
logger.debug('TREQ N CWD: %s -- %s -- for %s', treq, cwd, req_file)
target_path = os.path.join(treq, os.path.basename(req_file))
logger.debug('S: %s', req_file)
logger.debug('T: %s', target_path)
target_base = os.path.dirname(target_path)
if not os.path.exists(target_base):
os.makedirs(target_base, mode=0o755)
__salt__['file.chown'](target_base, user, None)
if not os.path.exists(target_path):
logger.debug(
'Copying %s to %s', req_file, target_path
)
__salt__['file.copy'](req_file, target_path)
logger.debug(
'Changing ownership of requirements file \'%s\' to '
'user \'%s\'', target_path, user
)
__salt__['file.chown'](target_path, user, None)
req_args = os.path.join(treq, requirement) if treq else requirement
cmd.extend(['--requirement', req_args])
cleanup_requirements.append(treq)
logger.debug('CLEANUP_REQUIREMENTS: %s', cleanup_requirements)
return cleanup_requirements, None
def _format_env_vars(env_vars):
ret = {}
if env_vars:
if isinstance(env_vars, dict):
for key, val in six.iteritems(env_vars):
if not isinstance(key, six.string_types):
key = str(key) # future lint: disable=blacklisted-function
if not isinstance(val, six.string_types):
val = str(val) # future lint: disable=blacklisted-function
ret[key] = val
else:
raise CommandExecutionError(
'env_vars {0} is not a dictionary'.format(env_vars))
return ret
def install(pkgs=None, # pylint: disable=R0912,R0913,R0914
requirements=None,
bin_env=None,
use_wheel=False,
no_use_wheel=False,
log=None,
proxy=None,
timeout=None,
editable=None,
find_links=None,
index_url=None,
extra_index_url=None,
no_index=False,
mirrors=None,
build=None,
target=None,
download=None,
download_cache=None,
source=None,
upgrade=False,
force_reinstall=False,
ignore_installed=False,
exists_action=None,
no_deps=False,
no_install=False,
no_download=False,
global_options=None,
install_options=None,
user=None,
cwd=None,
pre_releases=False,
cert=None,
allow_all_external=False,
allow_external=None,
allow_unverified=None,
process_dependency_links=False,
saltenv='base',
env_vars=None,
use_vt=False,
trusted_host=None,
no_cache_dir=False,
cache_dir=None,
no_binary=None,
extra_args=None,
**kwargs):
'''
Install packages with pip
Install packages individually or from a pip requirements file. Install
packages globally or to a virtualenv.
pkgs
Comma separated list of packages to install
requirements
Path to requirements
bin_env
Path to pip (or to a virtualenv). This can be used to specify the path
to the pip to use when more than one Python release is installed (e.g.
``/usr/bin/pip-2.7`` or ``/usr/bin/pip-2.6``. If a directory path is
specified, it is assumed to be a virtualenv.
.. note::
For Windows, if the pip module is being used to upgrade the pip
package, bin_env should be the path to the virtualenv or to the
python binary that should be used. The pip command is unable to
upgrade itself in Windows.
use_wheel
Prefer wheel archives (requires pip>=1.4)
no_use_wheel
Force to not use wheel archives (requires pip>=1.4,<10.0.0)
no_binary
Force to not use binary packages (requires pip >= 7.0.0)
Accepts either :all: to disable all binary packages, :none: to empty the set,
or one or more package names with commas between them
log
Log file where a complete (maximum verbosity) record will be kept
proxy
Specify a proxy in the form ``user:passwd@proxy.server:port``. Note
that the ``user:password@`` is optional and required only if you are
behind an authenticated proxy. If you provide
``user@proxy.server:port`` then you will be prompted for a password.
timeout
Set the socket timeout (default 15 seconds)
editable
install something editable (e.g.
``git+https://github.com/worldcompany/djangoembed.git#egg=djangoembed``)
find_links
URL to search for packages
index_url
Base URL of Python Package Index
extra_index_url
Extra URLs of package indexes to use in addition to ``index_url``
no_index
Ignore package index
mirrors
Specific mirror URL(s) to query (automatically adds --use-mirrors)
.. warning::
This option has been deprecated and removed in pip version 7.0.0.
Please use ``index_url`` and/or ``extra_index_url`` instead.
build
Unpack packages into ``build`` dir
target
Install packages into ``target`` dir
download
Download packages into ``download`` instead of installing them
download_cache | cache_dir
Cache downloaded packages in ``download_cache`` or ``cache_dir`` dir
source
Check out ``editable`` packages into ``source`` dir
upgrade
Upgrade all packages to the newest available version
force_reinstall
When upgrading, reinstall all packages even if they are already
up-to-date.
ignore_installed
Ignore the installed packages (reinstalling instead)
exists_action
Default action when a path already exists: (s)witch, (i)gnore, (w)ipe,
(b)ackup
no_deps
Ignore package dependencies
no_install
Download and unpack all packages, but don't actually install them
no_download
Don't download any packages, just install the ones already downloaded
(completes an install run with ``--no-install``)
install_options
Extra arguments to be supplied to the setup.py install command (e.g.
like ``--install-option='--install-scripts=/usr/local/bin'``). Use
multiple --install-option options to pass multiple options to setup.py
install. If you are using an option with a directory path, be sure to
use absolute path.
global_options
Extra global options to be supplied to the setup.py call before the
install command.
user
The user under which to run pip
cwd
Directory from which to run pip
pre_releases
Include pre-releases in the available versions
cert
Provide a path to an alternate CA bundle
allow_all_external
Allow the installation of all externally hosted files
allow_external
Allow the installation of externally hosted files (comma separated
list)
allow_unverified
Allow the installation of insecure and unverifiable files (comma
separated list)
process_dependency_links
Enable the processing of dependency links
env_vars
Set environment variables that some builds will depend on. For example,
a Python C-module may have a Makefile that needs INCLUDE_PATH set to
pick up a header file while compiling. This must be in the form of a
dictionary or a mapping.
Example:
.. code-block:: bash
salt '*' pip.install django_app env_vars="{'CUSTOM_PATH': '/opt/django_app'}"
trusted_host
Mark this host as trusted, even though it does not have valid or any
HTTPS.
use_vt
Use VT terminal emulation (see output while installing)
no_cache_dir
Disable the cache.
extra_args
pip keyword and positional arguments not yet implemented in salt
.. code-block:: yaml
salt '*' pip.install pandas extra_args="[{'--latest-pip-kwarg':'param'}, '--latest-pip-arg']"
.. warning::
If unsupported options are passed here that are not supported in a
minion's version of pip, a `No such option error` will be thrown.
Will be translated into the following pip command:
.. code-block:: bash
pip install pandas --latest-pip-kwarg param --latest-pip-arg
CLI Example:
.. code-block:: bash
salt '*' pip.install <package name>,<package2 name>
salt '*' pip.install requirements=/path/to/requirements.txt
salt '*' pip.install <package name> bin_env=/path/to/virtualenv
salt '*' pip.install <package name> bin_env=/path/to/pip_bin
Complicated CLI example::
salt '*' pip.install markdown,django \
editable=git+https://github.com/worldcompany/djangoembed.git#egg=djangoembed upgrade=True no_deps=True
'''
cmd = _get_pip_bin(bin_env)
cmd.append('install')
cleanup_requirements, error = _process_requirements(
requirements=requirements,
cmd=cmd,
cwd=cwd,
saltenv=saltenv,
user=user
)
if error:
return error
cur_version = version(bin_env)
if use_wheel:
min_version = '1.4'
max_version = '9.0.3'
too_low = salt.utils.versions.compare(ver1=cur_version, oper='<', ver2=min_version)
too_high = salt.utils.versions.compare(ver1=cur_version, oper='>', ver2=max_version)
if too_low or too_high:
logger.error(
'The --use-wheel option is only supported in pip between %s and '
'%s. The version of pip detected is %s. This option '
'will be ignored.', min_version, max_version, cur_version
)
else:
cmd.append('--use-wheel')
if no_use_wheel:
min_version = '1.4'
max_version = '9.0.3'
too_low = salt.utils.versions.compare(ver1=cur_version, oper='<', ver2=min_version)
too_high = salt.utils.versions.compare(ver1=cur_version, oper='>', ver2=max_version)
if too_low or too_high:
logger.error(
'The --no-use-wheel option is only supported in pip between %s and '
'%s. The version of pip detected is %s. This option '
'will be ignored.', min_version, max_version, cur_version
)
else:
cmd.append('--no-use-wheel')
if no_binary:
min_version = '7.0.0'
too_low = salt.utils.versions.compare(ver1=cur_version, oper='<', ver2=min_version)
if too_low:
logger.error(
'The --no-binary option is only supported in pip %s and '
'newer. The version of pip detected is %s. This option '
'will be ignored.', min_version, cur_version
)
else:
if isinstance(no_binary, list):
no_binary = ','.join(no_binary)
cmd.extend(['--no-binary', no_binary])
if log:
if os.path.isdir(log):
raise IOError(
'\'{0}\' is a directory. Use --log path_to_file'.format(log))
elif not os.access(log, os.W_OK):
raise IOError('\'{0}\' is not writeable'.format(log))
cmd.extend(['--log', log])
if proxy:
cmd.extend(['--proxy', proxy])
if timeout:
try:
if isinstance(timeout, float):
# Catch floating point input, exception will be caught in
# exception class below.
raise ValueError('Timeout cannot be a float')
int(timeout)
except ValueError:
raise ValueError(
'\'{0}\' is not a valid timeout, must be an integer'
.format(timeout)
)
cmd.extend(['--timeout', timeout])
if find_links:
if isinstance(find_links, six.string_types):
find_links = [l.strip() for l in find_links.split(',')]
for link in find_links:
if not (salt.utils.url.validate(link, VALID_PROTOS) or os.path.exists(link)):
raise CommandExecutionError(
'\'{0}\' is not a valid URL or path'.format(link)
)
cmd.extend(['--find-links', link])
if no_index and (index_url or extra_index_url):
raise CommandExecutionError(
'\'no_index\' and (\'index_url\' or \'extra_index_url\') are '
'mutually exclusive.'
)
if index_url:
if not salt.utils.url.validate(index_url, VALID_PROTOS):
raise CommandExecutionError(
'\'{0}\' is not a valid URL'.format(index_url)
)
cmd.extend(['--index-url', index_url])
if extra_index_url:
if not salt.utils.url.validate(extra_index_url, VALID_PROTOS):
raise CommandExecutionError(
'\'{0}\' is not a valid URL'.format(extra_index_url)
)
cmd.extend(['--extra-index-url', extra_index_url])
if no_index:
cmd.append('--no-index')
if mirrors:
# https://github.com/pypa/pip/pull/2641/files#diff-3ef137fb9ffdd400f117a565cd94c188L216
if salt.utils.versions.compare(ver1=cur_version, oper='>=', ver2='7.0.0'):
raise CommandExecutionError(
'pip >= 7.0.0 does not support mirror argument:'
' use index_url and/or extra_index_url instead'
)
if isinstance(mirrors, six.string_types):
mirrors = [m.strip() for m in mirrors.split(',')]
cmd.append('--use-mirrors')
for mirror in mirrors:
if not mirror.startswith('http://'):
raise CommandExecutionError(
'\'{0}\' is not a valid URL'.format(mirror)
)
cmd.extend(['--mirrors', mirror])
if build:
cmd.extend(['--build', build])
if target:
cmd.extend(['--target', target])
if download:
cmd.extend(['--download', download])
if download_cache or cache_dir:
cmd.extend(['--cache-dir' if salt.utils.versions.compare(
ver1=cur_version, oper='>=', ver2='6.0'
) else '--download-cache', download_cache or cache_dir])
if source:
cmd.extend(['--source', source])
if upgrade:
cmd.append('--upgrade')
if force_reinstall:
cmd.append('--force-reinstall')
if ignore_installed:
cmd.append('--ignore-installed')
if exists_action:
if exists_action.lower() not in ('s', 'i', 'w', 'b'):
raise CommandExecutionError(
'The exists_action pip option only supports the values '
's, i, w, and b. \'{0}\' is not valid.'.format(exists_action)
)
cmd.extend(['--exists-action', exists_action])
if no_deps:
cmd.append('--no-deps')
if no_install:
cmd.append('--no-install')
if no_download:
cmd.append('--no-download')
if no_cache_dir:
cmd.append('--no-cache-dir')
if pre_releases:
# Check the locally installed pip version
pip_version = cur_version
# From pip v1.4 the --pre flag is available
if salt.utils.versions.compare(ver1=pip_version, oper='>=', ver2='1.4'):
cmd.append('--pre')
if cert:
cmd.extend(['--cert', cert])
if global_options:
if isinstance(global_options, six.string_types):
global_options = [go.strip() for go in global_options.split(',')]
for opt in global_options:
cmd.extend(['--global-option', opt])
if install_options:
if isinstance(install_options, six.string_types):
install_options = [io.strip() for io in install_options.split(',')]
for opt in install_options:
cmd.extend(['--install-option', opt])
if pkgs:
if not isinstance(pkgs, list):
try:
pkgs = [p.strip() for p in pkgs.split(',')]
except AttributeError:
pkgs = [p.strip() for p in six.text_type(pkgs).split(',')]
pkgs = salt.utils.data.stringify(salt.utils.data.decode_list(pkgs))
# It's possible we replaced version-range commas with semicolons so
# they would survive the previous line (in the pip.installed state).
# Put the commas back in while making sure the names are contained in
# quotes, this allows for proper version spec passing salt>=0.17.0
cmd.extend([p.replace(';', ',') for p in pkgs])
elif not any([requirements, editable]):
# Starting with pip 10.0.0, if no packages are specified in the
# command, it returns a retcode 1. So instead of running the command,
# just return the output without running pip.
return {'retcode': 0, 'stdout': 'No packages to install.'}
if editable:
egg_match = re.compile(r'(?:#|#.*?&)egg=([^&]*)')
if isinstance(editable, six.string_types):
editable = [e.strip() for e in editable.split(',')]
for entry in editable:
# Is the editable local?
if not (entry == '.' or entry.startswith(('file://', '/'))):
match = egg_match.search(entry)
if not match or not match.group(1):
# Missing #egg=theEggName
raise CommandExecutionError(
'You must specify an egg for this editable'
)
cmd.extend(['--editable', entry])
if allow_all_external:
cmd.append('--allow-all-external')
if allow_external:
if isinstance(allow_external, six.string_types):
allow_external = [p.strip() for p in allow_external.split(',')]
for pkg in allow_external:
cmd.extend(['--allow-external', pkg])
if allow_unverified:
if isinstance(allow_unverified, six.string_types):
allow_unverified = \
[p.strip() for p in allow_unverified.split(',')]
for pkg in allow_unverified:
cmd.extend(['--allow-unverified', pkg])
if process_dependency_links:
cmd.append('--process-dependency-links')
if trusted_host:
cmd.extend(['--trusted-host', trusted_host])
if extra_args:
# These are arguments from the latest version of pip that
# have not yet been implemented in salt
for arg in extra_args:
# It is a keyword argument
if isinstance(arg, dict):
# There will only ever be one item in this dictionary
key, val = arg.popitem()
# Don't allow any recursion into keyword arg definitions
# Don't allow multiple definitions of a keyword
if isinstance(val, (dict, list)):
raise TypeError("Too many levels in: {}".format(key))
# This is a a normal one-to-one keyword argument
cmd.extend([key, val])
# It is a positional argument, append it to the list
else:
cmd.append(arg)
cmd_kwargs = dict(saltenv=saltenv, use_vt=use_vt, runas=user)
if kwargs:
cmd_kwargs.update(kwargs)
if env_vars:
cmd_kwargs.setdefault('env', {}).update(_format_env_vars(env_vars))
try:
if cwd:
cmd_kwargs['cwd'] = cwd
if bin_env and os.path.isdir(bin_env):
cmd_kwargs.setdefault('env', {})['VIRTUAL_ENV'] = bin_env
logger.debug(
'TRY BLOCK: end of pip.install -- cmd: %s, cmd_kwargs: %s',
cmd, cmd_kwargs
)
return __salt__['cmd.run_all'](cmd, python_shell=False, **cmd_kwargs)
finally:
_clear_context(bin_env)
for tempdir in [cr for cr in cleanup_requirements if cr is not None]:
if os.path.isdir(tempdir):
shutil.rmtree(tempdir)
def freeze(bin_env=None,
user=None,
cwd=None,
use_vt=False,
env_vars=None,
**kwargs):
'''
Return a list of installed packages either globally or in the specified
virtualenv
bin_env
Path to pip (or to a virtualenv). This can be used to specify the path
to the pip to use when more than one Python release is installed (e.g.
``/usr/bin/pip-2.7`` or ``/usr/bin/pip-2.6``. If a directory path is
specified, it is assumed to be a virtualenv.
user
The user under which to run pip
cwd
Directory from which to run pip
.. note::
If the version of pip available is older than 8.0.3, the list will not
include the packages ``pip``, ``wheel``, ``setuptools``, or
``distribute`` even if they are installed.
CLI Example:
.. code-block:: bash
salt '*' pip.freeze bin_env=/home/code/path/to/virtualenv
'''
cmd = _get_pip_bin(bin_env)
cmd.append('freeze')
# Include pip, setuptools, distribute, wheel
min_version = '8.0.3'
cur_version = version(bin_env)
if salt.utils.versions.compare(ver1=cur_version, oper='<', ver2=min_version):
logger.warning(
'The version of pip installed is %s, which is older than %s. '
'The packages pip, wheel, setuptools, and distribute will not be '
'included in the output of pip.freeze', cur_version, min_version
)
else:
cmd.append('--all')
cmd_kwargs = dict(runas=user, cwd=cwd, use_vt=use_vt, python_shell=False)
if kwargs:
cmd_kwargs.update(**kwargs)
if bin_env and os.path.isdir(bin_env):
cmd_kwargs['env'] = {'VIRTUAL_ENV': bin_env}
if env_vars:
cmd_kwargs.setdefault('env', {}).update(_format_env_vars(env_vars))
result = __salt__['cmd.run_all'](cmd, **cmd_kwargs)
if result['retcode']:
raise CommandExecutionError(result['stderr'], info=result)
return result['stdout'].splitlines()
def list_(prefix=None,
bin_env=None,
user=None,
cwd=None,
env_vars=None,
**kwargs):
'''
Filter list of installed apps from ``freeze`` and check to see if
``prefix`` exists in the list of packages installed.
.. note::
If the version of pip available is older than 8.0.3, the packages
``wheel``, ``setuptools``, and ``distribute`` will not be reported by
this function even if they are installed. Unlike :py:func:`pip.freeze
<salt.modules.pip.freeze>`, this function always reports the version of
pip which is installed.
CLI Example:
.. code-block:: bash
salt '*' pip.list salt
'''
packages = {}
if prefix is None or 'pip'.startswith(prefix):
packages['pip'] = version(bin_env)
for line in freeze(bin_env=bin_env,
user=user,
cwd=cwd,
env_vars=env_vars,
**kwargs):
if line.startswith('-f') or line.startswith('#'):
# ignore -f line as it contains --find-links directory
# ignore comment lines
continue
elif line.startswith('-e hg+not trust'):
# ignore hg + not trust problem
continue
elif line.startswith('-e'):
line = line.split('-e ')[1]
if '#egg=' in line:
version_, name = line.split('#egg=')
else:
if len(line.split('===')) >= 2:
name = line.split('===')[0]
version_ = line.split('===')[1]
elif len(line.split('==')) >= 2:
name = line.split('==')[0]
version_ = line.split('==')[1]
elif len(line.split('===')) >= 2:
name = line.split('===')[0]
version_ = line.split('===')[1]
elif len(line.split('==')) >= 2:
name = line.split('==')[0]
version_ = line.split('==')[1]
else:
logger.error('Can\'t parse line \'%s\'', line)
continue
if prefix:
if name.lower().startswith(prefix.lower()):
packages[name] = version_
else:
packages[name] = version_
return packages
def version(bin_env=None):
'''
.. versionadded:: 0.17.0
Returns the version of pip. Use ``bin_env`` to specify the path to a
virtualenv and get the version of pip in that virtualenv.
If unable to detect the pip version, returns ``None``.
CLI Example:
.. code-block:: bash
salt '*' pip.version
'''
contextkey = 'pip.version'
if bin_env is not None:
contextkey = '{0}.{1}'.format(contextkey, bin_env)
if contextkey in __context__:
return __context__[contextkey]
cmd = _get_pip_bin(bin_env)[:]
cmd.append('--version')
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
if ret['retcode']:
raise CommandNotFoundError('Could not find a `pip` binary')
try:
pip_version = re.match(r'^pip (\S+)', ret['stdout']).group(1)
except AttributeError:
pip_version = None
__context__[contextkey] = pip_version
return pip_version
def list_upgrades(bin_env=None,
user=None,
cwd=None):
'''
Check whether or not an upgrade is available for all packages
CLI Example:
.. code-block:: bash
salt '*' pip.list_upgrades
'''
cmd = _get_pip_bin(bin_env)
cmd.extend(['list', '--outdated'])
pip_version = version(bin_env)
# Pip started supporting the ability to output json starting with 9.0.0
min_version = '9.0'
if salt.utils.versions.compare(ver1=pip_version,
oper='>=',
ver2=min_version):
cmd.append('--format=json')
cmd_kwargs = dict(cwd=cwd, runas=user)
if bin_env and os.path.isdir(bin_env):
cmd_kwargs['env'] = {'VIRTUAL_ENV': bin_env}
result = __salt__['cmd.run_all'](cmd, **cmd_kwargs)
if result['retcode']:
raise CommandExecutionError(result['stderr'], info=result)
packages = {}
# Pip started supporting the ability to output json starting with 9.0.0
# Older versions will have to parse stdout
if salt.utils.versions.compare(ver1=pip_version, oper='<', ver2='9.0.0'):
# Pip versions < 8.0.0 had a different output format
# Sample data:
# pip (Current: 7.1.2 Latest: 10.0.1 [wheel])
# psutil (Current: 5.2.2 Latest: 5.4.5 [wheel])
# pyasn1 (Current: 0.2.3 Latest: 0.4.2 [wheel])
# pycparser (Current: 2.17 Latest: 2.18 [sdist])
if salt.utils.versions.compare(ver1=pip_version, oper='<', ver2='8.0.0'):
logger.debug('pip module: Old output format')
pat = re.compile(r'(\S*)\s+\(.*Latest:\s+(.*)\)')
# New output format for version 8.0.0+
# Sample data:
# pip (8.0.0) - Latest: 10.0.1 [wheel]
# psutil (5.2.2) - Latest: 5.4.5 [wheel]
# pyasn1 (0.2.3) - Latest: 0.4.2 [wheel]
# pycparser (2.17) - Latest: 2.18 [sdist]
else:
logger.debug('pip module: New output format')
pat = re.compile(r'(\S*)\s+\(.*\)\s+-\s+Latest:\s+(.*)')
for line in result['stdout'].splitlines():
match = pat.search(line)
if match:
name, version_ = match.groups()
else:
logger.error('Can\'t parse line \'%s\'', line)
continue
packages[name] = version_
else:
logger.debug('pip module: JSON output format')
try:
pkgs = salt.utils.json.loads(result['stdout'], strict=False)
except ValueError:
raise CommandExecutionError('Invalid JSON', info=result)
for pkg in pkgs:
packages[pkg['name']] = '{0} [{1}]'.format(pkg['latest_version'],
pkg['latest_filetype'])
return packages
def is_installed(pkgname=None,
bin_env=None,
user=None,
cwd=None):
'''
.. versionadded:: 2018.3.0
Filter list of installed apps from ``freeze`` and return True or False if
``pkgname`` exists in the list of packages installed.
.. note::
If the version of pip available is older than 8.0.3, the packages
wheel, setuptools, and distribute will not be reported by this function
even if they are installed. Unlike :py:func:`pip.freeze
<salt.modules.pip.freeze>`, this function always reports the version of
pip which is installed.
CLI Example:
.. code-block:: bash
salt '*' pip.is_installed salt
'''
for line in freeze(bin_env=bin_env, user=user, cwd=cwd):
if line.startswith('-f') or line.startswith('#'):
# ignore -f line as it contains --find-links directory
# ignore comment lines
continue
elif line.startswith('-e hg+not trust'):
# ignore hg + not trust problem
continue
elif line.startswith('-e'):
line = line.split('-e ')[1]
version_, name = line.split('#egg=')
elif len(line.split('===')) >= 2:
name = line.split('===')[0]
version_ = line.split('===')[1]
elif len(line.split('==')) >= 2:
name = line.split('==')[0]
version_ = line.split('==')[1]
else:
logger.error('Can\'t parse line \'%s\'', line)
continue
if pkgname:
if pkgname == name.lower():
return True
return False
def upgrade_available(pkg,
bin_env=None,
user=None,
cwd=None):
'''
.. versionadded:: 2015.5.0
Check whether or not an upgrade is available for a given package
CLI Example:
.. code-block:: bash
salt '*' pip.upgrade_available <package name>
'''
return pkg in list_upgrades(bin_env=bin_env, user=user, cwd=cwd)
def upgrade(bin_env=None,
user=None,
cwd=None,
use_vt=False):
'''
.. versionadded:: 2015.5.0
Upgrades outdated pip packages.
.. note::
On Windows you can't update salt from pip using salt, so salt will be
skipped
Returns a dict containing the changes.
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
CLI Example:
.. code-block:: bash
salt '*' pip.upgrade
'''
ret = {'changes': {},
'result': True,
'comment': '',
}
cmd = _get_pip_bin(bin_env)
cmd.extend(['install', '-U'])
old = list_(bin_env=bin_env, user=user, cwd=cwd)
cmd_kwargs = dict(cwd=cwd, use_vt=use_vt)
if bin_env and os.path.isdir(bin_env):
cmd_kwargs['env'] = {'VIRTUAL_ENV': bin_env}
errors = False
for pkg in list_upgrades(bin_env=bin_env, user=user, cwd=cwd):
if pkg == 'salt':
if salt.utils.platform.is_windows():
continue
result = __salt__['cmd.run_all'](cmd + [pkg], **cmd_kwargs)
if result['retcode'] != 0:
errors = True
if 'stderr' in result:
ret['comment'] += result['stderr']
if errors:
ret['result'] = False
_clear_context(bin_env)
new = list_(bin_env=bin_env, user=user, cwd=cwd)
ret['changes'] = salt.utils.data.compare_dicts(old, new)
return ret
def list_all_versions(pkg,
bin_env=None,
include_alpha=False,
include_beta=False,
include_rc=False,
user=None,
cwd=None,
index_url=None,
extra_index_url=None):
'''
.. versionadded:: 2017.7.3
List all available versions of a pip package
pkg
The package to check
bin_env
Path to pip (or to a virtualenv). This can be used to specify the path
to the pip to use when more than one Python release is installed (e.g.
``/usr/bin/pip-2.7`` or ``/usr/bin/pip-2.6``. If a directory path is
specified, it is assumed to be a virtualenv.
include_alpha
Include alpha versions in the list
include_beta
Include beta versions in the list
include_rc
Include release candidates versions in the list
user
The user under which to run pip
cwd
Directory from which to run pip
index_url
Base URL of Python Package Index
.. versionadded:: 2019.2.0
extra_index_url
Additional URL of Python Package Index
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' pip.list_all_versions <package name>
'''
cmd = _get_pip_bin(bin_env)
cmd.extend(['install', '{0}==versions'.format(pkg)])
if index_url:
if not salt.utils.url.validate(index_url, VALID_PROTOS):
raise CommandExecutionError(
'\'{0}\' is not a valid URL'.format(index_url)
)
cmd.extend(['--index-url', index_url])
if extra_index_url:
if not salt.utils.url.validate(extra_index_url, VALID_PROTOS):
raise CommandExecutionError(
'\'{0}\' is not a valid URL'.format(extra_index_url)
)
cmd.extend(['--extra-index-url', extra_index_url])
cmd_kwargs = dict(cwd=cwd, runas=user, output_loglevel='quiet', redirect_stderr=True)
if bin_env and os.path.isdir(bin_env):
cmd_kwargs['env'] = {'VIRTUAL_ENV': bin_env}
result = __salt__['cmd.run_all'](cmd, **cmd_kwargs)
filtered = []
if not include_alpha:
filtered.append('a')
if not include_beta:
filtered.append('b')
if not include_rc:
filtered.append('rc')
if filtered:
excludes = re.compile(r'^((?!{0}).)*$'.format('|'.join(filtered)))
else:
excludes = re.compile(r'')
versions = []
for line in result['stdout'].splitlines():
match = re.search(r'\s*Could not find a version.* \(from versions: (.*)\)', line)
if match:
versions = [v for v in match.group(1).split(', ') if v and excludes.match(v)]
versions.sort(key=pkg_resources.parse_version)
break
if not versions:
return None
return versions
|
saltstack/salt
|
salt/modules/pip.py
|
freeze
|
python
|
def freeze(bin_env=None,
user=None,
cwd=None,
use_vt=False,
env_vars=None,
**kwargs):
'''
Return a list of installed packages either globally or in the specified
virtualenv
bin_env
Path to pip (or to a virtualenv). This can be used to specify the path
to the pip to use when more than one Python release is installed (e.g.
``/usr/bin/pip-2.7`` or ``/usr/bin/pip-2.6``. If a directory path is
specified, it is assumed to be a virtualenv.
user
The user under which to run pip
cwd
Directory from which to run pip
.. note::
If the version of pip available is older than 8.0.3, the list will not
include the packages ``pip``, ``wheel``, ``setuptools``, or
``distribute`` even if they are installed.
CLI Example:
.. code-block:: bash
salt '*' pip.freeze bin_env=/home/code/path/to/virtualenv
'''
cmd = _get_pip_bin(bin_env)
cmd.append('freeze')
# Include pip, setuptools, distribute, wheel
min_version = '8.0.3'
cur_version = version(bin_env)
if salt.utils.versions.compare(ver1=cur_version, oper='<', ver2=min_version):
logger.warning(
'The version of pip installed is %s, which is older than %s. '
'The packages pip, wheel, setuptools, and distribute will not be '
'included in the output of pip.freeze', cur_version, min_version
)
else:
cmd.append('--all')
cmd_kwargs = dict(runas=user, cwd=cwd, use_vt=use_vt, python_shell=False)
if kwargs:
cmd_kwargs.update(**kwargs)
if bin_env and os.path.isdir(bin_env):
cmd_kwargs['env'] = {'VIRTUAL_ENV': bin_env}
if env_vars:
cmd_kwargs.setdefault('env', {}).update(_format_env_vars(env_vars))
result = __salt__['cmd.run_all'](cmd, **cmd_kwargs)
if result['retcode']:
raise CommandExecutionError(result['stderr'], info=result)
return result['stdout'].splitlines()
|
Return a list of installed packages either globally or in the specified
virtualenv
bin_env
Path to pip (or to a virtualenv). This can be used to specify the path
to the pip to use when more than one Python release is installed (e.g.
``/usr/bin/pip-2.7`` or ``/usr/bin/pip-2.6``. If a directory path is
specified, it is assumed to be a virtualenv.
user
The user under which to run pip
cwd
Directory from which to run pip
.. note::
If the version of pip available is older than 8.0.3, the list will not
include the packages ``pip``, ``wheel``, ``setuptools``, or
``distribute`` even if they are installed.
CLI Example:
.. code-block:: bash
salt '*' pip.freeze bin_env=/home/code/path/to/virtualenv
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/pip.py#L1089-L1149
|
[
"def version(bin_env=None):\n '''\n .. versionadded:: 0.17.0\n\n Returns the version of pip. Use ``bin_env`` to specify the path to a\n virtualenv and get the version of pip in that virtualenv.\n\n If unable to detect the pip version, returns ``None``.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' pip.version\n '''\n contextkey = 'pip.version'\n if bin_env is not None:\n contextkey = '{0}.{1}'.format(contextkey, bin_env)\n\n if contextkey in __context__:\n return __context__[contextkey]\n\n cmd = _get_pip_bin(bin_env)[:]\n cmd.append('--version')\n\n ret = __salt__['cmd.run_all'](cmd, python_shell=False)\n if ret['retcode']:\n raise CommandNotFoundError('Could not find a `pip` binary')\n\n try:\n pip_version = re.match(r'^pip (\\S+)', ret['stdout']).group(1)\n except AttributeError:\n pip_version = None\n\n __context__[contextkey] = pip_version\n return pip_version\n",
"def compare(ver1='', oper='==', ver2='', cmp_func=None, ignore_epoch=False):\n '''\n Compares two version numbers. Accepts a custom function to perform the\n cmp-style version comparison, otherwise uses version_cmp().\n '''\n cmp_map = {'<': (-1,), '<=': (-1, 0), '==': (0,),\n '>=': (0, 1), '>': (1,)}\n if oper not in ('!=',) and oper not in cmp_map:\n log.error('Invalid operator \\'%s\\' for version comparison', oper)\n return False\n\n if cmp_func is None:\n cmp_func = version_cmp\n\n cmp_result = cmp_func(ver1, ver2, ignore_epoch=ignore_epoch)\n if cmp_result is None:\n return False\n\n # Check if integer/long\n if not isinstance(cmp_result, numbers.Integral):\n log.error('The version comparison function did not return an '\n 'integer/long.')\n return False\n\n if oper == '!=':\n return cmp_result not in cmp_map['==']\n else:\n # Gracefully handle cmp_result not in (-1, 0, 1).\n if cmp_result < -1:\n cmp_result = -1\n elif cmp_result > 1:\n cmp_result = 1\n\n return cmp_result in cmp_map[oper]\n",
"def _get_pip_bin(bin_env):\n '''\n Locate the pip binary, either from `bin_env` as a virtualenv, as the\n executable itself, or from searching conventional filesystem locations\n '''\n if not bin_env:\n logger.debug('pip: Using pip from currently-running Python')\n return [os.path.normpath(sys.executable), '-m', 'pip']\n\n python_bin = 'python.exe' if salt.utils.platform.is_windows() else 'python'\n\n def _search_paths(*basedirs):\n ret = []\n for path in basedirs:\n ret.extend([\n os.path.join(path, python_bin),\n os.path.join(path, 'bin', python_bin),\n os.path.join(path, 'Scripts', python_bin)\n ])\n return ret\n\n # try to get python bin from virtualenv (i.e. bin_env)\n if os.path.isdir(bin_env):\n for bin_path in _search_paths(bin_env):\n if os.path.isfile(bin_path):\n if os.access(bin_path, os.X_OK):\n logger.debug('pip: Found python binary: %s', bin_path)\n return [os.path.normpath(bin_path), '-m', 'pip']\n else:\n logger.debug(\n 'pip: Found python binary by name but it is not '\n 'executable: %s', bin_path\n )\n raise CommandNotFoundError(\n 'Could not find a pip binary in virtualenv {0}'.format(bin_env)\n )\n\n # bin_env is the python or pip binary\n elif os.access(bin_env, os.X_OK):\n if os.path.isfile(bin_env):\n # If the python binary was passed, return it\n if 'python' in os.path.basename(bin_env):\n return [os.path.normpath(bin_env), '-m', 'pip']\n # We have been passed a pip binary, use the pip binary.\n return [os.path.normpath(bin_env)]\n\n raise CommandExecutionError(\n 'Could not find a pip binary within {0}'.format(bin_env)\n )\n else:\n raise CommandNotFoundError(\n 'Access denied to {0}, could not find a pip binary'.format(bin_env)\n )\n",
"def _format_env_vars(env_vars):\n ret = {}\n if env_vars:\n if isinstance(env_vars, dict):\n for key, val in six.iteritems(env_vars):\n if not isinstance(key, six.string_types):\n key = str(key) # future lint: disable=blacklisted-function\n if not isinstance(val, six.string_types):\n val = str(val) # future lint: disable=blacklisted-function\n ret[key] = val\n else:\n raise CommandExecutionError(\n 'env_vars {0} is not a dictionary'.format(env_vars))\n return ret\n"
] |
# -*- coding: utf-8 -*-
r'''
Install Python packages with pip to either the system or a virtualenv
Windows Support
===============
.. versionadded:: 2014.7.4
Salt now uses a portable python. As a result the entire pip module is now
functional on the salt installation itself. You can pip install dependencies
for your custom modules. You can even upgrade salt itself using pip. For this
to work properly, you must specify the Current Working Directory (``cwd``) and
the Pip Binary (``bin_env``) salt should use. The variable ``pip_bin`` can be
either a virtualenv path or the path to the pip binary itself.
For example, the following command will list all software installed using pip
to your current salt environment:
.. code-block:: bat
salt <minion> pip.list cwd='C:\salt\bin\Scripts' bin_env='C:\salt\bin\Scripts\pip.exe'
Specifying the ``cwd`` and ``bin_env`` options ensures you're modifying the
salt environment. If these are omitted, it will default to the local
installation of python. If python is not installed locally it will fail saying
it couldn't find pip.
State File Support
------------------
This functionality works in states as well. If you need to pip install colorama
with a state, for example, the following will work:
.. code-block:: yaml
install_colorama:
pip.installed:
- name: colorama
- cwd: 'C:\salt\bin\scripts'
- bin_env: 'C:\salt\bin\scripts\pip.exe'
- upgrade: True
Upgrading Salt using Pip
------------------------
You can now update salt using pip to any version from the 2014.7 branch
forward. Previous version require recompiling some of the dependencies which is
painful in windows.
To do this you just use pip with git to update to the version you want and then
restart the service. Here is a sample state file that upgrades salt to the head
of the 2015.5 branch:
.. code-block:: yaml
install_salt:
pip.installed:
- cwd: 'C:\salt\bin\scripts'
- bin_env: 'C:\salt\bin\scripts\pip.exe'
- editable: git+https://github.com/saltstack/salt@2015.5#egg=salt
- upgrade: True
restart_service:
service.running:
- name: salt-minion
- enable: True
- watch:
- pip: install_salt
.. note::
If you're having problems, you might try doubling the back slashes. For
example, cwd: 'C:\\salt\\bin\\scripts'. Sometimes python thinks the single
back slash is an escape character.
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import logging
import os
try:
import pkg_resources
except ImportError:
pkg_resources = None
import re
import shutil
import sys
import tempfile
# Import Salt libs
import salt.utils.data
import salt.utils.files
import salt.utils.json
import salt.utils.locales
import salt.utils.platform
import salt.utils.stringutils
import salt.utils.url
import salt.utils.versions
from salt.ext import six
from salt.exceptions import CommandExecutionError, CommandNotFoundError
# This needs to be named logger so we don't shadow it in pip.install
logger = logging.getLogger(__name__) # pylint: disable=C0103
# Don't shadow built-in's.
__func_alias__ = {
'list_': 'list'
}
VALID_PROTOS = ['http', 'https', 'ftp', 'file']
rex_pip_chain_read = re.compile(r'-r\s(.*)\n?', re.MULTILINE)
def __virtual__():
'''
There is no way to verify that pip is installed without inspecting the
entire filesystem. If it's not installed in a conventional location, the
user is required to provide the location of pip each time it is used.
'''
if pkg_resources is None:
ret = False, 'Package dependency "pkg_resource" is missing'
else:
ret = 'pip'
return ret
def _clear_context(bin_env=None):
'''
Remove the cached pip version
'''
contextkey = 'pip.version'
if bin_env is not None:
contextkey = '{0}.{1}'.format(contextkey, bin_env)
__context__.pop(contextkey, None)
def _get_pip_bin(bin_env):
'''
Locate the pip binary, either from `bin_env` as a virtualenv, as the
executable itself, or from searching conventional filesystem locations
'''
if not bin_env:
logger.debug('pip: Using pip from currently-running Python')
return [os.path.normpath(sys.executable), '-m', 'pip']
python_bin = 'python.exe' if salt.utils.platform.is_windows() else 'python'
def _search_paths(*basedirs):
ret = []
for path in basedirs:
ret.extend([
os.path.join(path, python_bin),
os.path.join(path, 'bin', python_bin),
os.path.join(path, 'Scripts', python_bin)
])
return ret
# try to get python bin from virtualenv (i.e. bin_env)
if os.path.isdir(bin_env):
for bin_path in _search_paths(bin_env):
if os.path.isfile(bin_path):
if os.access(bin_path, os.X_OK):
logger.debug('pip: Found python binary: %s', bin_path)
return [os.path.normpath(bin_path), '-m', 'pip']
else:
logger.debug(
'pip: Found python binary by name but it is not '
'executable: %s', bin_path
)
raise CommandNotFoundError(
'Could not find a pip binary in virtualenv {0}'.format(bin_env)
)
# bin_env is the python or pip binary
elif os.access(bin_env, os.X_OK):
if os.path.isfile(bin_env):
# If the python binary was passed, return it
if 'python' in os.path.basename(bin_env):
return [os.path.normpath(bin_env), '-m', 'pip']
# We have been passed a pip binary, use the pip binary.
return [os.path.normpath(bin_env)]
raise CommandExecutionError(
'Could not find a pip binary within {0}'.format(bin_env)
)
else:
raise CommandNotFoundError(
'Access denied to {0}, could not find a pip binary'.format(bin_env)
)
def _get_cached_requirements(requirements, saltenv):
'''
Get the location of a cached requirements file; caching if necessary.
'''
req_file, senv = salt.utils.url.parse(requirements)
if senv:
saltenv = senv
if req_file not in __salt__['cp.list_master'](saltenv):
# Requirements file does not exist in the given saltenv.
return False
cached_requirements = __salt__['cp.is_cached'](
requirements, saltenv
)
if not cached_requirements:
# It's not cached, let's cache it.
cached_requirements = __salt__['cp.cache_file'](
requirements, saltenv
)
# Check if the master version has changed.
if __salt__['cp.hash_file'](requirements, saltenv) != \
__salt__['cp.hash_file'](cached_requirements, saltenv):
cached_requirements = __salt__['cp.cache_file'](
requirements, saltenv
)
return cached_requirements
def _get_env_activate(bin_env):
'''
Return the path to the activate binary
'''
if not bin_env:
raise CommandNotFoundError('Could not find a `activate` binary')
if os.path.isdir(bin_env):
if salt.utils.platform.is_windows():
activate_bin = os.path.join(bin_env, 'Scripts', 'activate.bat')
else:
activate_bin = os.path.join(bin_env, 'bin', 'activate')
if os.path.isfile(activate_bin):
return activate_bin
raise CommandNotFoundError('Could not find a `activate` binary')
def _find_req(link):
logger.info('_find_req -- link = %s', link)
with salt.utils.files.fopen(link) as fh_link:
child_links = rex_pip_chain_read.findall(
salt.utils.stringutils.to_unicode(fh_link.read())
)
base_path = os.path.dirname(link)
child_links = [os.path.join(base_path, d) for d in child_links]
return child_links
def _resolve_requirements_chain(requirements):
'''
Return an array of requirements file paths that can be used to complete
the no_chown==False && user != None conundrum
'''
chain = []
if isinstance(requirements, six.string_types):
requirements = [requirements]
for req_file in requirements:
chain.append(req_file)
chain.extend(_resolve_requirements_chain(_find_req(req_file)))
return chain
def _process_requirements(requirements, cmd, cwd, saltenv, user):
'''
Process the requirements argument
'''
cleanup_requirements = []
if requirements is not None:
if isinstance(requirements, six.string_types):
requirements = [r.strip() for r in requirements.split(',')]
elif not isinstance(requirements, list):
raise TypeError('requirements must be a string or list')
treq = None
for requirement in requirements:
logger.debug('TREQ IS: %s', treq)
if requirement.startswith('salt://'):
cached_requirements = _get_cached_requirements(
requirement, saltenv
)
if not cached_requirements:
ret = {'result': False,
'comment': 'pip requirements file \'{0}\' not found'
.format(requirement)}
return None, ret
requirement = cached_requirements
if user:
# Need to make a temporary copy since the user will, most
# likely, not have the right permissions to read the file
if not treq:
treq = tempfile.mkdtemp()
__salt__['file.chown'](treq, user, None)
# In Windows, just being owner of a file isn't enough. You also
# need permissions
if salt.utils.platform.is_windows():
__utils__['dacl.set_permissions'](
obj_name=treq,
principal=user,
permissions='read_execute')
current_directory = None
if not current_directory:
current_directory = os.path.abspath(os.curdir)
logger.info('_process_requirements from directory, '
'%s -- requirement: %s', cwd, requirement)
if cwd is None:
r = requirement
c = cwd
requirement_abspath = os.path.abspath(requirement)
cwd = os.path.dirname(requirement_abspath)
requirement = os.path.basename(requirement)
logger.debug('\n\tcwd: %s -> %s\n\trequirement: %s -> %s\n',
c, cwd, r, requirement
)
os.chdir(cwd)
reqs = _resolve_requirements_chain(requirement)
os.chdir(current_directory)
logger.info('request files: %s', reqs)
for req_file in reqs:
if not os.path.isabs(req_file):
req_file = os.path.join(cwd, req_file)
logger.debug('TREQ N CWD: %s -- %s -- for %s', treq, cwd, req_file)
target_path = os.path.join(treq, os.path.basename(req_file))
logger.debug('S: %s', req_file)
logger.debug('T: %s', target_path)
target_base = os.path.dirname(target_path)
if not os.path.exists(target_base):
os.makedirs(target_base, mode=0o755)
__salt__['file.chown'](target_base, user, None)
if not os.path.exists(target_path):
logger.debug(
'Copying %s to %s', req_file, target_path
)
__salt__['file.copy'](req_file, target_path)
logger.debug(
'Changing ownership of requirements file \'%s\' to '
'user \'%s\'', target_path, user
)
__salt__['file.chown'](target_path, user, None)
req_args = os.path.join(treq, requirement) if treq else requirement
cmd.extend(['--requirement', req_args])
cleanup_requirements.append(treq)
logger.debug('CLEANUP_REQUIREMENTS: %s', cleanup_requirements)
return cleanup_requirements, None
def _format_env_vars(env_vars):
ret = {}
if env_vars:
if isinstance(env_vars, dict):
for key, val in six.iteritems(env_vars):
if not isinstance(key, six.string_types):
key = str(key) # future lint: disable=blacklisted-function
if not isinstance(val, six.string_types):
val = str(val) # future lint: disable=blacklisted-function
ret[key] = val
else:
raise CommandExecutionError(
'env_vars {0} is not a dictionary'.format(env_vars))
return ret
def install(pkgs=None, # pylint: disable=R0912,R0913,R0914
requirements=None,
bin_env=None,
use_wheel=False,
no_use_wheel=False,
log=None,
proxy=None,
timeout=None,
editable=None,
find_links=None,
index_url=None,
extra_index_url=None,
no_index=False,
mirrors=None,
build=None,
target=None,
download=None,
download_cache=None,
source=None,
upgrade=False,
force_reinstall=False,
ignore_installed=False,
exists_action=None,
no_deps=False,
no_install=False,
no_download=False,
global_options=None,
install_options=None,
user=None,
cwd=None,
pre_releases=False,
cert=None,
allow_all_external=False,
allow_external=None,
allow_unverified=None,
process_dependency_links=False,
saltenv='base',
env_vars=None,
use_vt=False,
trusted_host=None,
no_cache_dir=False,
cache_dir=None,
no_binary=None,
extra_args=None,
**kwargs):
'''
Install packages with pip
Install packages individually or from a pip requirements file. Install
packages globally or to a virtualenv.
pkgs
Comma separated list of packages to install
requirements
Path to requirements
bin_env
Path to pip (or to a virtualenv). This can be used to specify the path
to the pip to use when more than one Python release is installed (e.g.
``/usr/bin/pip-2.7`` or ``/usr/bin/pip-2.6``. If a directory path is
specified, it is assumed to be a virtualenv.
.. note::
For Windows, if the pip module is being used to upgrade the pip
package, bin_env should be the path to the virtualenv or to the
python binary that should be used. The pip command is unable to
upgrade itself in Windows.
use_wheel
Prefer wheel archives (requires pip>=1.4)
no_use_wheel
Force to not use wheel archives (requires pip>=1.4,<10.0.0)
no_binary
Force to not use binary packages (requires pip >= 7.0.0)
Accepts either :all: to disable all binary packages, :none: to empty the set,
or one or more package names with commas between them
log
Log file where a complete (maximum verbosity) record will be kept
proxy
Specify a proxy in the form ``user:passwd@proxy.server:port``. Note
that the ``user:password@`` is optional and required only if you are
behind an authenticated proxy. If you provide
``user@proxy.server:port`` then you will be prompted for a password.
timeout
Set the socket timeout (default 15 seconds)
editable
install something editable (e.g.
``git+https://github.com/worldcompany/djangoembed.git#egg=djangoembed``)
find_links
URL to search for packages
index_url
Base URL of Python Package Index
extra_index_url
Extra URLs of package indexes to use in addition to ``index_url``
no_index
Ignore package index
mirrors
Specific mirror URL(s) to query (automatically adds --use-mirrors)
.. warning::
This option has been deprecated and removed in pip version 7.0.0.
Please use ``index_url`` and/or ``extra_index_url`` instead.
build
Unpack packages into ``build`` dir
target
Install packages into ``target`` dir
download
Download packages into ``download`` instead of installing them
download_cache | cache_dir
Cache downloaded packages in ``download_cache`` or ``cache_dir`` dir
source
Check out ``editable`` packages into ``source`` dir
upgrade
Upgrade all packages to the newest available version
force_reinstall
When upgrading, reinstall all packages even if they are already
up-to-date.
ignore_installed
Ignore the installed packages (reinstalling instead)
exists_action
Default action when a path already exists: (s)witch, (i)gnore, (w)ipe,
(b)ackup
no_deps
Ignore package dependencies
no_install
Download and unpack all packages, but don't actually install them
no_download
Don't download any packages, just install the ones already downloaded
(completes an install run with ``--no-install``)
install_options
Extra arguments to be supplied to the setup.py install command (e.g.
like ``--install-option='--install-scripts=/usr/local/bin'``). Use
multiple --install-option options to pass multiple options to setup.py
install. If you are using an option with a directory path, be sure to
use absolute path.
global_options
Extra global options to be supplied to the setup.py call before the
install command.
user
The user under which to run pip
cwd
Directory from which to run pip
pre_releases
Include pre-releases in the available versions
cert
Provide a path to an alternate CA bundle
allow_all_external
Allow the installation of all externally hosted files
allow_external
Allow the installation of externally hosted files (comma separated
list)
allow_unverified
Allow the installation of insecure and unverifiable files (comma
separated list)
process_dependency_links
Enable the processing of dependency links
env_vars
Set environment variables that some builds will depend on. For example,
a Python C-module may have a Makefile that needs INCLUDE_PATH set to
pick up a header file while compiling. This must be in the form of a
dictionary or a mapping.
Example:
.. code-block:: bash
salt '*' pip.install django_app env_vars="{'CUSTOM_PATH': '/opt/django_app'}"
trusted_host
Mark this host as trusted, even though it does not have valid or any
HTTPS.
use_vt
Use VT terminal emulation (see output while installing)
no_cache_dir
Disable the cache.
extra_args
pip keyword and positional arguments not yet implemented in salt
.. code-block:: yaml
salt '*' pip.install pandas extra_args="[{'--latest-pip-kwarg':'param'}, '--latest-pip-arg']"
.. warning::
If unsupported options are passed here that are not supported in a
minion's version of pip, a `No such option error` will be thrown.
Will be translated into the following pip command:
.. code-block:: bash
pip install pandas --latest-pip-kwarg param --latest-pip-arg
CLI Example:
.. code-block:: bash
salt '*' pip.install <package name>,<package2 name>
salt '*' pip.install requirements=/path/to/requirements.txt
salt '*' pip.install <package name> bin_env=/path/to/virtualenv
salt '*' pip.install <package name> bin_env=/path/to/pip_bin
Complicated CLI example::
salt '*' pip.install markdown,django \
editable=git+https://github.com/worldcompany/djangoembed.git#egg=djangoembed upgrade=True no_deps=True
'''
cmd = _get_pip_bin(bin_env)
cmd.append('install')
cleanup_requirements, error = _process_requirements(
requirements=requirements,
cmd=cmd,
cwd=cwd,
saltenv=saltenv,
user=user
)
if error:
return error
cur_version = version(bin_env)
if use_wheel:
min_version = '1.4'
max_version = '9.0.3'
too_low = salt.utils.versions.compare(ver1=cur_version, oper='<', ver2=min_version)
too_high = salt.utils.versions.compare(ver1=cur_version, oper='>', ver2=max_version)
if too_low or too_high:
logger.error(
'The --use-wheel option is only supported in pip between %s and '
'%s. The version of pip detected is %s. This option '
'will be ignored.', min_version, max_version, cur_version
)
else:
cmd.append('--use-wheel')
if no_use_wheel:
min_version = '1.4'
max_version = '9.0.3'
too_low = salt.utils.versions.compare(ver1=cur_version, oper='<', ver2=min_version)
too_high = salt.utils.versions.compare(ver1=cur_version, oper='>', ver2=max_version)
if too_low or too_high:
logger.error(
'The --no-use-wheel option is only supported in pip between %s and '
'%s. The version of pip detected is %s. This option '
'will be ignored.', min_version, max_version, cur_version
)
else:
cmd.append('--no-use-wheel')
if no_binary:
min_version = '7.0.0'
too_low = salt.utils.versions.compare(ver1=cur_version, oper='<', ver2=min_version)
if too_low:
logger.error(
'The --no-binary option is only supported in pip %s and '
'newer. The version of pip detected is %s. This option '
'will be ignored.', min_version, cur_version
)
else:
if isinstance(no_binary, list):
no_binary = ','.join(no_binary)
cmd.extend(['--no-binary', no_binary])
if log:
if os.path.isdir(log):
raise IOError(
'\'{0}\' is a directory. Use --log path_to_file'.format(log))
elif not os.access(log, os.W_OK):
raise IOError('\'{0}\' is not writeable'.format(log))
cmd.extend(['--log', log])
if proxy:
cmd.extend(['--proxy', proxy])
if timeout:
try:
if isinstance(timeout, float):
# Catch floating point input, exception will be caught in
# exception class below.
raise ValueError('Timeout cannot be a float')
int(timeout)
except ValueError:
raise ValueError(
'\'{0}\' is not a valid timeout, must be an integer'
.format(timeout)
)
cmd.extend(['--timeout', timeout])
if find_links:
if isinstance(find_links, six.string_types):
find_links = [l.strip() for l in find_links.split(',')]
for link in find_links:
if not (salt.utils.url.validate(link, VALID_PROTOS) or os.path.exists(link)):
raise CommandExecutionError(
'\'{0}\' is not a valid URL or path'.format(link)
)
cmd.extend(['--find-links', link])
if no_index and (index_url or extra_index_url):
raise CommandExecutionError(
'\'no_index\' and (\'index_url\' or \'extra_index_url\') are '
'mutually exclusive.'
)
if index_url:
if not salt.utils.url.validate(index_url, VALID_PROTOS):
raise CommandExecutionError(
'\'{0}\' is not a valid URL'.format(index_url)
)
cmd.extend(['--index-url', index_url])
if extra_index_url:
if not salt.utils.url.validate(extra_index_url, VALID_PROTOS):
raise CommandExecutionError(
'\'{0}\' is not a valid URL'.format(extra_index_url)
)
cmd.extend(['--extra-index-url', extra_index_url])
if no_index:
cmd.append('--no-index')
if mirrors:
# https://github.com/pypa/pip/pull/2641/files#diff-3ef137fb9ffdd400f117a565cd94c188L216
if salt.utils.versions.compare(ver1=cur_version, oper='>=', ver2='7.0.0'):
raise CommandExecutionError(
'pip >= 7.0.0 does not support mirror argument:'
' use index_url and/or extra_index_url instead'
)
if isinstance(mirrors, six.string_types):
mirrors = [m.strip() for m in mirrors.split(',')]
cmd.append('--use-mirrors')
for mirror in mirrors:
if not mirror.startswith('http://'):
raise CommandExecutionError(
'\'{0}\' is not a valid URL'.format(mirror)
)
cmd.extend(['--mirrors', mirror])
if build:
cmd.extend(['--build', build])
if target:
cmd.extend(['--target', target])
if download:
cmd.extend(['--download', download])
if download_cache or cache_dir:
cmd.extend(['--cache-dir' if salt.utils.versions.compare(
ver1=cur_version, oper='>=', ver2='6.0'
) else '--download-cache', download_cache or cache_dir])
if source:
cmd.extend(['--source', source])
if upgrade:
cmd.append('--upgrade')
if force_reinstall:
cmd.append('--force-reinstall')
if ignore_installed:
cmd.append('--ignore-installed')
if exists_action:
if exists_action.lower() not in ('s', 'i', 'w', 'b'):
raise CommandExecutionError(
'The exists_action pip option only supports the values '
's, i, w, and b. \'{0}\' is not valid.'.format(exists_action)
)
cmd.extend(['--exists-action', exists_action])
if no_deps:
cmd.append('--no-deps')
if no_install:
cmd.append('--no-install')
if no_download:
cmd.append('--no-download')
if no_cache_dir:
cmd.append('--no-cache-dir')
if pre_releases:
# Check the locally installed pip version
pip_version = cur_version
# From pip v1.4 the --pre flag is available
if salt.utils.versions.compare(ver1=pip_version, oper='>=', ver2='1.4'):
cmd.append('--pre')
if cert:
cmd.extend(['--cert', cert])
if global_options:
if isinstance(global_options, six.string_types):
global_options = [go.strip() for go in global_options.split(',')]
for opt in global_options:
cmd.extend(['--global-option', opt])
if install_options:
if isinstance(install_options, six.string_types):
install_options = [io.strip() for io in install_options.split(',')]
for opt in install_options:
cmd.extend(['--install-option', opt])
if pkgs:
if not isinstance(pkgs, list):
try:
pkgs = [p.strip() for p in pkgs.split(',')]
except AttributeError:
pkgs = [p.strip() for p in six.text_type(pkgs).split(',')]
pkgs = salt.utils.data.stringify(salt.utils.data.decode_list(pkgs))
# It's possible we replaced version-range commas with semicolons so
# they would survive the previous line (in the pip.installed state).
# Put the commas back in while making sure the names are contained in
# quotes, this allows for proper version spec passing salt>=0.17.0
cmd.extend([p.replace(';', ',') for p in pkgs])
elif not any([requirements, editable]):
# Starting with pip 10.0.0, if no packages are specified in the
# command, it returns a retcode 1. So instead of running the command,
# just return the output without running pip.
return {'retcode': 0, 'stdout': 'No packages to install.'}
if editable:
egg_match = re.compile(r'(?:#|#.*?&)egg=([^&]*)')
if isinstance(editable, six.string_types):
editable = [e.strip() for e in editable.split(',')]
for entry in editable:
# Is the editable local?
if not (entry == '.' or entry.startswith(('file://', '/'))):
match = egg_match.search(entry)
if not match or not match.group(1):
# Missing #egg=theEggName
raise CommandExecutionError(
'You must specify an egg for this editable'
)
cmd.extend(['--editable', entry])
if allow_all_external:
cmd.append('--allow-all-external')
if allow_external:
if isinstance(allow_external, six.string_types):
allow_external = [p.strip() for p in allow_external.split(',')]
for pkg in allow_external:
cmd.extend(['--allow-external', pkg])
if allow_unverified:
if isinstance(allow_unverified, six.string_types):
allow_unverified = \
[p.strip() for p in allow_unverified.split(',')]
for pkg in allow_unverified:
cmd.extend(['--allow-unverified', pkg])
if process_dependency_links:
cmd.append('--process-dependency-links')
if trusted_host:
cmd.extend(['--trusted-host', trusted_host])
if extra_args:
# These are arguments from the latest version of pip that
# have not yet been implemented in salt
for arg in extra_args:
# It is a keyword argument
if isinstance(arg, dict):
# There will only ever be one item in this dictionary
key, val = arg.popitem()
# Don't allow any recursion into keyword arg definitions
# Don't allow multiple definitions of a keyword
if isinstance(val, (dict, list)):
raise TypeError("Too many levels in: {}".format(key))
# This is a a normal one-to-one keyword argument
cmd.extend([key, val])
# It is a positional argument, append it to the list
else:
cmd.append(arg)
cmd_kwargs = dict(saltenv=saltenv, use_vt=use_vt, runas=user)
if kwargs:
cmd_kwargs.update(kwargs)
if env_vars:
cmd_kwargs.setdefault('env', {}).update(_format_env_vars(env_vars))
try:
if cwd:
cmd_kwargs['cwd'] = cwd
if bin_env and os.path.isdir(bin_env):
cmd_kwargs.setdefault('env', {})['VIRTUAL_ENV'] = bin_env
logger.debug(
'TRY BLOCK: end of pip.install -- cmd: %s, cmd_kwargs: %s',
cmd, cmd_kwargs
)
return __salt__['cmd.run_all'](cmd, python_shell=False, **cmd_kwargs)
finally:
_clear_context(bin_env)
for tempdir in [cr for cr in cleanup_requirements if cr is not None]:
if os.path.isdir(tempdir):
shutil.rmtree(tempdir)
def uninstall(pkgs=None,
requirements=None,
bin_env=None,
log=None,
proxy=None,
timeout=None,
user=None,
cwd=None,
saltenv='base',
use_vt=False):
'''
Uninstall packages individually or from a pip requirements file
pkgs
comma separated list of packages to install
requirements
Path to requirements file
bin_env
Path to pip (or to a virtualenv). This can be used to specify the path
to the pip to use when more than one Python release is installed (e.g.
``/usr/bin/pip-2.7`` or ``/usr/bin/pip-2.6``. If a directory path is
specified, it is assumed to be a virtualenv.
log
Log file where a complete (maximum verbosity) record will be kept
proxy
Specify a proxy in the format ``user:passwd@proxy.server:port``. Note
that the ``user:password@`` is optional and required only if you are
behind an authenticated proxy. If you provide
``user@proxy.server:port`` then you will be prompted for a password.
timeout
Set the socket timeout (default 15 seconds)
user
The user under which to run pip
cwd
Directory from which to run pip
use_vt
Use VT terminal emulation (see output while installing)
CLI Example:
.. code-block:: bash
salt '*' pip.uninstall <package name>,<package2 name>
salt '*' pip.uninstall requirements=/path/to/requirements.txt
salt '*' pip.uninstall <package name> bin_env=/path/to/virtualenv
salt '*' pip.uninstall <package name> bin_env=/path/to/pip_bin
'''
cmd = _get_pip_bin(bin_env)
cmd.extend(['uninstall', '-y'])
cleanup_requirements, error = _process_requirements(
requirements=requirements, cmd=cmd, saltenv=saltenv, user=user,
cwd=cwd
)
if error:
return error
if log:
try:
# TODO make this check if writeable
os.path.exists(log)
except IOError:
raise IOError('\'{0}\' is not writeable'.format(log))
cmd.extend(['--log', log])
if proxy:
cmd.extend(['--proxy', proxy])
if timeout:
try:
if isinstance(timeout, float):
# Catch floating point input, exception will be caught in
# exception class below.
raise ValueError('Timeout cannot be a float')
int(timeout)
except ValueError:
raise ValueError(
'\'{0}\' is not a valid timeout, must be an integer'
.format(timeout)
)
cmd.extend(['--timeout', timeout])
if pkgs:
if isinstance(pkgs, six.string_types):
pkgs = [p.strip() for p in pkgs.split(',')]
if requirements:
for requirement in requirements:
with salt.utils.files.fopen(requirement) as rq_:
for req in rq_:
req = salt.utils.stringutils.to_unicode(req)
try:
req_pkg, _ = req.split('==')
if req_pkg in pkgs:
pkgs.remove(req_pkg)
except ValueError:
pass
cmd.extend(pkgs)
cmd_kwargs = dict(python_shell=False, runas=user,
cwd=cwd, saltenv=saltenv, use_vt=use_vt)
if bin_env and os.path.isdir(bin_env):
cmd_kwargs['env'] = {'VIRTUAL_ENV': bin_env}
try:
return __salt__['cmd.run_all'](cmd, **cmd_kwargs)
finally:
_clear_context(bin_env)
for requirement in cleanup_requirements:
if requirement:
try:
os.remove(requirement)
except OSError:
pass
def list_(prefix=None,
bin_env=None,
user=None,
cwd=None,
env_vars=None,
**kwargs):
'''
Filter list of installed apps from ``freeze`` and check to see if
``prefix`` exists in the list of packages installed.
.. note::
If the version of pip available is older than 8.0.3, the packages
``wheel``, ``setuptools``, and ``distribute`` will not be reported by
this function even if they are installed. Unlike :py:func:`pip.freeze
<salt.modules.pip.freeze>`, this function always reports the version of
pip which is installed.
CLI Example:
.. code-block:: bash
salt '*' pip.list salt
'''
packages = {}
if prefix is None or 'pip'.startswith(prefix):
packages['pip'] = version(bin_env)
for line in freeze(bin_env=bin_env,
user=user,
cwd=cwd,
env_vars=env_vars,
**kwargs):
if line.startswith('-f') or line.startswith('#'):
# ignore -f line as it contains --find-links directory
# ignore comment lines
continue
elif line.startswith('-e hg+not trust'):
# ignore hg + not trust problem
continue
elif line.startswith('-e'):
line = line.split('-e ')[1]
if '#egg=' in line:
version_, name = line.split('#egg=')
else:
if len(line.split('===')) >= 2:
name = line.split('===')[0]
version_ = line.split('===')[1]
elif len(line.split('==')) >= 2:
name = line.split('==')[0]
version_ = line.split('==')[1]
elif len(line.split('===')) >= 2:
name = line.split('===')[0]
version_ = line.split('===')[1]
elif len(line.split('==')) >= 2:
name = line.split('==')[0]
version_ = line.split('==')[1]
else:
logger.error('Can\'t parse line \'%s\'', line)
continue
if prefix:
if name.lower().startswith(prefix.lower()):
packages[name] = version_
else:
packages[name] = version_
return packages
def version(bin_env=None):
'''
.. versionadded:: 0.17.0
Returns the version of pip. Use ``bin_env`` to specify the path to a
virtualenv and get the version of pip in that virtualenv.
If unable to detect the pip version, returns ``None``.
CLI Example:
.. code-block:: bash
salt '*' pip.version
'''
contextkey = 'pip.version'
if bin_env is not None:
contextkey = '{0}.{1}'.format(contextkey, bin_env)
if contextkey in __context__:
return __context__[contextkey]
cmd = _get_pip_bin(bin_env)[:]
cmd.append('--version')
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
if ret['retcode']:
raise CommandNotFoundError('Could not find a `pip` binary')
try:
pip_version = re.match(r'^pip (\S+)', ret['stdout']).group(1)
except AttributeError:
pip_version = None
__context__[contextkey] = pip_version
return pip_version
def list_upgrades(bin_env=None,
user=None,
cwd=None):
'''
Check whether or not an upgrade is available for all packages
CLI Example:
.. code-block:: bash
salt '*' pip.list_upgrades
'''
cmd = _get_pip_bin(bin_env)
cmd.extend(['list', '--outdated'])
pip_version = version(bin_env)
# Pip started supporting the ability to output json starting with 9.0.0
min_version = '9.0'
if salt.utils.versions.compare(ver1=pip_version,
oper='>=',
ver2=min_version):
cmd.append('--format=json')
cmd_kwargs = dict(cwd=cwd, runas=user)
if bin_env and os.path.isdir(bin_env):
cmd_kwargs['env'] = {'VIRTUAL_ENV': bin_env}
result = __salt__['cmd.run_all'](cmd, **cmd_kwargs)
if result['retcode']:
raise CommandExecutionError(result['stderr'], info=result)
packages = {}
# Pip started supporting the ability to output json starting with 9.0.0
# Older versions will have to parse stdout
if salt.utils.versions.compare(ver1=pip_version, oper='<', ver2='9.0.0'):
# Pip versions < 8.0.0 had a different output format
# Sample data:
# pip (Current: 7.1.2 Latest: 10.0.1 [wheel])
# psutil (Current: 5.2.2 Latest: 5.4.5 [wheel])
# pyasn1 (Current: 0.2.3 Latest: 0.4.2 [wheel])
# pycparser (Current: 2.17 Latest: 2.18 [sdist])
if salt.utils.versions.compare(ver1=pip_version, oper='<', ver2='8.0.0'):
logger.debug('pip module: Old output format')
pat = re.compile(r'(\S*)\s+\(.*Latest:\s+(.*)\)')
# New output format for version 8.0.0+
# Sample data:
# pip (8.0.0) - Latest: 10.0.1 [wheel]
# psutil (5.2.2) - Latest: 5.4.5 [wheel]
# pyasn1 (0.2.3) - Latest: 0.4.2 [wheel]
# pycparser (2.17) - Latest: 2.18 [sdist]
else:
logger.debug('pip module: New output format')
pat = re.compile(r'(\S*)\s+\(.*\)\s+-\s+Latest:\s+(.*)')
for line in result['stdout'].splitlines():
match = pat.search(line)
if match:
name, version_ = match.groups()
else:
logger.error('Can\'t parse line \'%s\'', line)
continue
packages[name] = version_
else:
logger.debug('pip module: JSON output format')
try:
pkgs = salt.utils.json.loads(result['stdout'], strict=False)
except ValueError:
raise CommandExecutionError('Invalid JSON', info=result)
for pkg in pkgs:
packages[pkg['name']] = '{0} [{1}]'.format(pkg['latest_version'],
pkg['latest_filetype'])
return packages
def is_installed(pkgname=None,
bin_env=None,
user=None,
cwd=None):
'''
.. versionadded:: 2018.3.0
Filter list of installed apps from ``freeze`` and return True or False if
``pkgname`` exists in the list of packages installed.
.. note::
If the version of pip available is older than 8.0.3, the packages
wheel, setuptools, and distribute will not be reported by this function
even if they are installed. Unlike :py:func:`pip.freeze
<salt.modules.pip.freeze>`, this function always reports the version of
pip which is installed.
CLI Example:
.. code-block:: bash
salt '*' pip.is_installed salt
'''
for line in freeze(bin_env=bin_env, user=user, cwd=cwd):
if line.startswith('-f') or line.startswith('#'):
# ignore -f line as it contains --find-links directory
# ignore comment lines
continue
elif line.startswith('-e hg+not trust'):
# ignore hg + not trust problem
continue
elif line.startswith('-e'):
line = line.split('-e ')[1]
version_, name = line.split('#egg=')
elif len(line.split('===')) >= 2:
name = line.split('===')[0]
version_ = line.split('===')[1]
elif len(line.split('==')) >= 2:
name = line.split('==')[0]
version_ = line.split('==')[1]
else:
logger.error('Can\'t parse line \'%s\'', line)
continue
if pkgname:
if pkgname == name.lower():
return True
return False
def upgrade_available(pkg,
bin_env=None,
user=None,
cwd=None):
'''
.. versionadded:: 2015.5.0
Check whether or not an upgrade is available for a given package
CLI Example:
.. code-block:: bash
salt '*' pip.upgrade_available <package name>
'''
return pkg in list_upgrades(bin_env=bin_env, user=user, cwd=cwd)
def upgrade(bin_env=None,
user=None,
cwd=None,
use_vt=False):
'''
.. versionadded:: 2015.5.0
Upgrades outdated pip packages.
.. note::
On Windows you can't update salt from pip using salt, so salt will be
skipped
Returns a dict containing the changes.
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
CLI Example:
.. code-block:: bash
salt '*' pip.upgrade
'''
ret = {'changes': {},
'result': True,
'comment': '',
}
cmd = _get_pip_bin(bin_env)
cmd.extend(['install', '-U'])
old = list_(bin_env=bin_env, user=user, cwd=cwd)
cmd_kwargs = dict(cwd=cwd, use_vt=use_vt)
if bin_env and os.path.isdir(bin_env):
cmd_kwargs['env'] = {'VIRTUAL_ENV': bin_env}
errors = False
for pkg in list_upgrades(bin_env=bin_env, user=user, cwd=cwd):
if pkg == 'salt':
if salt.utils.platform.is_windows():
continue
result = __salt__['cmd.run_all'](cmd + [pkg], **cmd_kwargs)
if result['retcode'] != 0:
errors = True
if 'stderr' in result:
ret['comment'] += result['stderr']
if errors:
ret['result'] = False
_clear_context(bin_env)
new = list_(bin_env=bin_env, user=user, cwd=cwd)
ret['changes'] = salt.utils.data.compare_dicts(old, new)
return ret
def list_all_versions(pkg,
bin_env=None,
include_alpha=False,
include_beta=False,
include_rc=False,
user=None,
cwd=None,
index_url=None,
extra_index_url=None):
'''
.. versionadded:: 2017.7.3
List all available versions of a pip package
pkg
The package to check
bin_env
Path to pip (or to a virtualenv). This can be used to specify the path
to the pip to use when more than one Python release is installed (e.g.
``/usr/bin/pip-2.7`` or ``/usr/bin/pip-2.6``. If a directory path is
specified, it is assumed to be a virtualenv.
include_alpha
Include alpha versions in the list
include_beta
Include beta versions in the list
include_rc
Include release candidates versions in the list
user
The user under which to run pip
cwd
Directory from which to run pip
index_url
Base URL of Python Package Index
.. versionadded:: 2019.2.0
extra_index_url
Additional URL of Python Package Index
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' pip.list_all_versions <package name>
'''
cmd = _get_pip_bin(bin_env)
cmd.extend(['install', '{0}==versions'.format(pkg)])
if index_url:
if not salt.utils.url.validate(index_url, VALID_PROTOS):
raise CommandExecutionError(
'\'{0}\' is not a valid URL'.format(index_url)
)
cmd.extend(['--index-url', index_url])
if extra_index_url:
if not salt.utils.url.validate(extra_index_url, VALID_PROTOS):
raise CommandExecutionError(
'\'{0}\' is not a valid URL'.format(extra_index_url)
)
cmd.extend(['--extra-index-url', extra_index_url])
cmd_kwargs = dict(cwd=cwd, runas=user, output_loglevel='quiet', redirect_stderr=True)
if bin_env and os.path.isdir(bin_env):
cmd_kwargs['env'] = {'VIRTUAL_ENV': bin_env}
result = __salt__['cmd.run_all'](cmd, **cmd_kwargs)
filtered = []
if not include_alpha:
filtered.append('a')
if not include_beta:
filtered.append('b')
if not include_rc:
filtered.append('rc')
if filtered:
excludes = re.compile(r'^((?!{0}).)*$'.format('|'.join(filtered)))
else:
excludes = re.compile(r'')
versions = []
for line in result['stdout'].splitlines():
match = re.search(r'\s*Could not find a version.* \(from versions: (.*)\)', line)
if match:
versions = [v for v in match.group(1).split(', ') if v and excludes.match(v)]
versions.sort(key=pkg_resources.parse_version)
break
if not versions:
return None
return versions
|
saltstack/salt
|
salt/modules/pip.py
|
list_
|
python
|
def list_(prefix=None,
bin_env=None,
user=None,
cwd=None,
env_vars=None,
**kwargs):
'''
Filter list of installed apps from ``freeze`` and check to see if
``prefix`` exists in the list of packages installed.
.. note::
If the version of pip available is older than 8.0.3, the packages
``wheel``, ``setuptools``, and ``distribute`` will not be reported by
this function even if they are installed. Unlike :py:func:`pip.freeze
<salt.modules.pip.freeze>`, this function always reports the version of
pip which is installed.
CLI Example:
.. code-block:: bash
salt '*' pip.list salt
'''
packages = {}
if prefix is None or 'pip'.startswith(prefix):
packages['pip'] = version(bin_env)
for line in freeze(bin_env=bin_env,
user=user,
cwd=cwd,
env_vars=env_vars,
**kwargs):
if line.startswith('-f') or line.startswith('#'):
# ignore -f line as it contains --find-links directory
# ignore comment lines
continue
elif line.startswith('-e hg+not trust'):
# ignore hg + not trust problem
continue
elif line.startswith('-e'):
line = line.split('-e ')[1]
if '#egg=' in line:
version_, name = line.split('#egg=')
else:
if len(line.split('===')) >= 2:
name = line.split('===')[0]
version_ = line.split('===')[1]
elif len(line.split('==')) >= 2:
name = line.split('==')[0]
version_ = line.split('==')[1]
elif len(line.split('===')) >= 2:
name = line.split('===')[0]
version_ = line.split('===')[1]
elif len(line.split('==')) >= 2:
name = line.split('==')[0]
version_ = line.split('==')[1]
else:
logger.error('Can\'t parse line \'%s\'', line)
continue
if prefix:
if name.lower().startswith(prefix.lower()):
packages[name] = version_
else:
packages[name] = version_
return packages
|
Filter list of installed apps from ``freeze`` and check to see if
``prefix`` exists in the list of packages installed.
.. note::
If the version of pip available is older than 8.0.3, the packages
``wheel``, ``setuptools``, and ``distribute`` will not be reported by
this function even if they are installed. Unlike :py:func:`pip.freeze
<salt.modules.pip.freeze>`, this function always reports the version of
pip which is installed.
CLI Example:
.. code-block:: bash
salt '*' pip.list salt
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/pip.py#L1152-L1220
|
[
"def version(bin_env=None):\n '''\n .. versionadded:: 0.17.0\n\n Returns the version of pip. Use ``bin_env`` to specify the path to a\n virtualenv and get the version of pip in that virtualenv.\n\n If unable to detect the pip version, returns ``None``.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' pip.version\n '''\n contextkey = 'pip.version'\n if bin_env is not None:\n contextkey = '{0}.{1}'.format(contextkey, bin_env)\n\n if contextkey in __context__:\n return __context__[contextkey]\n\n cmd = _get_pip_bin(bin_env)[:]\n cmd.append('--version')\n\n ret = __salt__['cmd.run_all'](cmd, python_shell=False)\n if ret['retcode']:\n raise CommandNotFoundError('Could not find a `pip` binary')\n\n try:\n pip_version = re.match(r'^pip (\\S+)', ret['stdout']).group(1)\n except AttributeError:\n pip_version = None\n\n __context__[contextkey] = pip_version\n return pip_version\n",
"def freeze(bin_env=None,\n user=None,\n cwd=None,\n use_vt=False,\n env_vars=None,\n **kwargs):\n '''\n Return a list of installed packages either globally or in the specified\n virtualenv\n\n bin_env\n Path to pip (or to a virtualenv). This can be used to specify the path\n to the pip to use when more than one Python release is installed (e.g.\n ``/usr/bin/pip-2.7`` or ``/usr/bin/pip-2.6``. If a directory path is\n specified, it is assumed to be a virtualenv.\n\n user\n The user under which to run pip\n\n cwd\n Directory from which to run pip\n\n .. note::\n If the version of pip available is older than 8.0.3, the list will not\n include the packages ``pip``, ``wheel``, ``setuptools``, or\n ``distribute`` even if they are installed.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' pip.freeze bin_env=/home/code/path/to/virtualenv\n '''\n cmd = _get_pip_bin(bin_env)\n cmd.append('freeze')\n\n # Include pip, setuptools, distribute, wheel\n min_version = '8.0.3'\n cur_version = version(bin_env)\n if salt.utils.versions.compare(ver1=cur_version, oper='<', ver2=min_version):\n logger.warning(\n 'The version of pip installed is %s, which is older than %s. '\n 'The packages pip, wheel, setuptools, and distribute will not be '\n 'included in the output of pip.freeze', cur_version, min_version\n )\n else:\n cmd.append('--all')\n\n cmd_kwargs = dict(runas=user, cwd=cwd, use_vt=use_vt, python_shell=False)\n if kwargs:\n cmd_kwargs.update(**kwargs)\n if bin_env and os.path.isdir(bin_env):\n cmd_kwargs['env'] = {'VIRTUAL_ENV': bin_env}\n if env_vars:\n cmd_kwargs.setdefault('env', {}).update(_format_env_vars(env_vars))\n result = __salt__['cmd.run_all'](cmd, **cmd_kwargs)\n\n if result['retcode']:\n raise CommandExecutionError(result['stderr'], info=result)\n\n return result['stdout'].splitlines()\n"
] |
# -*- coding: utf-8 -*-
r'''
Install Python packages with pip to either the system or a virtualenv
Windows Support
===============
.. versionadded:: 2014.7.4
Salt now uses a portable python. As a result the entire pip module is now
functional on the salt installation itself. You can pip install dependencies
for your custom modules. You can even upgrade salt itself using pip. For this
to work properly, you must specify the Current Working Directory (``cwd``) and
the Pip Binary (``bin_env``) salt should use. The variable ``pip_bin`` can be
either a virtualenv path or the path to the pip binary itself.
For example, the following command will list all software installed using pip
to your current salt environment:
.. code-block:: bat
salt <minion> pip.list cwd='C:\salt\bin\Scripts' bin_env='C:\salt\bin\Scripts\pip.exe'
Specifying the ``cwd`` and ``bin_env`` options ensures you're modifying the
salt environment. If these are omitted, it will default to the local
installation of python. If python is not installed locally it will fail saying
it couldn't find pip.
State File Support
------------------
This functionality works in states as well. If you need to pip install colorama
with a state, for example, the following will work:
.. code-block:: yaml
install_colorama:
pip.installed:
- name: colorama
- cwd: 'C:\salt\bin\scripts'
- bin_env: 'C:\salt\bin\scripts\pip.exe'
- upgrade: True
Upgrading Salt using Pip
------------------------
You can now update salt using pip to any version from the 2014.7 branch
forward. Previous version require recompiling some of the dependencies which is
painful in windows.
To do this you just use pip with git to update to the version you want and then
restart the service. Here is a sample state file that upgrades salt to the head
of the 2015.5 branch:
.. code-block:: yaml
install_salt:
pip.installed:
- cwd: 'C:\salt\bin\scripts'
- bin_env: 'C:\salt\bin\scripts\pip.exe'
- editable: git+https://github.com/saltstack/salt@2015.5#egg=salt
- upgrade: True
restart_service:
service.running:
- name: salt-minion
- enable: True
- watch:
- pip: install_salt
.. note::
If you're having problems, you might try doubling the back slashes. For
example, cwd: 'C:\\salt\\bin\\scripts'. Sometimes python thinks the single
back slash is an escape character.
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import logging
import os
try:
import pkg_resources
except ImportError:
pkg_resources = None
import re
import shutil
import sys
import tempfile
# Import Salt libs
import salt.utils.data
import salt.utils.files
import salt.utils.json
import salt.utils.locales
import salt.utils.platform
import salt.utils.stringutils
import salt.utils.url
import salt.utils.versions
from salt.ext import six
from salt.exceptions import CommandExecutionError, CommandNotFoundError
# This needs to be named logger so we don't shadow it in pip.install
logger = logging.getLogger(__name__) # pylint: disable=C0103
# Don't shadow built-in's.
__func_alias__ = {
'list_': 'list'
}
VALID_PROTOS = ['http', 'https', 'ftp', 'file']
rex_pip_chain_read = re.compile(r'-r\s(.*)\n?', re.MULTILINE)
def __virtual__():
'''
There is no way to verify that pip is installed without inspecting the
entire filesystem. If it's not installed in a conventional location, the
user is required to provide the location of pip each time it is used.
'''
if pkg_resources is None:
ret = False, 'Package dependency "pkg_resource" is missing'
else:
ret = 'pip'
return ret
def _clear_context(bin_env=None):
'''
Remove the cached pip version
'''
contextkey = 'pip.version'
if bin_env is not None:
contextkey = '{0}.{1}'.format(contextkey, bin_env)
__context__.pop(contextkey, None)
def _get_pip_bin(bin_env):
'''
Locate the pip binary, either from `bin_env` as a virtualenv, as the
executable itself, or from searching conventional filesystem locations
'''
if not bin_env:
logger.debug('pip: Using pip from currently-running Python')
return [os.path.normpath(sys.executable), '-m', 'pip']
python_bin = 'python.exe' if salt.utils.platform.is_windows() else 'python'
def _search_paths(*basedirs):
ret = []
for path in basedirs:
ret.extend([
os.path.join(path, python_bin),
os.path.join(path, 'bin', python_bin),
os.path.join(path, 'Scripts', python_bin)
])
return ret
# try to get python bin from virtualenv (i.e. bin_env)
if os.path.isdir(bin_env):
for bin_path in _search_paths(bin_env):
if os.path.isfile(bin_path):
if os.access(bin_path, os.X_OK):
logger.debug('pip: Found python binary: %s', bin_path)
return [os.path.normpath(bin_path), '-m', 'pip']
else:
logger.debug(
'pip: Found python binary by name but it is not '
'executable: %s', bin_path
)
raise CommandNotFoundError(
'Could not find a pip binary in virtualenv {0}'.format(bin_env)
)
# bin_env is the python or pip binary
elif os.access(bin_env, os.X_OK):
if os.path.isfile(bin_env):
# If the python binary was passed, return it
if 'python' in os.path.basename(bin_env):
return [os.path.normpath(bin_env), '-m', 'pip']
# We have been passed a pip binary, use the pip binary.
return [os.path.normpath(bin_env)]
raise CommandExecutionError(
'Could not find a pip binary within {0}'.format(bin_env)
)
else:
raise CommandNotFoundError(
'Access denied to {0}, could not find a pip binary'.format(bin_env)
)
def _get_cached_requirements(requirements, saltenv):
'''
Get the location of a cached requirements file; caching if necessary.
'''
req_file, senv = salt.utils.url.parse(requirements)
if senv:
saltenv = senv
if req_file not in __salt__['cp.list_master'](saltenv):
# Requirements file does not exist in the given saltenv.
return False
cached_requirements = __salt__['cp.is_cached'](
requirements, saltenv
)
if not cached_requirements:
# It's not cached, let's cache it.
cached_requirements = __salt__['cp.cache_file'](
requirements, saltenv
)
# Check if the master version has changed.
if __salt__['cp.hash_file'](requirements, saltenv) != \
__salt__['cp.hash_file'](cached_requirements, saltenv):
cached_requirements = __salt__['cp.cache_file'](
requirements, saltenv
)
return cached_requirements
def _get_env_activate(bin_env):
'''
Return the path to the activate binary
'''
if not bin_env:
raise CommandNotFoundError('Could not find a `activate` binary')
if os.path.isdir(bin_env):
if salt.utils.platform.is_windows():
activate_bin = os.path.join(bin_env, 'Scripts', 'activate.bat')
else:
activate_bin = os.path.join(bin_env, 'bin', 'activate')
if os.path.isfile(activate_bin):
return activate_bin
raise CommandNotFoundError('Could not find a `activate` binary')
def _find_req(link):
logger.info('_find_req -- link = %s', link)
with salt.utils.files.fopen(link) as fh_link:
child_links = rex_pip_chain_read.findall(
salt.utils.stringutils.to_unicode(fh_link.read())
)
base_path = os.path.dirname(link)
child_links = [os.path.join(base_path, d) for d in child_links]
return child_links
def _resolve_requirements_chain(requirements):
'''
Return an array of requirements file paths that can be used to complete
the no_chown==False && user != None conundrum
'''
chain = []
if isinstance(requirements, six.string_types):
requirements = [requirements]
for req_file in requirements:
chain.append(req_file)
chain.extend(_resolve_requirements_chain(_find_req(req_file)))
return chain
def _process_requirements(requirements, cmd, cwd, saltenv, user):
'''
Process the requirements argument
'''
cleanup_requirements = []
if requirements is not None:
if isinstance(requirements, six.string_types):
requirements = [r.strip() for r in requirements.split(',')]
elif not isinstance(requirements, list):
raise TypeError('requirements must be a string or list')
treq = None
for requirement in requirements:
logger.debug('TREQ IS: %s', treq)
if requirement.startswith('salt://'):
cached_requirements = _get_cached_requirements(
requirement, saltenv
)
if not cached_requirements:
ret = {'result': False,
'comment': 'pip requirements file \'{0}\' not found'
.format(requirement)}
return None, ret
requirement = cached_requirements
if user:
# Need to make a temporary copy since the user will, most
# likely, not have the right permissions to read the file
if not treq:
treq = tempfile.mkdtemp()
__salt__['file.chown'](treq, user, None)
# In Windows, just being owner of a file isn't enough. You also
# need permissions
if salt.utils.platform.is_windows():
__utils__['dacl.set_permissions'](
obj_name=treq,
principal=user,
permissions='read_execute')
current_directory = None
if not current_directory:
current_directory = os.path.abspath(os.curdir)
logger.info('_process_requirements from directory, '
'%s -- requirement: %s', cwd, requirement)
if cwd is None:
r = requirement
c = cwd
requirement_abspath = os.path.abspath(requirement)
cwd = os.path.dirname(requirement_abspath)
requirement = os.path.basename(requirement)
logger.debug('\n\tcwd: %s -> %s\n\trequirement: %s -> %s\n',
c, cwd, r, requirement
)
os.chdir(cwd)
reqs = _resolve_requirements_chain(requirement)
os.chdir(current_directory)
logger.info('request files: %s', reqs)
for req_file in reqs:
if not os.path.isabs(req_file):
req_file = os.path.join(cwd, req_file)
logger.debug('TREQ N CWD: %s -- %s -- for %s', treq, cwd, req_file)
target_path = os.path.join(treq, os.path.basename(req_file))
logger.debug('S: %s', req_file)
logger.debug('T: %s', target_path)
target_base = os.path.dirname(target_path)
if not os.path.exists(target_base):
os.makedirs(target_base, mode=0o755)
__salt__['file.chown'](target_base, user, None)
if not os.path.exists(target_path):
logger.debug(
'Copying %s to %s', req_file, target_path
)
__salt__['file.copy'](req_file, target_path)
logger.debug(
'Changing ownership of requirements file \'%s\' to '
'user \'%s\'', target_path, user
)
__salt__['file.chown'](target_path, user, None)
req_args = os.path.join(treq, requirement) if treq else requirement
cmd.extend(['--requirement', req_args])
cleanup_requirements.append(treq)
logger.debug('CLEANUP_REQUIREMENTS: %s', cleanup_requirements)
return cleanup_requirements, None
def _format_env_vars(env_vars):
ret = {}
if env_vars:
if isinstance(env_vars, dict):
for key, val in six.iteritems(env_vars):
if not isinstance(key, six.string_types):
key = str(key) # future lint: disable=blacklisted-function
if not isinstance(val, six.string_types):
val = str(val) # future lint: disable=blacklisted-function
ret[key] = val
else:
raise CommandExecutionError(
'env_vars {0} is not a dictionary'.format(env_vars))
return ret
def install(pkgs=None, # pylint: disable=R0912,R0913,R0914
requirements=None,
bin_env=None,
use_wheel=False,
no_use_wheel=False,
log=None,
proxy=None,
timeout=None,
editable=None,
find_links=None,
index_url=None,
extra_index_url=None,
no_index=False,
mirrors=None,
build=None,
target=None,
download=None,
download_cache=None,
source=None,
upgrade=False,
force_reinstall=False,
ignore_installed=False,
exists_action=None,
no_deps=False,
no_install=False,
no_download=False,
global_options=None,
install_options=None,
user=None,
cwd=None,
pre_releases=False,
cert=None,
allow_all_external=False,
allow_external=None,
allow_unverified=None,
process_dependency_links=False,
saltenv='base',
env_vars=None,
use_vt=False,
trusted_host=None,
no_cache_dir=False,
cache_dir=None,
no_binary=None,
extra_args=None,
**kwargs):
'''
Install packages with pip
Install packages individually or from a pip requirements file. Install
packages globally or to a virtualenv.
pkgs
Comma separated list of packages to install
requirements
Path to requirements
bin_env
Path to pip (or to a virtualenv). This can be used to specify the path
to the pip to use when more than one Python release is installed (e.g.
``/usr/bin/pip-2.7`` or ``/usr/bin/pip-2.6``. If a directory path is
specified, it is assumed to be a virtualenv.
.. note::
For Windows, if the pip module is being used to upgrade the pip
package, bin_env should be the path to the virtualenv or to the
python binary that should be used. The pip command is unable to
upgrade itself in Windows.
use_wheel
Prefer wheel archives (requires pip>=1.4)
no_use_wheel
Force to not use wheel archives (requires pip>=1.4,<10.0.0)
no_binary
Force to not use binary packages (requires pip >= 7.0.0)
Accepts either :all: to disable all binary packages, :none: to empty the set,
or one or more package names with commas between them
log
Log file where a complete (maximum verbosity) record will be kept
proxy
Specify a proxy in the form ``user:passwd@proxy.server:port``. Note
that the ``user:password@`` is optional and required only if you are
behind an authenticated proxy. If you provide
``user@proxy.server:port`` then you will be prompted for a password.
timeout
Set the socket timeout (default 15 seconds)
editable
install something editable (e.g.
``git+https://github.com/worldcompany/djangoembed.git#egg=djangoembed``)
find_links
URL to search for packages
index_url
Base URL of Python Package Index
extra_index_url
Extra URLs of package indexes to use in addition to ``index_url``
no_index
Ignore package index
mirrors
Specific mirror URL(s) to query (automatically adds --use-mirrors)
.. warning::
This option has been deprecated and removed in pip version 7.0.0.
Please use ``index_url`` and/or ``extra_index_url`` instead.
build
Unpack packages into ``build`` dir
target
Install packages into ``target`` dir
download
Download packages into ``download`` instead of installing them
download_cache | cache_dir
Cache downloaded packages in ``download_cache`` or ``cache_dir`` dir
source
Check out ``editable`` packages into ``source`` dir
upgrade
Upgrade all packages to the newest available version
force_reinstall
When upgrading, reinstall all packages even if they are already
up-to-date.
ignore_installed
Ignore the installed packages (reinstalling instead)
exists_action
Default action when a path already exists: (s)witch, (i)gnore, (w)ipe,
(b)ackup
no_deps
Ignore package dependencies
no_install
Download and unpack all packages, but don't actually install them
no_download
Don't download any packages, just install the ones already downloaded
(completes an install run with ``--no-install``)
install_options
Extra arguments to be supplied to the setup.py install command (e.g.
like ``--install-option='--install-scripts=/usr/local/bin'``). Use
multiple --install-option options to pass multiple options to setup.py
install. If you are using an option with a directory path, be sure to
use absolute path.
global_options
Extra global options to be supplied to the setup.py call before the
install command.
user
The user under which to run pip
cwd
Directory from which to run pip
pre_releases
Include pre-releases in the available versions
cert
Provide a path to an alternate CA bundle
allow_all_external
Allow the installation of all externally hosted files
allow_external
Allow the installation of externally hosted files (comma separated
list)
allow_unverified
Allow the installation of insecure and unverifiable files (comma
separated list)
process_dependency_links
Enable the processing of dependency links
env_vars
Set environment variables that some builds will depend on. For example,
a Python C-module may have a Makefile that needs INCLUDE_PATH set to
pick up a header file while compiling. This must be in the form of a
dictionary or a mapping.
Example:
.. code-block:: bash
salt '*' pip.install django_app env_vars="{'CUSTOM_PATH': '/opt/django_app'}"
trusted_host
Mark this host as trusted, even though it does not have valid or any
HTTPS.
use_vt
Use VT terminal emulation (see output while installing)
no_cache_dir
Disable the cache.
extra_args
pip keyword and positional arguments not yet implemented in salt
.. code-block:: yaml
salt '*' pip.install pandas extra_args="[{'--latest-pip-kwarg':'param'}, '--latest-pip-arg']"
.. warning::
If unsupported options are passed here that are not supported in a
minion's version of pip, a `No such option error` will be thrown.
Will be translated into the following pip command:
.. code-block:: bash
pip install pandas --latest-pip-kwarg param --latest-pip-arg
CLI Example:
.. code-block:: bash
salt '*' pip.install <package name>,<package2 name>
salt '*' pip.install requirements=/path/to/requirements.txt
salt '*' pip.install <package name> bin_env=/path/to/virtualenv
salt '*' pip.install <package name> bin_env=/path/to/pip_bin
Complicated CLI example::
salt '*' pip.install markdown,django \
editable=git+https://github.com/worldcompany/djangoembed.git#egg=djangoembed upgrade=True no_deps=True
'''
cmd = _get_pip_bin(bin_env)
cmd.append('install')
cleanup_requirements, error = _process_requirements(
requirements=requirements,
cmd=cmd,
cwd=cwd,
saltenv=saltenv,
user=user
)
if error:
return error
cur_version = version(bin_env)
if use_wheel:
min_version = '1.4'
max_version = '9.0.3'
too_low = salt.utils.versions.compare(ver1=cur_version, oper='<', ver2=min_version)
too_high = salt.utils.versions.compare(ver1=cur_version, oper='>', ver2=max_version)
if too_low or too_high:
logger.error(
'The --use-wheel option is only supported in pip between %s and '
'%s. The version of pip detected is %s. This option '
'will be ignored.', min_version, max_version, cur_version
)
else:
cmd.append('--use-wheel')
if no_use_wheel:
min_version = '1.4'
max_version = '9.0.3'
too_low = salt.utils.versions.compare(ver1=cur_version, oper='<', ver2=min_version)
too_high = salt.utils.versions.compare(ver1=cur_version, oper='>', ver2=max_version)
if too_low or too_high:
logger.error(
'The --no-use-wheel option is only supported in pip between %s and '
'%s. The version of pip detected is %s. This option '
'will be ignored.', min_version, max_version, cur_version
)
else:
cmd.append('--no-use-wheel')
if no_binary:
min_version = '7.0.0'
too_low = salt.utils.versions.compare(ver1=cur_version, oper='<', ver2=min_version)
if too_low:
logger.error(
'The --no-binary option is only supported in pip %s and '
'newer. The version of pip detected is %s. This option '
'will be ignored.', min_version, cur_version
)
else:
if isinstance(no_binary, list):
no_binary = ','.join(no_binary)
cmd.extend(['--no-binary', no_binary])
if log:
if os.path.isdir(log):
raise IOError(
'\'{0}\' is a directory. Use --log path_to_file'.format(log))
elif not os.access(log, os.W_OK):
raise IOError('\'{0}\' is not writeable'.format(log))
cmd.extend(['--log', log])
if proxy:
cmd.extend(['--proxy', proxy])
if timeout:
try:
if isinstance(timeout, float):
# Catch floating point input, exception will be caught in
# exception class below.
raise ValueError('Timeout cannot be a float')
int(timeout)
except ValueError:
raise ValueError(
'\'{0}\' is not a valid timeout, must be an integer'
.format(timeout)
)
cmd.extend(['--timeout', timeout])
if find_links:
if isinstance(find_links, six.string_types):
find_links = [l.strip() for l in find_links.split(',')]
for link in find_links:
if not (salt.utils.url.validate(link, VALID_PROTOS) or os.path.exists(link)):
raise CommandExecutionError(
'\'{0}\' is not a valid URL or path'.format(link)
)
cmd.extend(['--find-links', link])
if no_index and (index_url or extra_index_url):
raise CommandExecutionError(
'\'no_index\' and (\'index_url\' or \'extra_index_url\') are '
'mutually exclusive.'
)
if index_url:
if not salt.utils.url.validate(index_url, VALID_PROTOS):
raise CommandExecutionError(
'\'{0}\' is not a valid URL'.format(index_url)
)
cmd.extend(['--index-url', index_url])
if extra_index_url:
if not salt.utils.url.validate(extra_index_url, VALID_PROTOS):
raise CommandExecutionError(
'\'{0}\' is not a valid URL'.format(extra_index_url)
)
cmd.extend(['--extra-index-url', extra_index_url])
if no_index:
cmd.append('--no-index')
if mirrors:
# https://github.com/pypa/pip/pull/2641/files#diff-3ef137fb9ffdd400f117a565cd94c188L216
if salt.utils.versions.compare(ver1=cur_version, oper='>=', ver2='7.0.0'):
raise CommandExecutionError(
'pip >= 7.0.0 does not support mirror argument:'
' use index_url and/or extra_index_url instead'
)
if isinstance(mirrors, six.string_types):
mirrors = [m.strip() for m in mirrors.split(',')]
cmd.append('--use-mirrors')
for mirror in mirrors:
if not mirror.startswith('http://'):
raise CommandExecutionError(
'\'{0}\' is not a valid URL'.format(mirror)
)
cmd.extend(['--mirrors', mirror])
if build:
cmd.extend(['--build', build])
if target:
cmd.extend(['--target', target])
if download:
cmd.extend(['--download', download])
if download_cache or cache_dir:
cmd.extend(['--cache-dir' if salt.utils.versions.compare(
ver1=cur_version, oper='>=', ver2='6.0'
) else '--download-cache', download_cache or cache_dir])
if source:
cmd.extend(['--source', source])
if upgrade:
cmd.append('--upgrade')
if force_reinstall:
cmd.append('--force-reinstall')
if ignore_installed:
cmd.append('--ignore-installed')
if exists_action:
if exists_action.lower() not in ('s', 'i', 'w', 'b'):
raise CommandExecutionError(
'The exists_action pip option only supports the values '
's, i, w, and b. \'{0}\' is not valid.'.format(exists_action)
)
cmd.extend(['--exists-action', exists_action])
if no_deps:
cmd.append('--no-deps')
if no_install:
cmd.append('--no-install')
if no_download:
cmd.append('--no-download')
if no_cache_dir:
cmd.append('--no-cache-dir')
if pre_releases:
# Check the locally installed pip version
pip_version = cur_version
# From pip v1.4 the --pre flag is available
if salt.utils.versions.compare(ver1=pip_version, oper='>=', ver2='1.4'):
cmd.append('--pre')
if cert:
cmd.extend(['--cert', cert])
if global_options:
if isinstance(global_options, six.string_types):
global_options = [go.strip() for go in global_options.split(',')]
for opt in global_options:
cmd.extend(['--global-option', opt])
if install_options:
if isinstance(install_options, six.string_types):
install_options = [io.strip() for io in install_options.split(',')]
for opt in install_options:
cmd.extend(['--install-option', opt])
if pkgs:
if not isinstance(pkgs, list):
try:
pkgs = [p.strip() for p in pkgs.split(',')]
except AttributeError:
pkgs = [p.strip() for p in six.text_type(pkgs).split(',')]
pkgs = salt.utils.data.stringify(salt.utils.data.decode_list(pkgs))
# It's possible we replaced version-range commas with semicolons so
# they would survive the previous line (in the pip.installed state).
# Put the commas back in while making sure the names are contained in
# quotes, this allows for proper version spec passing salt>=0.17.0
cmd.extend([p.replace(';', ',') for p in pkgs])
elif not any([requirements, editable]):
# Starting with pip 10.0.0, if no packages are specified in the
# command, it returns a retcode 1. So instead of running the command,
# just return the output without running pip.
return {'retcode': 0, 'stdout': 'No packages to install.'}
if editable:
egg_match = re.compile(r'(?:#|#.*?&)egg=([^&]*)')
if isinstance(editable, six.string_types):
editable = [e.strip() for e in editable.split(',')]
for entry in editable:
# Is the editable local?
if not (entry == '.' or entry.startswith(('file://', '/'))):
match = egg_match.search(entry)
if not match or not match.group(1):
# Missing #egg=theEggName
raise CommandExecutionError(
'You must specify an egg for this editable'
)
cmd.extend(['--editable', entry])
if allow_all_external:
cmd.append('--allow-all-external')
if allow_external:
if isinstance(allow_external, six.string_types):
allow_external = [p.strip() for p in allow_external.split(',')]
for pkg in allow_external:
cmd.extend(['--allow-external', pkg])
if allow_unverified:
if isinstance(allow_unverified, six.string_types):
allow_unverified = \
[p.strip() for p in allow_unverified.split(',')]
for pkg in allow_unverified:
cmd.extend(['--allow-unverified', pkg])
if process_dependency_links:
cmd.append('--process-dependency-links')
if trusted_host:
cmd.extend(['--trusted-host', trusted_host])
if extra_args:
# These are arguments from the latest version of pip that
# have not yet been implemented in salt
for arg in extra_args:
# It is a keyword argument
if isinstance(arg, dict):
# There will only ever be one item in this dictionary
key, val = arg.popitem()
# Don't allow any recursion into keyword arg definitions
# Don't allow multiple definitions of a keyword
if isinstance(val, (dict, list)):
raise TypeError("Too many levels in: {}".format(key))
# This is a a normal one-to-one keyword argument
cmd.extend([key, val])
# It is a positional argument, append it to the list
else:
cmd.append(arg)
cmd_kwargs = dict(saltenv=saltenv, use_vt=use_vt, runas=user)
if kwargs:
cmd_kwargs.update(kwargs)
if env_vars:
cmd_kwargs.setdefault('env', {}).update(_format_env_vars(env_vars))
try:
if cwd:
cmd_kwargs['cwd'] = cwd
if bin_env and os.path.isdir(bin_env):
cmd_kwargs.setdefault('env', {})['VIRTUAL_ENV'] = bin_env
logger.debug(
'TRY BLOCK: end of pip.install -- cmd: %s, cmd_kwargs: %s',
cmd, cmd_kwargs
)
return __salt__['cmd.run_all'](cmd, python_shell=False, **cmd_kwargs)
finally:
_clear_context(bin_env)
for tempdir in [cr for cr in cleanup_requirements if cr is not None]:
if os.path.isdir(tempdir):
shutil.rmtree(tempdir)
def uninstall(pkgs=None,
requirements=None,
bin_env=None,
log=None,
proxy=None,
timeout=None,
user=None,
cwd=None,
saltenv='base',
use_vt=False):
'''
Uninstall packages individually or from a pip requirements file
pkgs
comma separated list of packages to install
requirements
Path to requirements file
bin_env
Path to pip (or to a virtualenv). This can be used to specify the path
to the pip to use when more than one Python release is installed (e.g.
``/usr/bin/pip-2.7`` or ``/usr/bin/pip-2.6``. If a directory path is
specified, it is assumed to be a virtualenv.
log
Log file where a complete (maximum verbosity) record will be kept
proxy
Specify a proxy in the format ``user:passwd@proxy.server:port``. Note
that the ``user:password@`` is optional and required only if you are
behind an authenticated proxy. If you provide
``user@proxy.server:port`` then you will be prompted for a password.
timeout
Set the socket timeout (default 15 seconds)
user
The user under which to run pip
cwd
Directory from which to run pip
use_vt
Use VT terminal emulation (see output while installing)
CLI Example:
.. code-block:: bash
salt '*' pip.uninstall <package name>,<package2 name>
salt '*' pip.uninstall requirements=/path/to/requirements.txt
salt '*' pip.uninstall <package name> bin_env=/path/to/virtualenv
salt '*' pip.uninstall <package name> bin_env=/path/to/pip_bin
'''
cmd = _get_pip_bin(bin_env)
cmd.extend(['uninstall', '-y'])
cleanup_requirements, error = _process_requirements(
requirements=requirements, cmd=cmd, saltenv=saltenv, user=user,
cwd=cwd
)
if error:
return error
if log:
try:
# TODO make this check if writeable
os.path.exists(log)
except IOError:
raise IOError('\'{0}\' is not writeable'.format(log))
cmd.extend(['--log', log])
if proxy:
cmd.extend(['--proxy', proxy])
if timeout:
try:
if isinstance(timeout, float):
# Catch floating point input, exception will be caught in
# exception class below.
raise ValueError('Timeout cannot be a float')
int(timeout)
except ValueError:
raise ValueError(
'\'{0}\' is not a valid timeout, must be an integer'
.format(timeout)
)
cmd.extend(['--timeout', timeout])
if pkgs:
if isinstance(pkgs, six.string_types):
pkgs = [p.strip() for p in pkgs.split(',')]
if requirements:
for requirement in requirements:
with salt.utils.files.fopen(requirement) as rq_:
for req in rq_:
req = salt.utils.stringutils.to_unicode(req)
try:
req_pkg, _ = req.split('==')
if req_pkg in pkgs:
pkgs.remove(req_pkg)
except ValueError:
pass
cmd.extend(pkgs)
cmd_kwargs = dict(python_shell=False, runas=user,
cwd=cwd, saltenv=saltenv, use_vt=use_vt)
if bin_env and os.path.isdir(bin_env):
cmd_kwargs['env'] = {'VIRTUAL_ENV': bin_env}
try:
return __salt__['cmd.run_all'](cmd, **cmd_kwargs)
finally:
_clear_context(bin_env)
for requirement in cleanup_requirements:
if requirement:
try:
os.remove(requirement)
except OSError:
pass
def freeze(bin_env=None,
user=None,
cwd=None,
use_vt=False,
env_vars=None,
**kwargs):
'''
Return a list of installed packages either globally or in the specified
virtualenv
bin_env
Path to pip (or to a virtualenv). This can be used to specify the path
to the pip to use when more than one Python release is installed (e.g.
``/usr/bin/pip-2.7`` or ``/usr/bin/pip-2.6``. If a directory path is
specified, it is assumed to be a virtualenv.
user
The user under which to run pip
cwd
Directory from which to run pip
.. note::
If the version of pip available is older than 8.0.3, the list will not
include the packages ``pip``, ``wheel``, ``setuptools``, or
``distribute`` even if they are installed.
CLI Example:
.. code-block:: bash
salt '*' pip.freeze bin_env=/home/code/path/to/virtualenv
'''
cmd = _get_pip_bin(bin_env)
cmd.append('freeze')
# Include pip, setuptools, distribute, wheel
min_version = '8.0.3'
cur_version = version(bin_env)
if salt.utils.versions.compare(ver1=cur_version, oper='<', ver2=min_version):
logger.warning(
'The version of pip installed is %s, which is older than %s. '
'The packages pip, wheel, setuptools, and distribute will not be '
'included in the output of pip.freeze', cur_version, min_version
)
else:
cmd.append('--all')
cmd_kwargs = dict(runas=user, cwd=cwd, use_vt=use_vt, python_shell=False)
if kwargs:
cmd_kwargs.update(**kwargs)
if bin_env and os.path.isdir(bin_env):
cmd_kwargs['env'] = {'VIRTUAL_ENV': bin_env}
if env_vars:
cmd_kwargs.setdefault('env', {}).update(_format_env_vars(env_vars))
result = __salt__['cmd.run_all'](cmd, **cmd_kwargs)
if result['retcode']:
raise CommandExecutionError(result['stderr'], info=result)
return result['stdout'].splitlines()
def version(bin_env=None):
'''
.. versionadded:: 0.17.0
Returns the version of pip. Use ``bin_env`` to specify the path to a
virtualenv and get the version of pip in that virtualenv.
If unable to detect the pip version, returns ``None``.
CLI Example:
.. code-block:: bash
salt '*' pip.version
'''
contextkey = 'pip.version'
if bin_env is not None:
contextkey = '{0}.{1}'.format(contextkey, bin_env)
if contextkey in __context__:
return __context__[contextkey]
cmd = _get_pip_bin(bin_env)[:]
cmd.append('--version')
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
if ret['retcode']:
raise CommandNotFoundError('Could not find a `pip` binary')
try:
pip_version = re.match(r'^pip (\S+)', ret['stdout']).group(1)
except AttributeError:
pip_version = None
__context__[contextkey] = pip_version
return pip_version
def list_upgrades(bin_env=None,
user=None,
cwd=None):
'''
Check whether or not an upgrade is available for all packages
CLI Example:
.. code-block:: bash
salt '*' pip.list_upgrades
'''
cmd = _get_pip_bin(bin_env)
cmd.extend(['list', '--outdated'])
pip_version = version(bin_env)
# Pip started supporting the ability to output json starting with 9.0.0
min_version = '9.0'
if salt.utils.versions.compare(ver1=pip_version,
oper='>=',
ver2=min_version):
cmd.append('--format=json')
cmd_kwargs = dict(cwd=cwd, runas=user)
if bin_env and os.path.isdir(bin_env):
cmd_kwargs['env'] = {'VIRTUAL_ENV': bin_env}
result = __salt__['cmd.run_all'](cmd, **cmd_kwargs)
if result['retcode']:
raise CommandExecutionError(result['stderr'], info=result)
packages = {}
# Pip started supporting the ability to output json starting with 9.0.0
# Older versions will have to parse stdout
if salt.utils.versions.compare(ver1=pip_version, oper='<', ver2='9.0.0'):
# Pip versions < 8.0.0 had a different output format
# Sample data:
# pip (Current: 7.1.2 Latest: 10.0.1 [wheel])
# psutil (Current: 5.2.2 Latest: 5.4.5 [wheel])
# pyasn1 (Current: 0.2.3 Latest: 0.4.2 [wheel])
# pycparser (Current: 2.17 Latest: 2.18 [sdist])
if salt.utils.versions.compare(ver1=pip_version, oper='<', ver2='8.0.0'):
logger.debug('pip module: Old output format')
pat = re.compile(r'(\S*)\s+\(.*Latest:\s+(.*)\)')
# New output format for version 8.0.0+
# Sample data:
# pip (8.0.0) - Latest: 10.0.1 [wheel]
# psutil (5.2.2) - Latest: 5.4.5 [wheel]
# pyasn1 (0.2.3) - Latest: 0.4.2 [wheel]
# pycparser (2.17) - Latest: 2.18 [sdist]
else:
logger.debug('pip module: New output format')
pat = re.compile(r'(\S*)\s+\(.*\)\s+-\s+Latest:\s+(.*)')
for line in result['stdout'].splitlines():
match = pat.search(line)
if match:
name, version_ = match.groups()
else:
logger.error('Can\'t parse line \'%s\'', line)
continue
packages[name] = version_
else:
logger.debug('pip module: JSON output format')
try:
pkgs = salt.utils.json.loads(result['stdout'], strict=False)
except ValueError:
raise CommandExecutionError('Invalid JSON', info=result)
for pkg in pkgs:
packages[pkg['name']] = '{0} [{1}]'.format(pkg['latest_version'],
pkg['latest_filetype'])
return packages
def is_installed(pkgname=None,
bin_env=None,
user=None,
cwd=None):
'''
.. versionadded:: 2018.3.0
Filter list of installed apps from ``freeze`` and return True or False if
``pkgname`` exists in the list of packages installed.
.. note::
If the version of pip available is older than 8.0.3, the packages
wheel, setuptools, and distribute will not be reported by this function
even if they are installed. Unlike :py:func:`pip.freeze
<salt.modules.pip.freeze>`, this function always reports the version of
pip which is installed.
CLI Example:
.. code-block:: bash
salt '*' pip.is_installed salt
'''
for line in freeze(bin_env=bin_env, user=user, cwd=cwd):
if line.startswith('-f') or line.startswith('#'):
# ignore -f line as it contains --find-links directory
# ignore comment lines
continue
elif line.startswith('-e hg+not trust'):
# ignore hg + not trust problem
continue
elif line.startswith('-e'):
line = line.split('-e ')[1]
version_, name = line.split('#egg=')
elif len(line.split('===')) >= 2:
name = line.split('===')[0]
version_ = line.split('===')[1]
elif len(line.split('==')) >= 2:
name = line.split('==')[0]
version_ = line.split('==')[1]
else:
logger.error('Can\'t parse line \'%s\'', line)
continue
if pkgname:
if pkgname == name.lower():
return True
return False
def upgrade_available(pkg,
bin_env=None,
user=None,
cwd=None):
'''
.. versionadded:: 2015.5.0
Check whether or not an upgrade is available for a given package
CLI Example:
.. code-block:: bash
salt '*' pip.upgrade_available <package name>
'''
return pkg in list_upgrades(bin_env=bin_env, user=user, cwd=cwd)
def upgrade(bin_env=None,
user=None,
cwd=None,
use_vt=False):
'''
.. versionadded:: 2015.5.0
Upgrades outdated pip packages.
.. note::
On Windows you can't update salt from pip using salt, so salt will be
skipped
Returns a dict containing the changes.
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
CLI Example:
.. code-block:: bash
salt '*' pip.upgrade
'''
ret = {'changes': {},
'result': True,
'comment': '',
}
cmd = _get_pip_bin(bin_env)
cmd.extend(['install', '-U'])
old = list_(bin_env=bin_env, user=user, cwd=cwd)
cmd_kwargs = dict(cwd=cwd, use_vt=use_vt)
if bin_env and os.path.isdir(bin_env):
cmd_kwargs['env'] = {'VIRTUAL_ENV': bin_env}
errors = False
for pkg in list_upgrades(bin_env=bin_env, user=user, cwd=cwd):
if pkg == 'salt':
if salt.utils.platform.is_windows():
continue
result = __salt__['cmd.run_all'](cmd + [pkg], **cmd_kwargs)
if result['retcode'] != 0:
errors = True
if 'stderr' in result:
ret['comment'] += result['stderr']
if errors:
ret['result'] = False
_clear_context(bin_env)
new = list_(bin_env=bin_env, user=user, cwd=cwd)
ret['changes'] = salt.utils.data.compare_dicts(old, new)
return ret
def list_all_versions(pkg,
bin_env=None,
include_alpha=False,
include_beta=False,
include_rc=False,
user=None,
cwd=None,
index_url=None,
extra_index_url=None):
'''
.. versionadded:: 2017.7.3
List all available versions of a pip package
pkg
The package to check
bin_env
Path to pip (or to a virtualenv). This can be used to specify the path
to the pip to use when more than one Python release is installed (e.g.
``/usr/bin/pip-2.7`` or ``/usr/bin/pip-2.6``. If a directory path is
specified, it is assumed to be a virtualenv.
include_alpha
Include alpha versions in the list
include_beta
Include beta versions in the list
include_rc
Include release candidates versions in the list
user
The user under which to run pip
cwd
Directory from which to run pip
index_url
Base URL of Python Package Index
.. versionadded:: 2019.2.0
extra_index_url
Additional URL of Python Package Index
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' pip.list_all_versions <package name>
'''
cmd = _get_pip_bin(bin_env)
cmd.extend(['install', '{0}==versions'.format(pkg)])
if index_url:
if not salt.utils.url.validate(index_url, VALID_PROTOS):
raise CommandExecutionError(
'\'{0}\' is not a valid URL'.format(index_url)
)
cmd.extend(['--index-url', index_url])
if extra_index_url:
if not salt.utils.url.validate(extra_index_url, VALID_PROTOS):
raise CommandExecutionError(
'\'{0}\' is not a valid URL'.format(extra_index_url)
)
cmd.extend(['--extra-index-url', extra_index_url])
cmd_kwargs = dict(cwd=cwd, runas=user, output_loglevel='quiet', redirect_stderr=True)
if bin_env and os.path.isdir(bin_env):
cmd_kwargs['env'] = {'VIRTUAL_ENV': bin_env}
result = __salt__['cmd.run_all'](cmd, **cmd_kwargs)
filtered = []
if not include_alpha:
filtered.append('a')
if not include_beta:
filtered.append('b')
if not include_rc:
filtered.append('rc')
if filtered:
excludes = re.compile(r'^((?!{0}).)*$'.format('|'.join(filtered)))
else:
excludes = re.compile(r'')
versions = []
for line in result['stdout'].splitlines():
match = re.search(r'\s*Could not find a version.* \(from versions: (.*)\)', line)
if match:
versions = [v for v in match.group(1).split(', ') if v and excludes.match(v)]
versions.sort(key=pkg_resources.parse_version)
break
if not versions:
return None
return versions
|
saltstack/salt
|
salt/modules/pip.py
|
version
|
python
|
def version(bin_env=None):
'''
.. versionadded:: 0.17.0
Returns the version of pip. Use ``bin_env`` to specify the path to a
virtualenv and get the version of pip in that virtualenv.
If unable to detect the pip version, returns ``None``.
CLI Example:
.. code-block:: bash
salt '*' pip.version
'''
contextkey = 'pip.version'
if bin_env is not None:
contextkey = '{0}.{1}'.format(contextkey, bin_env)
if contextkey in __context__:
return __context__[contextkey]
cmd = _get_pip_bin(bin_env)[:]
cmd.append('--version')
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
if ret['retcode']:
raise CommandNotFoundError('Could not find a `pip` binary')
try:
pip_version = re.match(r'^pip (\S+)', ret['stdout']).group(1)
except AttributeError:
pip_version = None
__context__[contextkey] = pip_version
return pip_version
|
.. versionadded:: 0.17.0
Returns the version of pip. Use ``bin_env`` to specify the path to a
virtualenv and get the version of pip in that virtualenv.
If unable to detect the pip version, returns ``None``.
CLI Example:
.. code-block:: bash
salt '*' pip.version
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/pip.py#L1223-L1258
|
[
"def _get_pip_bin(bin_env):\n '''\n Locate the pip binary, either from `bin_env` as a virtualenv, as the\n executable itself, or from searching conventional filesystem locations\n '''\n if not bin_env:\n logger.debug('pip: Using pip from currently-running Python')\n return [os.path.normpath(sys.executable), '-m', 'pip']\n\n python_bin = 'python.exe' if salt.utils.platform.is_windows() else 'python'\n\n def _search_paths(*basedirs):\n ret = []\n for path in basedirs:\n ret.extend([\n os.path.join(path, python_bin),\n os.path.join(path, 'bin', python_bin),\n os.path.join(path, 'Scripts', python_bin)\n ])\n return ret\n\n # try to get python bin from virtualenv (i.e. bin_env)\n if os.path.isdir(bin_env):\n for bin_path in _search_paths(bin_env):\n if os.path.isfile(bin_path):\n if os.access(bin_path, os.X_OK):\n logger.debug('pip: Found python binary: %s', bin_path)\n return [os.path.normpath(bin_path), '-m', 'pip']\n else:\n logger.debug(\n 'pip: Found python binary by name but it is not '\n 'executable: %s', bin_path\n )\n raise CommandNotFoundError(\n 'Could not find a pip binary in virtualenv {0}'.format(bin_env)\n )\n\n # bin_env is the python or pip binary\n elif os.access(bin_env, os.X_OK):\n if os.path.isfile(bin_env):\n # If the python binary was passed, return it\n if 'python' in os.path.basename(bin_env):\n return [os.path.normpath(bin_env), '-m', 'pip']\n # We have been passed a pip binary, use the pip binary.\n return [os.path.normpath(bin_env)]\n\n raise CommandExecutionError(\n 'Could not find a pip binary within {0}'.format(bin_env)\n )\n else:\n raise CommandNotFoundError(\n 'Access denied to {0}, could not find a pip binary'.format(bin_env)\n )\n"
] |
# -*- coding: utf-8 -*-
r'''
Install Python packages with pip to either the system or a virtualenv
Windows Support
===============
.. versionadded:: 2014.7.4
Salt now uses a portable python. As a result the entire pip module is now
functional on the salt installation itself. You can pip install dependencies
for your custom modules. You can even upgrade salt itself using pip. For this
to work properly, you must specify the Current Working Directory (``cwd``) and
the Pip Binary (``bin_env``) salt should use. The variable ``pip_bin`` can be
either a virtualenv path or the path to the pip binary itself.
For example, the following command will list all software installed using pip
to your current salt environment:
.. code-block:: bat
salt <minion> pip.list cwd='C:\salt\bin\Scripts' bin_env='C:\salt\bin\Scripts\pip.exe'
Specifying the ``cwd`` and ``bin_env`` options ensures you're modifying the
salt environment. If these are omitted, it will default to the local
installation of python. If python is not installed locally it will fail saying
it couldn't find pip.
State File Support
------------------
This functionality works in states as well. If you need to pip install colorama
with a state, for example, the following will work:
.. code-block:: yaml
install_colorama:
pip.installed:
- name: colorama
- cwd: 'C:\salt\bin\scripts'
- bin_env: 'C:\salt\bin\scripts\pip.exe'
- upgrade: True
Upgrading Salt using Pip
------------------------
You can now update salt using pip to any version from the 2014.7 branch
forward. Previous version require recompiling some of the dependencies which is
painful in windows.
To do this you just use pip with git to update to the version you want and then
restart the service. Here is a sample state file that upgrades salt to the head
of the 2015.5 branch:
.. code-block:: yaml
install_salt:
pip.installed:
- cwd: 'C:\salt\bin\scripts'
- bin_env: 'C:\salt\bin\scripts\pip.exe'
- editable: git+https://github.com/saltstack/salt@2015.5#egg=salt
- upgrade: True
restart_service:
service.running:
- name: salt-minion
- enable: True
- watch:
- pip: install_salt
.. note::
If you're having problems, you might try doubling the back slashes. For
example, cwd: 'C:\\salt\\bin\\scripts'. Sometimes python thinks the single
back slash is an escape character.
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import logging
import os
try:
import pkg_resources
except ImportError:
pkg_resources = None
import re
import shutil
import sys
import tempfile
# Import Salt libs
import salt.utils.data
import salt.utils.files
import salt.utils.json
import salt.utils.locales
import salt.utils.platform
import salt.utils.stringutils
import salt.utils.url
import salt.utils.versions
from salt.ext import six
from salt.exceptions import CommandExecutionError, CommandNotFoundError
# This needs to be named logger so we don't shadow it in pip.install
logger = logging.getLogger(__name__) # pylint: disable=C0103
# Don't shadow built-in's.
__func_alias__ = {
'list_': 'list'
}
VALID_PROTOS = ['http', 'https', 'ftp', 'file']
rex_pip_chain_read = re.compile(r'-r\s(.*)\n?', re.MULTILINE)
def __virtual__():
'''
There is no way to verify that pip is installed without inspecting the
entire filesystem. If it's not installed in a conventional location, the
user is required to provide the location of pip each time it is used.
'''
if pkg_resources is None:
ret = False, 'Package dependency "pkg_resource" is missing'
else:
ret = 'pip'
return ret
def _clear_context(bin_env=None):
'''
Remove the cached pip version
'''
contextkey = 'pip.version'
if bin_env is not None:
contextkey = '{0}.{1}'.format(contextkey, bin_env)
__context__.pop(contextkey, None)
def _get_pip_bin(bin_env):
'''
Locate the pip binary, either from `bin_env` as a virtualenv, as the
executable itself, or from searching conventional filesystem locations
'''
if not bin_env:
logger.debug('pip: Using pip from currently-running Python')
return [os.path.normpath(sys.executable), '-m', 'pip']
python_bin = 'python.exe' if salt.utils.platform.is_windows() else 'python'
def _search_paths(*basedirs):
ret = []
for path in basedirs:
ret.extend([
os.path.join(path, python_bin),
os.path.join(path, 'bin', python_bin),
os.path.join(path, 'Scripts', python_bin)
])
return ret
# try to get python bin from virtualenv (i.e. bin_env)
if os.path.isdir(bin_env):
for bin_path in _search_paths(bin_env):
if os.path.isfile(bin_path):
if os.access(bin_path, os.X_OK):
logger.debug('pip: Found python binary: %s', bin_path)
return [os.path.normpath(bin_path), '-m', 'pip']
else:
logger.debug(
'pip: Found python binary by name but it is not '
'executable: %s', bin_path
)
raise CommandNotFoundError(
'Could not find a pip binary in virtualenv {0}'.format(bin_env)
)
# bin_env is the python or pip binary
elif os.access(bin_env, os.X_OK):
if os.path.isfile(bin_env):
# If the python binary was passed, return it
if 'python' in os.path.basename(bin_env):
return [os.path.normpath(bin_env), '-m', 'pip']
# We have been passed a pip binary, use the pip binary.
return [os.path.normpath(bin_env)]
raise CommandExecutionError(
'Could not find a pip binary within {0}'.format(bin_env)
)
else:
raise CommandNotFoundError(
'Access denied to {0}, could not find a pip binary'.format(bin_env)
)
def _get_cached_requirements(requirements, saltenv):
'''
Get the location of a cached requirements file; caching if necessary.
'''
req_file, senv = salt.utils.url.parse(requirements)
if senv:
saltenv = senv
if req_file not in __salt__['cp.list_master'](saltenv):
# Requirements file does not exist in the given saltenv.
return False
cached_requirements = __salt__['cp.is_cached'](
requirements, saltenv
)
if not cached_requirements:
# It's not cached, let's cache it.
cached_requirements = __salt__['cp.cache_file'](
requirements, saltenv
)
# Check if the master version has changed.
if __salt__['cp.hash_file'](requirements, saltenv) != \
__salt__['cp.hash_file'](cached_requirements, saltenv):
cached_requirements = __salt__['cp.cache_file'](
requirements, saltenv
)
return cached_requirements
def _get_env_activate(bin_env):
'''
Return the path to the activate binary
'''
if not bin_env:
raise CommandNotFoundError('Could not find a `activate` binary')
if os.path.isdir(bin_env):
if salt.utils.platform.is_windows():
activate_bin = os.path.join(bin_env, 'Scripts', 'activate.bat')
else:
activate_bin = os.path.join(bin_env, 'bin', 'activate')
if os.path.isfile(activate_bin):
return activate_bin
raise CommandNotFoundError('Could not find a `activate` binary')
def _find_req(link):
logger.info('_find_req -- link = %s', link)
with salt.utils.files.fopen(link) as fh_link:
child_links = rex_pip_chain_read.findall(
salt.utils.stringutils.to_unicode(fh_link.read())
)
base_path = os.path.dirname(link)
child_links = [os.path.join(base_path, d) for d in child_links]
return child_links
def _resolve_requirements_chain(requirements):
'''
Return an array of requirements file paths that can be used to complete
the no_chown==False && user != None conundrum
'''
chain = []
if isinstance(requirements, six.string_types):
requirements = [requirements]
for req_file in requirements:
chain.append(req_file)
chain.extend(_resolve_requirements_chain(_find_req(req_file)))
return chain
def _process_requirements(requirements, cmd, cwd, saltenv, user):
'''
Process the requirements argument
'''
cleanup_requirements = []
if requirements is not None:
if isinstance(requirements, six.string_types):
requirements = [r.strip() for r in requirements.split(',')]
elif not isinstance(requirements, list):
raise TypeError('requirements must be a string or list')
treq = None
for requirement in requirements:
logger.debug('TREQ IS: %s', treq)
if requirement.startswith('salt://'):
cached_requirements = _get_cached_requirements(
requirement, saltenv
)
if not cached_requirements:
ret = {'result': False,
'comment': 'pip requirements file \'{0}\' not found'
.format(requirement)}
return None, ret
requirement = cached_requirements
if user:
# Need to make a temporary copy since the user will, most
# likely, not have the right permissions to read the file
if not treq:
treq = tempfile.mkdtemp()
__salt__['file.chown'](treq, user, None)
# In Windows, just being owner of a file isn't enough. You also
# need permissions
if salt.utils.platform.is_windows():
__utils__['dacl.set_permissions'](
obj_name=treq,
principal=user,
permissions='read_execute')
current_directory = None
if not current_directory:
current_directory = os.path.abspath(os.curdir)
logger.info('_process_requirements from directory, '
'%s -- requirement: %s', cwd, requirement)
if cwd is None:
r = requirement
c = cwd
requirement_abspath = os.path.abspath(requirement)
cwd = os.path.dirname(requirement_abspath)
requirement = os.path.basename(requirement)
logger.debug('\n\tcwd: %s -> %s\n\trequirement: %s -> %s\n',
c, cwd, r, requirement
)
os.chdir(cwd)
reqs = _resolve_requirements_chain(requirement)
os.chdir(current_directory)
logger.info('request files: %s', reqs)
for req_file in reqs:
if not os.path.isabs(req_file):
req_file = os.path.join(cwd, req_file)
logger.debug('TREQ N CWD: %s -- %s -- for %s', treq, cwd, req_file)
target_path = os.path.join(treq, os.path.basename(req_file))
logger.debug('S: %s', req_file)
logger.debug('T: %s', target_path)
target_base = os.path.dirname(target_path)
if not os.path.exists(target_base):
os.makedirs(target_base, mode=0o755)
__salt__['file.chown'](target_base, user, None)
if not os.path.exists(target_path):
logger.debug(
'Copying %s to %s', req_file, target_path
)
__salt__['file.copy'](req_file, target_path)
logger.debug(
'Changing ownership of requirements file \'%s\' to '
'user \'%s\'', target_path, user
)
__salt__['file.chown'](target_path, user, None)
req_args = os.path.join(treq, requirement) if treq else requirement
cmd.extend(['--requirement', req_args])
cleanup_requirements.append(treq)
logger.debug('CLEANUP_REQUIREMENTS: %s', cleanup_requirements)
return cleanup_requirements, None
def _format_env_vars(env_vars):
ret = {}
if env_vars:
if isinstance(env_vars, dict):
for key, val in six.iteritems(env_vars):
if not isinstance(key, six.string_types):
key = str(key) # future lint: disable=blacklisted-function
if not isinstance(val, six.string_types):
val = str(val) # future lint: disable=blacklisted-function
ret[key] = val
else:
raise CommandExecutionError(
'env_vars {0} is not a dictionary'.format(env_vars))
return ret
def install(pkgs=None, # pylint: disable=R0912,R0913,R0914
requirements=None,
bin_env=None,
use_wheel=False,
no_use_wheel=False,
log=None,
proxy=None,
timeout=None,
editable=None,
find_links=None,
index_url=None,
extra_index_url=None,
no_index=False,
mirrors=None,
build=None,
target=None,
download=None,
download_cache=None,
source=None,
upgrade=False,
force_reinstall=False,
ignore_installed=False,
exists_action=None,
no_deps=False,
no_install=False,
no_download=False,
global_options=None,
install_options=None,
user=None,
cwd=None,
pre_releases=False,
cert=None,
allow_all_external=False,
allow_external=None,
allow_unverified=None,
process_dependency_links=False,
saltenv='base',
env_vars=None,
use_vt=False,
trusted_host=None,
no_cache_dir=False,
cache_dir=None,
no_binary=None,
extra_args=None,
**kwargs):
'''
Install packages with pip
Install packages individually or from a pip requirements file. Install
packages globally or to a virtualenv.
pkgs
Comma separated list of packages to install
requirements
Path to requirements
bin_env
Path to pip (or to a virtualenv). This can be used to specify the path
to the pip to use when more than one Python release is installed (e.g.
``/usr/bin/pip-2.7`` or ``/usr/bin/pip-2.6``. If a directory path is
specified, it is assumed to be a virtualenv.
.. note::
For Windows, if the pip module is being used to upgrade the pip
package, bin_env should be the path to the virtualenv or to the
python binary that should be used. The pip command is unable to
upgrade itself in Windows.
use_wheel
Prefer wheel archives (requires pip>=1.4)
no_use_wheel
Force to not use wheel archives (requires pip>=1.4,<10.0.0)
no_binary
Force to not use binary packages (requires pip >= 7.0.0)
Accepts either :all: to disable all binary packages, :none: to empty the set,
or one or more package names with commas between them
log
Log file where a complete (maximum verbosity) record will be kept
proxy
Specify a proxy in the form ``user:passwd@proxy.server:port``. Note
that the ``user:password@`` is optional and required only if you are
behind an authenticated proxy. If you provide
``user@proxy.server:port`` then you will be prompted for a password.
timeout
Set the socket timeout (default 15 seconds)
editable
install something editable (e.g.
``git+https://github.com/worldcompany/djangoembed.git#egg=djangoembed``)
find_links
URL to search for packages
index_url
Base URL of Python Package Index
extra_index_url
Extra URLs of package indexes to use in addition to ``index_url``
no_index
Ignore package index
mirrors
Specific mirror URL(s) to query (automatically adds --use-mirrors)
.. warning::
This option has been deprecated and removed in pip version 7.0.0.
Please use ``index_url`` and/or ``extra_index_url`` instead.
build
Unpack packages into ``build`` dir
target
Install packages into ``target`` dir
download
Download packages into ``download`` instead of installing them
download_cache | cache_dir
Cache downloaded packages in ``download_cache`` or ``cache_dir`` dir
source
Check out ``editable`` packages into ``source`` dir
upgrade
Upgrade all packages to the newest available version
force_reinstall
When upgrading, reinstall all packages even if they are already
up-to-date.
ignore_installed
Ignore the installed packages (reinstalling instead)
exists_action
Default action when a path already exists: (s)witch, (i)gnore, (w)ipe,
(b)ackup
no_deps
Ignore package dependencies
no_install
Download and unpack all packages, but don't actually install them
no_download
Don't download any packages, just install the ones already downloaded
(completes an install run with ``--no-install``)
install_options
Extra arguments to be supplied to the setup.py install command (e.g.
like ``--install-option='--install-scripts=/usr/local/bin'``). Use
multiple --install-option options to pass multiple options to setup.py
install. If you are using an option with a directory path, be sure to
use absolute path.
global_options
Extra global options to be supplied to the setup.py call before the
install command.
user
The user under which to run pip
cwd
Directory from which to run pip
pre_releases
Include pre-releases in the available versions
cert
Provide a path to an alternate CA bundle
allow_all_external
Allow the installation of all externally hosted files
allow_external
Allow the installation of externally hosted files (comma separated
list)
allow_unverified
Allow the installation of insecure and unverifiable files (comma
separated list)
process_dependency_links
Enable the processing of dependency links
env_vars
Set environment variables that some builds will depend on. For example,
a Python C-module may have a Makefile that needs INCLUDE_PATH set to
pick up a header file while compiling. This must be in the form of a
dictionary or a mapping.
Example:
.. code-block:: bash
salt '*' pip.install django_app env_vars="{'CUSTOM_PATH': '/opt/django_app'}"
trusted_host
Mark this host as trusted, even though it does not have valid or any
HTTPS.
use_vt
Use VT terminal emulation (see output while installing)
no_cache_dir
Disable the cache.
extra_args
pip keyword and positional arguments not yet implemented in salt
.. code-block:: yaml
salt '*' pip.install pandas extra_args="[{'--latest-pip-kwarg':'param'}, '--latest-pip-arg']"
.. warning::
If unsupported options are passed here that are not supported in a
minion's version of pip, a `No such option error` will be thrown.
Will be translated into the following pip command:
.. code-block:: bash
pip install pandas --latest-pip-kwarg param --latest-pip-arg
CLI Example:
.. code-block:: bash
salt '*' pip.install <package name>,<package2 name>
salt '*' pip.install requirements=/path/to/requirements.txt
salt '*' pip.install <package name> bin_env=/path/to/virtualenv
salt '*' pip.install <package name> bin_env=/path/to/pip_bin
Complicated CLI example::
salt '*' pip.install markdown,django \
editable=git+https://github.com/worldcompany/djangoembed.git#egg=djangoembed upgrade=True no_deps=True
'''
cmd = _get_pip_bin(bin_env)
cmd.append('install')
cleanup_requirements, error = _process_requirements(
requirements=requirements,
cmd=cmd,
cwd=cwd,
saltenv=saltenv,
user=user
)
if error:
return error
cur_version = version(bin_env)
if use_wheel:
min_version = '1.4'
max_version = '9.0.3'
too_low = salt.utils.versions.compare(ver1=cur_version, oper='<', ver2=min_version)
too_high = salt.utils.versions.compare(ver1=cur_version, oper='>', ver2=max_version)
if too_low or too_high:
logger.error(
'The --use-wheel option is only supported in pip between %s and '
'%s. The version of pip detected is %s. This option '
'will be ignored.', min_version, max_version, cur_version
)
else:
cmd.append('--use-wheel')
if no_use_wheel:
min_version = '1.4'
max_version = '9.0.3'
too_low = salt.utils.versions.compare(ver1=cur_version, oper='<', ver2=min_version)
too_high = salt.utils.versions.compare(ver1=cur_version, oper='>', ver2=max_version)
if too_low or too_high:
logger.error(
'The --no-use-wheel option is only supported in pip between %s and '
'%s. The version of pip detected is %s. This option '
'will be ignored.', min_version, max_version, cur_version
)
else:
cmd.append('--no-use-wheel')
if no_binary:
min_version = '7.0.0'
too_low = salt.utils.versions.compare(ver1=cur_version, oper='<', ver2=min_version)
if too_low:
logger.error(
'The --no-binary option is only supported in pip %s and '
'newer. The version of pip detected is %s. This option '
'will be ignored.', min_version, cur_version
)
else:
if isinstance(no_binary, list):
no_binary = ','.join(no_binary)
cmd.extend(['--no-binary', no_binary])
if log:
if os.path.isdir(log):
raise IOError(
'\'{0}\' is a directory. Use --log path_to_file'.format(log))
elif not os.access(log, os.W_OK):
raise IOError('\'{0}\' is not writeable'.format(log))
cmd.extend(['--log', log])
if proxy:
cmd.extend(['--proxy', proxy])
if timeout:
try:
if isinstance(timeout, float):
# Catch floating point input, exception will be caught in
# exception class below.
raise ValueError('Timeout cannot be a float')
int(timeout)
except ValueError:
raise ValueError(
'\'{0}\' is not a valid timeout, must be an integer'
.format(timeout)
)
cmd.extend(['--timeout', timeout])
if find_links:
if isinstance(find_links, six.string_types):
find_links = [l.strip() for l in find_links.split(',')]
for link in find_links:
if not (salt.utils.url.validate(link, VALID_PROTOS) or os.path.exists(link)):
raise CommandExecutionError(
'\'{0}\' is not a valid URL or path'.format(link)
)
cmd.extend(['--find-links', link])
if no_index and (index_url or extra_index_url):
raise CommandExecutionError(
'\'no_index\' and (\'index_url\' or \'extra_index_url\') are '
'mutually exclusive.'
)
if index_url:
if not salt.utils.url.validate(index_url, VALID_PROTOS):
raise CommandExecutionError(
'\'{0}\' is not a valid URL'.format(index_url)
)
cmd.extend(['--index-url', index_url])
if extra_index_url:
if not salt.utils.url.validate(extra_index_url, VALID_PROTOS):
raise CommandExecutionError(
'\'{0}\' is not a valid URL'.format(extra_index_url)
)
cmd.extend(['--extra-index-url', extra_index_url])
if no_index:
cmd.append('--no-index')
if mirrors:
# https://github.com/pypa/pip/pull/2641/files#diff-3ef137fb9ffdd400f117a565cd94c188L216
if salt.utils.versions.compare(ver1=cur_version, oper='>=', ver2='7.0.0'):
raise CommandExecutionError(
'pip >= 7.0.0 does not support mirror argument:'
' use index_url and/or extra_index_url instead'
)
if isinstance(mirrors, six.string_types):
mirrors = [m.strip() for m in mirrors.split(',')]
cmd.append('--use-mirrors')
for mirror in mirrors:
if not mirror.startswith('http://'):
raise CommandExecutionError(
'\'{0}\' is not a valid URL'.format(mirror)
)
cmd.extend(['--mirrors', mirror])
if build:
cmd.extend(['--build', build])
if target:
cmd.extend(['--target', target])
if download:
cmd.extend(['--download', download])
if download_cache or cache_dir:
cmd.extend(['--cache-dir' if salt.utils.versions.compare(
ver1=cur_version, oper='>=', ver2='6.0'
) else '--download-cache', download_cache or cache_dir])
if source:
cmd.extend(['--source', source])
if upgrade:
cmd.append('--upgrade')
if force_reinstall:
cmd.append('--force-reinstall')
if ignore_installed:
cmd.append('--ignore-installed')
if exists_action:
if exists_action.lower() not in ('s', 'i', 'w', 'b'):
raise CommandExecutionError(
'The exists_action pip option only supports the values '
's, i, w, and b. \'{0}\' is not valid.'.format(exists_action)
)
cmd.extend(['--exists-action', exists_action])
if no_deps:
cmd.append('--no-deps')
if no_install:
cmd.append('--no-install')
if no_download:
cmd.append('--no-download')
if no_cache_dir:
cmd.append('--no-cache-dir')
if pre_releases:
# Check the locally installed pip version
pip_version = cur_version
# From pip v1.4 the --pre flag is available
if salt.utils.versions.compare(ver1=pip_version, oper='>=', ver2='1.4'):
cmd.append('--pre')
if cert:
cmd.extend(['--cert', cert])
if global_options:
if isinstance(global_options, six.string_types):
global_options = [go.strip() for go in global_options.split(',')]
for opt in global_options:
cmd.extend(['--global-option', opt])
if install_options:
if isinstance(install_options, six.string_types):
install_options = [io.strip() for io in install_options.split(',')]
for opt in install_options:
cmd.extend(['--install-option', opt])
if pkgs:
if not isinstance(pkgs, list):
try:
pkgs = [p.strip() for p in pkgs.split(',')]
except AttributeError:
pkgs = [p.strip() for p in six.text_type(pkgs).split(',')]
pkgs = salt.utils.data.stringify(salt.utils.data.decode_list(pkgs))
# It's possible we replaced version-range commas with semicolons so
# they would survive the previous line (in the pip.installed state).
# Put the commas back in while making sure the names are contained in
# quotes, this allows for proper version spec passing salt>=0.17.0
cmd.extend([p.replace(';', ',') for p in pkgs])
elif not any([requirements, editable]):
# Starting with pip 10.0.0, if no packages are specified in the
# command, it returns a retcode 1. So instead of running the command,
# just return the output without running pip.
return {'retcode': 0, 'stdout': 'No packages to install.'}
if editable:
egg_match = re.compile(r'(?:#|#.*?&)egg=([^&]*)')
if isinstance(editable, six.string_types):
editable = [e.strip() for e in editable.split(',')]
for entry in editable:
# Is the editable local?
if not (entry == '.' or entry.startswith(('file://', '/'))):
match = egg_match.search(entry)
if not match or not match.group(1):
# Missing #egg=theEggName
raise CommandExecutionError(
'You must specify an egg for this editable'
)
cmd.extend(['--editable', entry])
if allow_all_external:
cmd.append('--allow-all-external')
if allow_external:
if isinstance(allow_external, six.string_types):
allow_external = [p.strip() for p in allow_external.split(',')]
for pkg in allow_external:
cmd.extend(['--allow-external', pkg])
if allow_unverified:
if isinstance(allow_unverified, six.string_types):
allow_unverified = \
[p.strip() for p in allow_unverified.split(',')]
for pkg in allow_unverified:
cmd.extend(['--allow-unverified', pkg])
if process_dependency_links:
cmd.append('--process-dependency-links')
if trusted_host:
cmd.extend(['--trusted-host', trusted_host])
if extra_args:
# These are arguments from the latest version of pip that
# have not yet been implemented in salt
for arg in extra_args:
# It is a keyword argument
if isinstance(arg, dict):
# There will only ever be one item in this dictionary
key, val = arg.popitem()
# Don't allow any recursion into keyword arg definitions
# Don't allow multiple definitions of a keyword
if isinstance(val, (dict, list)):
raise TypeError("Too many levels in: {}".format(key))
# This is a a normal one-to-one keyword argument
cmd.extend([key, val])
# It is a positional argument, append it to the list
else:
cmd.append(arg)
cmd_kwargs = dict(saltenv=saltenv, use_vt=use_vt, runas=user)
if kwargs:
cmd_kwargs.update(kwargs)
if env_vars:
cmd_kwargs.setdefault('env', {}).update(_format_env_vars(env_vars))
try:
if cwd:
cmd_kwargs['cwd'] = cwd
if bin_env and os.path.isdir(bin_env):
cmd_kwargs.setdefault('env', {})['VIRTUAL_ENV'] = bin_env
logger.debug(
'TRY BLOCK: end of pip.install -- cmd: %s, cmd_kwargs: %s',
cmd, cmd_kwargs
)
return __salt__['cmd.run_all'](cmd, python_shell=False, **cmd_kwargs)
finally:
_clear_context(bin_env)
for tempdir in [cr for cr in cleanup_requirements if cr is not None]:
if os.path.isdir(tempdir):
shutil.rmtree(tempdir)
def uninstall(pkgs=None,
requirements=None,
bin_env=None,
log=None,
proxy=None,
timeout=None,
user=None,
cwd=None,
saltenv='base',
use_vt=False):
'''
Uninstall packages individually or from a pip requirements file
pkgs
comma separated list of packages to install
requirements
Path to requirements file
bin_env
Path to pip (or to a virtualenv). This can be used to specify the path
to the pip to use when more than one Python release is installed (e.g.
``/usr/bin/pip-2.7`` or ``/usr/bin/pip-2.6``. If a directory path is
specified, it is assumed to be a virtualenv.
log
Log file where a complete (maximum verbosity) record will be kept
proxy
Specify a proxy in the format ``user:passwd@proxy.server:port``. Note
that the ``user:password@`` is optional and required only if you are
behind an authenticated proxy. If you provide
``user@proxy.server:port`` then you will be prompted for a password.
timeout
Set the socket timeout (default 15 seconds)
user
The user under which to run pip
cwd
Directory from which to run pip
use_vt
Use VT terminal emulation (see output while installing)
CLI Example:
.. code-block:: bash
salt '*' pip.uninstall <package name>,<package2 name>
salt '*' pip.uninstall requirements=/path/to/requirements.txt
salt '*' pip.uninstall <package name> bin_env=/path/to/virtualenv
salt '*' pip.uninstall <package name> bin_env=/path/to/pip_bin
'''
cmd = _get_pip_bin(bin_env)
cmd.extend(['uninstall', '-y'])
cleanup_requirements, error = _process_requirements(
requirements=requirements, cmd=cmd, saltenv=saltenv, user=user,
cwd=cwd
)
if error:
return error
if log:
try:
# TODO make this check if writeable
os.path.exists(log)
except IOError:
raise IOError('\'{0}\' is not writeable'.format(log))
cmd.extend(['--log', log])
if proxy:
cmd.extend(['--proxy', proxy])
if timeout:
try:
if isinstance(timeout, float):
# Catch floating point input, exception will be caught in
# exception class below.
raise ValueError('Timeout cannot be a float')
int(timeout)
except ValueError:
raise ValueError(
'\'{0}\' is not a valid timeout, must be an integer'
.format(timeout)
)
cmd.extend(['--timeout', timeout])
if pkgs:
if isinstance(pkgs, six.string_types):
pkgs = [p.strip() for p in pkgs.split(',')]
if requirements:
for requirement in requirements:
with salt.utils.files.fopen(requirement) as rq_:
for req in rq_:
req = salt.utils.stringutils.to_unicode(req)
try:
req_pkg, _ = req.split('==')
if req_pkg in pkgs:
pkgs.remove(req_pkg)
except ValueError:
pass
cmd.extend(pkgs)
cmd_kwargs = dict(python_shell=False, runas=user,
cwd=cwd, saltenv=saltenv, use_vt=use_vt)
if bin_env and os.path.isdir(bin_env):
cmd_kwargs['env'] = {'VIRTUAL_ENV': bin_env}
try:
return __salt__['cmd.run_all'](cmd, **cmd_kwargs)
finally:
_clear_context(bin_env)
for requirement in cleanup_requirements:
if requirement:
try:
os.remove(requirement)
except OSError:
pass
def freeze(bin_env=None,
user=None,
cwd=None,
use_vt=False,
env_vars=None,
**kwargs):
'''
Return a list of installed packages either globally or in the specified
virtualenv
bin_env
Path to pip (or to a virtualenv). This can be used to specify the path
to the pip to use when more than one Python release is installed (e.g.
``/usr/bin/pip-2.7`` or ``/usr/bin/pip-2.6``. If a directory path is
specified, it is assumed to be a virtualenv.
user
The user under which to run pip
cwd
Directory from which to run pip
.. note::
If the version of pip available is older than 8.0.3, the list will not
include the packages ``pip``, ``wheel``, ``setuptools``, or
``distribute`` even if they are installed.
CLI Example:
.. code-block:: bash
salt '*' pip.freeze bin_env=/home/code/path/to/virtualenv
'''
cmd = _get_pip_bin(bin_env)
cmd.append('freeze')
# Include pip, setuptools, distribute, wheel
min_version = '8.0.3'
cur_version = version(bin_env)
if salt.utils.versions.compare(ver1=cur_version, oper='<', ver2=min_version):
logger.warning(
'The version of pip installed is %s, which is older than %s. '
'The packages pip, wheel, setuptools, and distribute will not be '
'included in the output of pip.freeze', cur_version, min_version
)
else:
cmd.append('--all')
cmd_kwargs = dict(runas=user, cwd=cwd, use_vt=use_vt, python_shell=False)
if kwargs:
cmd_kwargs.update(**kwargs)
if bin_env and os.path.isdir(bin_env):
cmd_kwargs['env'] = {'VIRTUAL_ENV': bin_env}
if env_vars:
cmd_kwargs.setdefault('env', {}).update(_format_env_vars(env_vars))
result = __salt__['cmd.run_all'](cmd, **cmd_kwargs)
if result['retcode']:
raise CommandExecutionError(result['stderr'], info=result)
return result['stdout'].splitlines()
def list_(prefix=None,
bin_env=None,
user=None,
cwd=None,
env_vars=None,
**kwargs):
'''
Filter list of installed apps from ``freeze`` and check to see if
``prefix`` exists in the list of packages installed.
.. note::
If the version of pip available is older than 8.0.3, the packages
``wheel``, ``setuptools``, and ``distribute`` will not be reported by
this function even if they are installed. Unlike :py:func:`pip.freeze
<salt.modules.pip.freeze>`, this function always reports the version of
pip which is installed.
CLI Example:
.. code-block:: bash
salt '*' pip.list salt
'''
packages = {}
if prefix is None or 'pip'.startswith(prefix):
packages['pip'] = version(bin_env)
for line in freeze(bin_env=bin_env,
user=user,
cwd=cwd,
env_vars=env_vars,
**kwargs):
if line.startswith('-f') or line.startswith('#'):
# ignore -f line as it contains --find-links directory
# ignore comment lines
continue
elif line.startswith('-e hg+not trust'):
# ignore hg + not trust problem
continue
elif line.startswith('-e'):
line = line.split('-e ')[1]
if '#egg=' in line:
version_, name = line.split('#egg=')
else:
if len(line.split('===')) >= 2:
name = line.split('===')[0]
version_ = line.split('===')[1]
elif len(line.split('==')) >= 2:
name = line.split('==')[0]
version_ = line.split('==')[1]
elif len(line.split('===')) >= 2:
name = line.split('===')[0]
version_ = line.split('===')[1]
elif len(line.split('==')) >= 2:
name = line.split('==')[0]
version_ = line.split('==')[1]
else:
logger.error('Can\'t parse line \'%s\'', line)
continue
if prefix:
if name.lower().startswith(prefix.lower()):
packages[name] = version_
else:
packages[name] = version_
return packages
def list_upgrades(bin_env=None,
user=None,
cwd=None):
'''
Check whether or not an upgrade is available for all packages
CLI Example:
.. code-block:: bash
salt '*' pip.list_upgrades
'''
cmd = _get_pip_bin(bin_env)
cmd.extend(['list', '--outdated'])
pip_version = version(bin_env)
# Pip started supporting the ability to output json starting with 9.0.0
min_version = '9.0'
if salt.utils.versions.compare(ver1=pip_version,
oper='>=',
ver2=min_version):
cmd.append('--format=json')
cmd_kwargs = dict(cwd=cwd, runas=user)
if bin_env and os.path.isdir(bin_env):
cmd_kwargs['env'] = {'VIRTUAL_ENV': bin_env}
result = __salt__['cmd.run_all'](cmd, **cmd_kwargs)
if result['retcode']:
raise CommandExecutionError(result['stderr'], info=result)
packages = {}
# Pip started supporting the ability to output json starting with 9.0.0
# Older versions will have to parse stdout
if salt.utils.versions.compare(ver1=pip_version, oper='<', ver2='9.0.0'):
# Pip versions < 8.0.0 had a different output format
# Sample data:
# pip (Current: 7.1.2 Latest: 10.0.1 [wheel])
# psutil (Current: 5.2.2 Latest: 5.4.5 [wheel])
# pyasn1 (Current: 0.2.3 Latest: 0.4.2 [wheel])
# pycparser (Current: 2.17 Latest: 2.18 [sdist])
if salt.utils.versions.compare(ver1=pip_version, oper='<', ver2='8.0.0'):
logger.debug('pip module: Old output format')
pat = re.compile(r'(\S*)\s+\(.*Latest:\s+(.*)\)')
# New output format for version 8.0.0+
# Sample data:
# pip (8.0.0) - Latest: 10.0.1 [wheel]
# psutil (5.2.2) - Latest: 5.4.5 [wheel]
# pyasn1 (0.2.3) - Latest: 0.4.2 [wheel]
# pycparser (2.17) - Latest: 2.18 [sdist]
else:
logger.debug('pip module: New output format')
pat = re.compile(r'(\S*)\s+\(.*\)\s+-\s+Latest:\s+(.*)')
for line in result['stdout'].splitlines():
match = pat.search(line)
if match:
name, version_ = match.groups()
else:
logger.error('Can\'t parse line \'%s\'', line)
continue
packages[name] = version_
else:
logger.debug('pip module: JSON output format')
try:
pkgs = salt.utils.json.loads(result['stdout'], strict=False)
except ValueError:
raise CommandExecutionError('Invalid JSON', info=result)
for pkg in pkgs:
packages[pkg['name']] = '{0} [{1}]'.format(pkg['latest_version'],
pkg['latest_filetype'])
return packages
def is_installed(pkgname=None,
bin_env=None,
user=None,
cwd=None):
'''
.. versionadded:: 2018.3.0
Filter list of installed apps from ``freeze`` and return True or False if
``pkgname`` exists in the list of packages installed.
.. note::
If the version of pip available is older than 8.0.3, the packages
wheel, setuptools, and distribute will not be reported by this function
even if they are installed. Unlike :py:func:`pip.freeze
<salt.modules.pip.freeze>`, this function always reports the version of
pip which is installed.
CLI Example:
.. code-block:: bash
salt '*' pip.is_installed salt
'''
for line in freeze(bin_env=bin_env, user=user, cwd=cwd):
if line.startswith('-f') or line.startswith('#'):
# ignore -f line as it contains --find-links directory
# ignore comment lines
continue
elif line.startswith('-e hg+not trust'):
# ignore hg + not trust problem
continue
elif line.startswith('-e'):
line = line.split('-e ')[1]
version_, name = line.split('#egg=')
elif len(line.split('===')) >= 2:
name = line.split('===')[0]
version_ = line.split('===')[1]
elif len(line.split('==')) >= 2:
name = line.split('==')[0]
version_ = line.split('==')[1]
else:
logger.error('Can\'t parse line \'%s\'', line)
continue
if pkgname:
if pkgname == name.lower():
return True
return False
def upgrade_available(pkg,
bin_env=None,
user=None,
cwd=None):
'''
.. versionadded:: 2015.5.0
Check whether or not an upgrade is available for a given package
CLI Example:
.. code-block:: bash
salt '*' pip.upgrade_available <package name>
'''
return pkg in list_upgrades(bin_env=bin_env, user=user, cwd=cwd)
def upgrade(bin_env=None,
user=None,
cwd=None,
use_vt=False):
'''
.. versionadded:: 2015.5.0
Upgrades outdated pip packages.
.. note::
On Windows you can't update salt from pip using salt, so salt will be
skipped
Returns a dict containing the changes.
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
CLI Example:
.. code-block:: bash
salt '*' pip.upgrade
'''
ret = {'changes': {},
'result': True,
'comment': '',
}
cmd = _get_pip_bin(bin_env)
cmd.extend(['install', '-U'])
old = list_(bin_env=bin_env, user=user, cwd=cwd)
cmd_kwargs = dict(cwd=cwd, use_vt=use_vt)
if bin_env and os.path.isdir(bin_env):
cmd_kwargs['env'] = {'VIRTUAL_ENV': bin_env}
errors = False
for pkg in list_upgrades(bin_env=bin_env, user=user, cwd=cwd):
if pkg == 'salt':
if salt.utils.platform.is_windows():
continue
result = __salt__['cmd.run_all'](cmd + [pkg], **cmd_kwargs)
if result['retcode'] != 0:
errors = True
if 'stderr' in result:
ret['comment'] += result['stderr']
if errors:
ret['result'] = False
_clear_context(bin_env)
new = list_(bin_env=bin_env, user=user, cwd=cwd)
ret['changes'] = salt.utils.data.compare_dicts(old, new)
return ret
def list_all_versions(pkg,
bin_env=None,
include_alpha=False,
include_beta=False,
include_rc=False,
user=None,
cwd=None,
index_url=None,
extra_index_url=None):
'''
.. versionadded:: 2017.7.3
List all available versions of a pip package
pkg
The package to check
bin_env
Path to pip (or to a virtualenv). This can be used to specify the path
to the pip to use when more than one Python release is installed (e.g.
``/usr/bin/pip-2.7`` or ``/usr/bin/pip-2.6``. If a directory path is
specified, it is assumed to be a virtualenv.
include_alpha
Include alpha versions in the list
include_beta
Include beta versions in the list
include_rc
Include release candidates versions in the list
user
The user under which to run pip
cwd
Directory from which to run pip
index_url
Base URL of Python Package Index
.. versionadded:: 2019.2.0
extra_index_url
Additional URL of Python Package Index
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' pip.list_all_versions <package name>
'''
cmd = _get_pip_bin(bin_env)
cmd.extend(['install', '{0}==versions'.format(pkg)])
if index_url:
if not salt.utils.url.validate(index_url, VALID_PROTOS):
raise CommandExecutionError(
'\'{0}\' is not a valid URL'.format(index_url)
)
cmd.extend(['--index-url', index_url])
if extra_index_url:
if not salt.utils.url.validate(extra_index_url, VALID_PROTOS):
raise CommandExecutionError(
'\'{0}\' is not a valid URL'.format(extra_index_url)
)
cmd.extend(['--extra-index-url', extra_index_url])
cmd_kwargs = dict(cwd=cwd, runas=user, output_loglevel='quiet', redirect_stderr=True)
if bin_env and os.path.isdir(bin_env):
cmd_kwargs['env'] = {'VIRTUAL_ENV': bin_env}
result = __salt__['cmd.run_all'](cmd, **cmd_kwargs)
filtered = []
if not include_alpha:
filtered.append('a')
if not include_beta:
filtered.append('b')
if not include_rc:
filtered.append('rc')
if filtered:
excludes = re.compile(r'^((?!{0}).)*$'.format('|'.join(filtered)))
else:
excludes = re.compile(r'')
versions = []
for line in result['stdout'].splitlines():
match = re.search(r'\s*Could not find a version.* \(from versions: (.*)\)', line)
if match:
versions = [v for v in match.group(1).split(', ') if v and excludes.match(v)]
versions.sort(key=pkg_resources.parse_version)
break
if not versions:
return None
return versions
|
saltstack/salt
|
salt/modules/pip.py
|
list_upgrades
|
python
|
def list_upgrades(bin_env=None,
user=None,
cwd=None):
'''
Check whether or not an upgrade is available for all packages
CLI Example:
.. code-block:: bash
salt '*' pip.list_upgrades
'''
cmd = _get_pip_bin(bin_env)
cmd.extend(['list', '--outdated'])
pip_version = version(bin_env)
# Pip started supporting the ability to output json starting with 9.0.0
min_version = '9.0'
if salt.utils.versions.compare(ver1=pip_version,
oper='>=',
ver2=min_version):
cmd.append('--format=json')
cmd_kwargs = dict(cwd=cwd, runas=user)
if bin_env and os.path.isdir(bin_env):
cmd_kwargs['env'] = {'VIRTUAL_ENV': bin_env}
result = __salt__['cmd.run_all'](cmd, **cmd_kwargs)
if result['retcode']:
raise CommandExecutionError(result['stderr'], info=result)
packages = {}
# Pip started supporting the ability to output json starting with 9.0.0
# Older versions will have to parse stdout
if salt.utils.versions.compare(ver1=pip_version, oper='<', ver2='9.0.0'):
# Pip versions < 8.0.0 had a different output format
# Sample data:
# pip (Current: 7.1.2 Latest: 10.0.1 [wheel])
# psutil (Current: 5.2.2 Latest: 5.4.5 [wheel])
# pyasn1 (Current: 0.2.3 Latest: 0.4.2 [wheel])
# pycparser (Current: 2.17 Latest: 2.18 [sdist])
if salt.utils.versions.compare(ver1=pip_version, oper='<', ver2='8.0.0'):
logger.debug('pip module: Old output format')
pat = re.compile(r'(\S*)\s+\(.*Latest:\s+(.*)\)')
# New output format for version 8.0.0+
# Sample data:
# pip (8.0.0) - Latest: 10.0.1 [wheel]
# psutil (5.2.2) - Latest: 5.4.5 [wheel]
# pyasn1 (0.2.3) - Latest: 0.4.2 [wheel]
# pycparser (2.17) - Latest: 2.18 [sdist]
else:
logger.debug('pip module: New output format')
pat = re.compile(r'(\S*)\s+\(.*\)\s+-\s+Latest:\s+(.*)')
for line in result['stdout'].splitlines():
match = pat.search(line)
if match:
name, version_ = match.groups()
else:
logger.error('Can\'t parse line \'%s\'', line)
continue
packages[name] = version_
else:
logger.debug('pip module: JSON output format')
try:
pkgs = salt.utils.json.loads(result['stdout'], strict=False)
except ValueError:
raise CommandExecutionError('Invalid JSON', info=result)
for pkg in pkgs:
packages[pkg['name']] = '{0} [{1}]'.format(pkg['latest_version'],
pkg['latest_filetype'])
return packages
|
Check whether or not an upgrade is available for all packages
CLI Example:
.. code-block:: bash
salt '*' pip.list_upgrades
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/pip.py#L1261-L1336
|
[
"def version(bin_env=None):\n '''\n .. versionadded:: 0.17.0\n\n Returns the version of pip. Use ``bin_env`` to specify the path to a\n virtualenv and get the version of pip in that virtualenv.\n\n If unable to detect the pip version, returns ``None``.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' pip.version\n '''\n contextkey = 'pip.version'\n if bin_env is not None:\n contextkey = '{0}.{1}'.format(contextkey, bin_env)\n\n if contextkey in __context__:\n return __context__[contextkey]\n\n cmd = _get_pip_bin(bin_env)[:]\n cmd.append('--version')\n\n ret = __salt__['cmd.run_all'](cmd, python_shell=False)\n if ret['retcode']:\n raise CommandNotFoundError('Could not find a `pip` binary')\n\n try:\n pip_version = re.match(r'^pip (\\S+)', ret['stdout']).group(1)\n except AttributeError:\n pip_version = None\n\n __context__[contextkey] = pip_version\n return pip_version\n",
"def compare(ver1='', oper='==', ver2='', cmp_func=None, ignore_epoch=False):\n '''\n Compares two version numbers. Accepts a custom function to perform the\n cmp-style version comparison, otherwise uses version_cmp().\n '''\n cmp_map = {'<': (-1,), '<=': (-1, 0), '==': (0,),\n '>=': (0, 1), '>': (1,)}\n if oper not in ('!=',) and oper not in cmp_map:\n log.error('Invalid operator \\'%s\\' for version comparison', oper)\n return False\n\n if cmp_func is None:\n cmp_func = version_cmp\n\n cmp_result = cmp_func(ver1, ver2, ignore_epoch=ignore_epoch)\n if cmp_result is None:\n return False\n\n # Check if integer/long\n if not isinstance(cmp_result, numbers.Integral):\n log.error('The version comparison function did not return an '\n 'integer/long.')\n return False\n\n if oper == '!=':\n return cmp_result not in cmp_map['==']\n else:\n # Gracefully handle cmp_result not in (-1, 0, 1).\n if cmp_result < -1:\n cmp_result = -1\n elif cmp_result > 1:\n cmp_result = 1\n\n return cmp_result in cmp_map[oper]\n",
"def _get_pip_bin(bin_env):\n '''\n Locate the pip binary, either from `bin_env` as a virtualenv, as the\n executable itself, or from searching conventional filesystem locations\n '''\n if not bin_env:\n logger.debug('pip: Using pip from currently-running Python')\n return [os.path.normpath(sys.executable), '-m', 'pip']\n\n python_bin = 'python.exe' if salt.utils.platform.is_windows() else 'python'\n\n def _search_paths(*basedirs):\n ret = []\n for path in basedirs:\n ret.extend([\n os.path.join(path, python_bin),\n os.path.join(path, 'bin', python_bin),\n os.path.join(path, 'Scripts', python_bin)\n ])\n return ret\n\n # try to get python bin from virtualenv (i.e. bin_env)\n if os.path.isdir(bin_env):\n for bin_path in _search_paths(bin_env):\n if os.path.isfile(bin_path):\n if os.access(bin_path, os.X_OK):\n logger.debug('pip: Found python binary: %s', bin_path)\n return [os.path.normpath(bin_path), '-m', 'pip']\n else:\n logger.debug(\n 'pip: Found python binary by name but it is not '\n 'executable: %s', bin_path\n )\n raise CommandNotFoundError(\n 'Could not find a pip binary in virtualenv {0}'.format(bin_env)\n )\n\n # bin_env is the python or pip binary\n elif os.access(bin_env, os.X_OK):\n if os.path.isfile(bin_env):\n # If the python binary was passed, return it\n if 'python' in os.path.basename(bin_env):\n return [os.path.normpath(bin_env), '-m', 'pip']\n # We have been passed a pip binary, use the pip binary.\n return [os.path.normpath(bin_env)]\n\n raise CommandExecutionError(\n 'Could not find a pip binary within {0}'.format(bin_env)\n )\n else:\n raise CommandNotFoundError(\n 'Access denied to {0}, could not find a pip binary'.format(bin_env)\n )\n"
] |
# -*- coding: utf-8 -*-
r'''
Install Python packages with pip to either the system or a virtualenv
Windows Support
===============
.. versionadded:: 2014.7.4
Salt now uses a portable python. As a result the entire pip module is now
functional on the salt installation itself. You can pip install dependencies
for your custom modules. You can even upgrade salt itself using pip. For this
to work properly, you must specify the Current Working Directory (``cwd``) and
the Pip Binary (``bin_env``) salt should use. The variable ``pip_bin`` can be
either a virtualenv path or the path to the pip binary itself.
For example, the following command will list all software installed using pip
to your current salt environment:
.. code-block:: bat
salt <minion> pip.list cwd='C:\salt\bin\Scripts' bin_env='C:\salt\bin\Scripts\pip.exe'
Specifying the ``cwd`` and ``bin_env`` options ensures you're modifying the
salt environment. If these are omitted, it will default to the local
installation of python. If python is not installed locally it will fail saying
it couldn't find pip.
State File Support
------------------
This functionality works in states as well. If you need to pip install colorama
with a state, for example, the following will work:
.. code-block:: yaml
install_colorama:
pip.installed:
- name: colorama
- cwd: 'C:\salt\bin\scripts'
- bin_env: 'C:\salt\bin\scripts\pip.exe'
- upgrade: True
Upgrading Salt using Pip
------------------------
You can now update salt using pip to any version from the 2014.7 branch
forward. Previous version require recompiling some of the dependencies which is
painful in windows.
To do this you just use pip with git to update to the version you want and then
restart the service. Here is a sample state file that upgrades salt to the head
of the 2015.5 branch:
.. code-block:: yaml
install_salt:
pip.installed:
- cwd: 'C:\salt\bin\scripts'
- bin_env: 'C:\salt\bin\scripts\pip.exe'
- editable: git+https://github.com/saltstack/salt@2015.5#egg=salt
- upgrade: True
restart_service:
service.running:
- name: salt-minion
- enable: True
- watch:
- pip: install_salt
.. note::
If you're having problems, you might try doubling the back slashes. For
example, cwd: 'C:\\salt\\bin\\scripts'. Sometimes python thinks the single
back slash is an escape character.
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import logging
import os
try:
import pkg_resources
except ImportError:
pkg_resources = None
import re
import shutil
import sys
import tempfile
# Import Salt libs
import salt.utils.data
import salt.utils.files
import salt.utils.json
import salt.utils.locales
import salt.utils.platform
import salt.utils.stringutils
import salt.utils.url
import salt.utils.versions
from salt.ext import six
from salt.exceptions import CommandExecutionError, CommandNotFoundError
# This needs to be named logger so we don't shadow it in pip.install
logger = logging.getLogger(__name__) # pylint: disable=C0103
# Don't shadow built-in's.
__func_alias__ = {
'list_': 'list'
}
VALID_PROTOS = ['http', 'https', 'ftp', 'file']
rex_pip_chain_read = re.compile(r'-r\s(.*)\n?', re.MULTILINE)
def __virtual__():
'''
There is no way to verify that pip is installed without inspecting the
entire filesystem. If it's not installed in a conventional location, the
user is required to provide the location of pip each time it is used.
'''
if pkg_resources is None:
ret = False, 'Package dependency "pkg_resource" is missing'
else:
ret = 'pip'
return ret
def _clear_context(bin_env=None):
'''
Remove the cached pip version
'''
contextkey = 'pip.version'
if bin_env is not None:
contextkey = '{0}.{1}'.format(contextkey, bin_env)
__context__.pop(contextkey, None)
def _get_pip_bin(bin_env):
'''
Locate the pip binary, either from `bin_env` as a virtualenv, as the
executable itself, or from searching conventional filesystem locations
'''
if not bin_env:
logger.debug('pip: Using pip from currently-running Python')
return [os.path.normpath(sys.executable), '-m', 'pip']
python_bin = 'python.exe' if salt.utils.platform.is_windows() else 'python'
def _search_paths(*basedirs):
ret = []
for path in basedirs:
ret.extend([
os.path.join(path, python_bin),
os.path.join(path, 'bin', python_bin),
os.path.join(path, 'Scripts', python_bin)
])
return ret
# try to get python bin from virtualenv (i.e. bin_env)
if os.path.isdir(bin_env):
for bin_path in _search_paths(bin_env):
if os.path.isfile(bin_path):
if os.access(bin_path, os.X_OK):
logger.debug('pip: Found python binary: %s', bin_path)
return [os.path.normpath(bin_path), '-m', 'pip']
else:
logger.debug(
'pip: Found python binary by name but it is not '
'executable: %s', bin_path
)
raise CommandNotFoundError(
'Could not find a pip binary in virtualenv {0}'.format(bin_env)
)
# bin_env is the python or pip binary
elif os.access(bin_env, os.X_OK):
if os.path.isfile(bin_env):
# If the python binary was passed, return it
if 'python' in os.path.basename(bin_env):
return [os.path.normpath(bin_env), '-m', 'pip']
# We have been passed a pip binary, use the pip binary.
return [os.path.normpath(bin_env)]
raise CommandExecutionError(
'Could not find a pip binary within {0}'.format(bin_env)
)
else:
raise CommandNotFoundError(
'Access denied to {0}, could not find a pip binary'.format(bin_env)
)
def _get_cached_requirements(requirements, saltenv):
'''
Get the location of a cached requirements file; caching if necessary.
'''
req_file, senv = salt.utils.url.parse(requirements)
if senv:
saltenv = senv
if req_file not in __salt__['cp.list_master'](saltenv):
# Requirements file does not exist in the given saltenv.
return False
cached_requirements = __salt__['cp.is_cached'](
requirements, saltenv
)
if not cached_requirements:
# It's not cached, let's cache it.
cached_requirements = __salt__['cp.cache_file'](
requirements, saltenv
)
# Check if the master version has changed.
if __salt__['cp.hash_file'](requirements, saltenv) != \
__salt__['cp.hash_file'](cached_requirements, saltenv):
cached_requirements = __salt__['cp.cache_file'](
requirements, saltenv
)
return cached_requirements
def _get_env_activate(bin_env):
'''
Return the path to the activate binary
'''
if not bin_env:
raise CommandNotFoundError('Could not find a `activate` binary')
if os.path.isdir(bin_env):
if salt.utils.platform.is_windows():
activate_bin = os.path.join(bin_env, 'Scripts', 'activate.bat')
else:
activate_bin = os.path.join(bin_env, 'bin', 'activate')
if os.path.isfile(activate_bin):
return activate_bin
raise CommandNotFoundError('Could not find a `activate` binary')
def _find_req(link):
logger.info('_find_req -- link = %s', link)
with salt.utils.files.fopen(link) as fh_link:
child_links = rex_pip_chain_read.findall(
salt.utils.stringutils.to_unicode(fh_link.read())
)
base_path = os.path.dirname(link)
child_links = [os.path.join(base_path, d) for d in child_links]
return child_links
def _resolve_requirements_chain(requirements):
'''
Return an array of requirements file paths that can be used to complete
the no_chown==False && user != None conundrum
'''
chain = []
if isinstance(requirements, six.string_types):
requirements = [requirements]
for req_file in requirements:
chain.append(req_file)
chain.extend(_resolve_requirements_chain(_find_req(req_file)))
return chain
def _process_requirements(requirements, cmd, cwd, saltenv, user):
'''
Process the requirements argument
'''
cleanup_requirements = []
if requirements is not None:
if isinstance(requirements, six.string_types):
requirements = [r.strip() for r in requirements.split(',')]
elif not isinstance(requirements, list):
raise TypeError('requirements must be a string or list')
treq = None
for requirement in requirements:
logger.debug('TREQ IS: %s', treq)
if requirement.startswith('salt://'):
cached_requirements = _get_cached_requirements(
requirement, saltenv
)
if not cached_requirements:
ret = {'result': False,
'comment': 'pip requirements file \'{0}\' not found'
.format(requirement)}
return None, ret
requirement = cached_requirements
if user:
# Need to make a temporary copy since the user will, most
# likely, not have the right permissions to read the file
if not treq:
treq = tempfile.mkdtemp()
__salt__['file.chown'](treq, user, None)
# In Windows, just being owner of a file isn't enough. You also
# need permissions
if salt.utils.platform.is_windows():
__utils__['dacl.set_permissions'](
obj_name=treq,
principal=user,
permissions='read_execute')
current_directory = None
if not current_directory:
current_directory = os.path.abspath(os.curdir)
logger.info('_process_requirements from directory, '
'%s -- requirement: %s', cwd, requirement)
if cwd is None:
r = requirement
c = cwd
requirement_abspath = os.path.abspath(requirement)
cwd = os.path.dirname(requirement_abspath)
requirement = os.path.basename(requirement)
logger.debug('\n\tcwd: %s -> %s\n\trequirement: %s -> %s\n',
c, cwd, r, requirement
)
os.chdir(cwd)
reqs = _resolve_requirements_chain(requirement)
os.chdir(current_directory)
logger.info('request files: %s', reqs)
for req_file in reqs:
if not os.path.isabs(req_file):
req_file = os.path.join(cwd, req_file)
logger.debug('TREQ N CWD: %s -- %s -- for %s', treq, cwd, req_file)
target_path = os.path.join(treq, os.path.basename(req_file))
logger.debug('S: %s', req_file)
logger.debug('T: %s', target_path)
target_base = os.path.dirname(target_path)
if not os.path.exists(target_base):
os.makedirs(target_base, mode=0o755)
__salt__['file.chown'](target_base, user, None)
if not os.path.exists(target_path):
logger.debug(
'Copying %s to %s', req_file, target_path
)
__salt__['file.copy'](req_file, target_path)
logger.debug(
'Changing ownership of requirements file \'%s\' to '
'user \'%s\'', target_path, user
)
__salt__['file.chown'](target_path, user, None)
req_args = os.path.join(treq, requirement) if treq else requirement
cmd.extend(['--requirement', req_args])
cleanup_requirements.append(treq)
logger.debug('CLEANUP_REQUIREMENTS: %s', cleanup_requirements)
return cleanup_requirements, None
def _format_env_vars(env_vars):
ret = {}
if env_vars:
if isinstance(env_vars, dict):
for key, val in six.iteritems(env_vars):
if not isinstance(key, six.string_types):
key = str(key) # future lint: disable=blacklisted-function
if not isinstance(val, six.string_types):
val = str(val) # future lint: disable=blacklisted-function
ret[key] = val
else:
raise CommandExecutionError(
'env_vars {0} is not a dictionary'.format(env_vars))
return ret
def install(pkgs=None, # pylint: disable=R0912,R0913,R0914
requirements=None,
bin_env=None,
use_wheel=False,
no_use_wheel=False,
log=None,
proxy=None,
timeout=None,
editable=None,
find_links=None,
index_url=None,
extra_index_url=None,
no_index=False,
mirrors=None,
build=None,
target=None,
download=None,
download_cache=None,
source=None,
upgrade=False,
force_reinstall=False,
ignore_installed=False,
exists_action=None,
no_deps=False,
no_install=False,
no_download=False,
global_options=None,
install_options=None,
user=None,
cwd=None,
pre_releases=False,
cert=None,
allow_all_external=False,
allow_external=None,
allow_unverified=None,
process_dependency_links=False,
saltenv='base',
env_vars=None,
use_vt=False,
trusted_host=None,
no_cache_dir=False,
cache_dir=None,
no_binary=None,
extra_args=None,
**kwargs):
'''
Install packages with pip
Install packages individually or from a pip requirements file. Install
packages globally or to a virtualenv.
pkgs
Comma separated list of packages to install
requirements
Path to requirements
bin_env
Path to pip (or to a virtualenv). This can be used to specify the path
to the pip to use when more than one Python release is installed (e.g.
``/usr/bin/pip-2.7`` or ``/usr/bin/pip-2.6``. If a directory path is
specified, it is assumed to be a virtualenv.
.. note::
For Windows, if the pip module is being used to upgrade the pip
package, bin_env should be the path to the virtualenv or to the
python binary that should be used. The pip command is unable to
upgrade itself in Windows.
use_wheel
Prefer wheel archives (requires pip>=1.4)
no_use_wheel
Force to not use wheel archives (requires pip>=1.4,<10.0.0)
no_binary
Force to not use binary packages (requires pip >= 7.0.0)
Accepts either :all: to disable all binary packages, :none: to empty the set,
or one or more package names with commas between them
log
Log file where a complete (maximum verbosity) record will be kept
proxy
Specify a proxy in the form ``user:passwd@proxy.server:port``. Note
that the ``user:password@`` is optional and required only if you are
behind an authenticated proxy. If you provide
``user@proxy.server:port`` then you will be prompted for a password.
timeout
Set the socket timeout (default 15 seconds)
editable
install something editable (e.g.
``git+https://github.com/worldcompany/djangoembed.git#egg=djangoembed``)
find_links
URL to search for packages
index_url
Base URL of Python Package Index
extra_index_url
Extra URLs of package indexes to use in addition to ``index_url``
no_index
Ignore package index
mirrors
Specific mirror URL(s) to query (automatically adds --use-mirrors)
.. warning::
This option has been deprecated and removed in pip version 7.0.0.
Please use ``index_url`` and/or ``extra_index_url`` instead.
build
Unpack packages into ``build`` dir
target
Install packages into ``target`` dir
download
Download packages into ``download`` instead of installing them
download_cache | cache_dir
Cache downloaded packages in ``download_cache`` or ``cache_dir`` dir
source
Check out ``editable`` packages into ``source`` dir
upgrade
Upgrade all packages to the newest available version
force_reinstall
When upgrading, reinstall all packages even if they are already
up-to-date.
ignore_installed
Ignore the installed packages (reinstalling instead)
exists_action
Default action when a path already exists: (s)witch, (i)gnore, (w)ipe,
(b)ackup
no_deps
Ignore package dependencies
no_install
Download and unpack all packages, but don't actually install them
no_download
Don't download any packages, just install the ones already downloaded
(completes an install run with ``--no-install``)
install_options
Extra arguments to be supplied to the setup.py install command (e.g.
like ``--install-option='--install-scripts=/usr/local/bin'``). Use
multiple --install-option options to pass multiple options to setup.py
install. If you are using an option with a directory path, be sure to
use absolute path.
global_options
Extra global options to be supplied to the setup.py call before the
install command.
user
The user under which to run pip
cwd
Directory from which to run pip
pre_releases
Include pre-releases in the available versions
cert
Provide a path to an alternate CA bundle
allow_all_external
Allow the installation of all externally hosted files
allow_external
Allow the installation of externally hosted files (comma separated
list)
allow_unverified
Allow the installation of insecure and unverifiable files (comma
separated list)
process_dependency_links
Enable the processing of dependency links
env_vars
Set environment variables that some builds will depend on. For example,
a Python C-module may have a Makefile that needs INCLUDE_PATH set to
pick up a header file while compiling. This must be in the form of a
dictionary or a mapping.
Example:
.. code-block:: bash
salt '*' pip.install django_app env_vars="{'CUSTOM_PATH': '/opt/django_app'}"
trusted_host
Mark this host as trusted, even though it does not have valid or any
HTTPS.
use_vt
Use VT terminal emulation (see output while installing)
no_cache_dir
Disable the cache.
extra_args
pip keyword and positional arguments not yet implemented in salt
.. code-block:: yaml
salt '*' pip.install pandas extra_args="[{'--latest-pip-kwarg':'param'}, '--latest-pip-arg']"
.. warning::
If unsupported options are passed here that are not supported in a
minion's version of pip, a `No such option error` will be thrown.
Will be translated into the following pip command:
.. code-block:: bash
pip install pandas --latest-pip-kwarg param --latest-pip-arg
CLI Example:
.. code-block:: bash
salt '*' pip.install <package name>,<package2 name>
salt '*' pip.install requirements=/path/to/requirements.txt
salt '*' pip.install <package name> bin_env=/path/to/virtualenv
salt '*' pip.install <package name> bin_env=/path/to/pip_bin
Complicated CLI example::
salt '*' pip.install markdown,django \
editable=git+https://github.com/worldcompany/djangoembed.git#egg=djangoembed upgrade=True no_deps=True
'''
cmd = _get_pip_bin(bin_env)
cmd.append('install')
cleanup_requirements, error = _process_requirements(
requirements=requirements,
cmd=cmd,
cwd=cwd,
saltenv=saltenv,
user=user
)
if error:
return error
cur_version = version(bin_env)
if use_wheel:
min_version = '1.4'
max_version = '9.0.3'
too_low = salt.utils.versions.compare(ver1=cur_version, oper='<', ver2=min_version)
too_high = salt.utils.versions.compare(ver1=cur_version, oper='>', ver2=max_version)
if too_low or too_high:
logger.error(
'The --use-wheel option is only supported in pip between %s and '
'%s. The version of pip detected is %s. This option '
'will be ignored.', min_version, max_version, cur_version
)
else:
cmd.append('--use-wheel')
if no_use_wheel:
min_version = '1.4'
max_version = '9.0.3'
too_low = salt.utils.versions.compare(ver1=cur_version, oper='<', ver2=min_version)
too_high = salt.utils.versions.compare(ver1=cur_version, oper='>', ver2=max_version)
if too_low or too_high:
logger.error(
'The --no-use-wheel option is only supported in pip between %s and '
'%s. The version of pip detected is %s. This option '
'will be ignored.', min_version, max_version, cur_version
)
else:
cmd.append('--no-use-wheel')
if no_binary:
min_version = '7.0.0'
too_low = salt.utils.versions.compare(ver1=cur_version, oper='<', ver2=min_version)
if too_low:
logger.error(
'The --no-binary option is only supported in pip %s and '
'newer. The version of pip detected is %s. This option '
'will be ignored.', min_version, cur_version
)
else:
if isinstance(no_binary, list):
no_binary = ','.join(no_binary)
cmd.extend(['--no-binary', no_binary])
if log:
if os.path.isdir(log):
raise IOError(
'\'{0}\' is a directory. Use --log path_to_file'.format(log))
elif not os.access(log, os.W_OK):
raise IOError('\'{0}\' is not writeable'.format(log))
cmd.extend(['--log', log])
if proxy:
cmd.extend(['--proxy', proxy])
if timeout:
try:
if isinstance(timeout, float):
# Catch floating point input, exception will be caught in
# exception class below.
raise ValueError('Timeout cannot be a float')
int(timeout)
except ValueError:
raise ValueError(
'\'{0}\' is not a valid timeout, must be an integer'
.format(timeout)
)
cmd.extend(['--timeout', timeout])
if find_links:
if isinstance(find_links, six.string_types):
find_links = [l.strip() for l in find_links.split(',')]
for link in find_links:
if not (salt.utils.url.validate(link, VALID_PROTOS) or os.path.exists(link)):
raise CommandExecutionError(
'\'{0}\' is not a valid URL or path'.format(link)
)
cmd.extend(['--find-links', link])
if no_index and (index_url or extra_index_url):
raise CommandExecutionError(
'\'no_index\' and (\'index_url\' or \'extra_index_url\') are '
'mutually exclusive.'
)
if index_url:
if not salt.utils.url.validate(index_url, VALID_PROTOS):
raise CommandExecutionError(
'\'{0}\' is not a valid URL'.format(index_url)
)
cmd.extend(['--index-url', index_url])
if extra_index_url:
if not salt.utils.url.validate(extra_index_url, VALID_PROTOS):
raise CommandExecutionError(
'\'{0}\' is not a valid URL'.format(extra_index_url)
)
cmd.extend(['--extra-index-url', extra_index_url])
if no_index:
cmd.append('--no-index')
if mirrors:
# https://github.com/pypa/pip/pull/2641/files#diff-3ef137fb9ffdd400f117a565cd94c188L216
if salt.utils.versions.compare(ver1=cur_version, oper='>=', ver2='7.0.0'):
raise CommandExecutionError(
'pip >= 7.0.0 does not support mirror argument:'
' use index_url and/or extra_index_url instead'
)
if isinstance(mirrors, six.string_types):
mirrors = [m.strip() for m in mirrors.split(',')]
cmd.append('--use-mirrors')
for mirror in mirrors:
if not mirror.startswith('http://'):
raise CommandExecutionError(
'\'{0}\' is not a valid URL'.format(mirror)
)
cmd.extend(['--mirrors', mirror])
if build:
cmd.extend(['--build', build])
if target:
cmd.extend(['--target', target])
if download:
cmd.extend(['--download', download])
if download_cache or cache_dir:
cmd.extend(['--cache-dir' if salt.utils.versions.compare(
ver1=cur_version, oper='>=', ver2='6.0'
) else '--download-cache', download_cache or cache_dir])
if source:
cmd.extend(['--source', source])
if upgrade:
cmd.append('--upgrade')
if force_reinstall:
cmd.append('--force-reinstall')
if ignore_installed:
cmd.append('--ignore-installed')
if exists_action:
if exists_action.lower() not in ('s', 'i', 'w', 'b'):
raise CommandExecutionError(
'The exists_action pip option only supports the values '
's, i, w, and b. \'{0}\' is not valid.'.format(exists_action)
)
cmd.extend(['--exists-action', exists_action])
if no_deps:
cmd.append('--no-deps')
if no_install:
cmd.append('--no-install')
if no_download:
cmd.append('--no-download')
if no_cache_dir:
cmd.append('--no-cache-dir')
if pre_releases:
# Check the locally installed pip version
pip_version = cur_version
# From pip v1.4 the --pre flag is available
if salt.utils.versions.compare(ver1=pip_version, oper='>=', ver2='1.4'):
cmd.append('--pre')
if cert:
cmd.extend(['--cert', cert])
if global_options:
if isinstance(global_options, six.string_types):
global_options = [go.strip() for go in global_options.split(',')]
for opt in global_options:
cmd.extend(['--global-option', opt])
if install_options:
if isinstance(install_options, six.string_types):
install_options = [io.strip() for io in install_options.split(',')]
for opt in install_options:
cmd.extend(['--install-option', opt])
if pkgs:
if not isinstance(pkgs, list):
try:
pkgs = [p.strip() for p in pkgs.split(',')]
except AttributeError:
pkgs = [p.strip() for p in six.text_type(pkgs).split(',')]
pkgs = salt.utils.data.stringify(salt.utils.data.decode_list(pkgs))
# It's possible we replaced version-range commas with semicolons so
# they would survive the previous line (in the pip.installed state).
# Put the commas back in while making sure the names are contained in
# quotes, this allows for proper version spec passing salt>=0.17.0
cmd.extend([p.replace(';', ',') for p in pkgs])
elif not any([requirements, editable]):
# Starting with pip 10.0.0, if no packages are specified in the
# command, it returns a retcode 1. So instead of running the command,
# just return the output without running pip.
return {'retcode': 0, 'stdout': 'No packages to install.'}
if editable:
egg_match = re.compile(r'(?:#|#.*?&)egg=([^&]*)')
if isinstance(editable, six.string_types):
editable = [e.strip() for e in editable.split(',')]
for entry in editable:
# Is the editable local?
if not (entry == '.' or entry.startswith(('file://', '/'))):
match = egg_match.search(entry)
if not match or not match.group(1):
# Missing #egg=theEggName
raise CommandExecutionError(
'You must specify an egg for this editable'
)
cmd.extend(['--editable', entry])
if allow_all_external:
cmd.append('--allow-all-external')
if allow_external:
if isinstance(allow_external, six.string_types):
allow_external = [p.strip() for p in allow_external.split(',')]
for pkg in allow_external:
cmd.extend(['--allow-external', pkg])
if allow_unverified:
if isinstance(allow_unverified, six.string_types):
allow_unverified = \
[p.strip() for p in allow_unverified.split(',')]
for pkg in allow_unverified:
cmd.extend(['--allow-unverified', pkg])
if process_dependency_links:
cmd.append('--process-dependency-links')
if trusted_host:
cmd.extend(['--trusted-host', trusted_host])
if extra_args:
# These are arguments from the latest version of pip that
# have not yet been implemented in salt
for arg in extra_args:
# It is a keyword argument
if isinstance(arg, dict):
# There will only ever be one item in this dictionary
key, val = arg.popitem()
# Don't allow any recursion into keyword arg definitions
# Don't allow multiple definitions of a keyword
if isinstance(val, (dict, list)):
raise TypeError("Too many levels in: {}".format(key))
# This is a a normal one-to-one keyword argument
cmd.extend([key, val])
# It is a positional argument, append it to the list
else:
cmd.append(arg)
cmd_kwargs = dict(saltenv=saltenv, use_vt=use_vt, runas=user)
if kwargs:
cmd_kwargs.update(kwargs)
if env_vars:
cmd_kwargs.setdefault('env', {}).update(_format_env_vars(env_vars))
try:
if cwd:
cmd_kwargs['cwd'] = cwd
if bin_env and os.path.isdir(bin_env):
cmd_kwargs.setdefault('env', {})['VIRTUAL_ENV'] = bin_env
logger.debug(
'TRY BLOCK: end of pip.install -- cmd: %s, cmd_kwargs: %s',
cmd, cmd_kwargs
)
return __salt__['cmd.run_all'](cmd, python_shell=False, **cmd_kwargs)
finally:
_clear_context(bin_env)
for tempdir in [cr for cr in cleanup_requirements if cr is not None]:
if os.path.isdir(tempdir):
shutil.rmtree(tempdir)
def uninstall(pkgs=None,
requirements=None,
bin_env=None,
log=None,
proxy=None,
timeout=None,
user=None,
cwd=None,
saltenv='base',
use_vt=False):
'''
Uninstall packages individually or from a pip requirements file
pkgs
comma separated list of packages to install
requirements
Path to requirements file
bin_env
Path to pip (or to a virtualenv). This can be used to specify the path
to the pip to use when more than one Python release is installed (e.g.
``/usr/bin/pip-2.7`` or ``/usr/bin/pip-2.6``. If a directory path is
specified, it is assumed to be a virtualenv.
log
Log file where a complete (maximum verbosity) record will be kept
proxy
Specify a proxy in the format ``user:passwd@proxy.server:port``. Note
that the ``user:password@`` is optional and required only if you are
behind an authenticated proxy. If you provide
``user@proxy.server:port`` then you will be prompted for a password.
timeout
Set the socket timeout (default 15 seconds)
user
The user under which to run pip
cwd
Directory from which to run pip
use_vt
Use VT terminal emulation (see output while installing)
CLI Example:
.. code-block:: bash
salt '*' pip.uninstall <package name>,<package2 name>
salt '*' pip.uninstall requirements=/path/to/requirements.txt
salt '*' pip.uninstall <package name> bin_env=/path/to/virtualenv
salt '*' pip.uninstall <package name> bin_env=/path/to/pip_bin
'''
cmd = _get_pip_bin(bin_env)
cmd.extend(['uninstall', '-y'])
cleanup_requirements, error = _process_requirements(
requirements=requirements, cmd=cmd, saltenv=saltenv, user=user,
cwd=cwd
)
if error:
return error
if log:
try:
# TODO make this check if writeable
os.path.exists(log)
except IOError:
raise IOError('\'{0}\' is not writeable'.format(log))
cmd.extend(['--log', log])
if proxy:
cmd.extend(['--proxy', proxy])
if timeout:
try:
if isinstance(timeout, float):
# Catch floating point input, exception will be caught in
# exception class below.
raise ValueError('Timeout cannot be a float')
int(timeout)
except ValueError:
raise ValueError(
'\'{0}\' is not a valid timeout, must be an integer'
.format(timeout)
)
cmd.extend(['--timeout', timeout])
if pkgs:
if isinstance(pkgs, six.string_types):
pkgs = [p.strip() for p in pkgs.split(',')]
if requirements:
for requirement in requirements:
with salt.utils.files.fopen(requirement) as rq_:
for req in rq_:
req = salt.utils.stringutils.to_unicode(req)
try:
req_pkg, _ = req.split('==')
if req_pkg in pkgs:
pkgs.remove(req_pkg)
except ValueError:
pass
cmd.extend(pkgs)
cmd_kwargs = dict(python_shell=False, runas=user,
cwd=cwd, saltenv=saltenv, use_vt=use_vt)
if bin_env and os.path.isdir(bin_env):
cmd_kwargs['env'] = {'VIRTUAL_ENV': bin_env}
try:
return __salt__['cmd.run_all'](cmd, **cmd_kwargs)
finally:
_clear_context(bin_env)
for requirement in cleanup_requirements:
if requirement:
try:
os.remove(requirement)
except OSError:
pass
def freeze(bin_env=None,
user=None,
cwd=None,
use_vt=False,
env_vars=None,
**kwargs):
'''
Return a list of installed packages either globally or in the specified
virtualenv
bin_env
Path to pip (or to a virtualenv). This can be used to specify the path
to the pip to use when more than one Python release is installed (e.g.
``/usr/bin/pip-2.7`` or ``/usr/bin/pip-2.6``. If a directory path is
specified, it is assumed to be a virtualenv.
user
The user under which to run pip
cwd
Directory from which to run pip
.. note::
If the version of pip available is older than 8.0.3, the list will not
include the packages ``pip``, ``wheel``, ``setuptools``, or
``distribute`` even if they are installed.
CLI Example:
.. code-block:: bash
salt '*' pip.freeze bin_env=/home/code/path/to/virtualenv
'''
cmd = _get_pip_bin(bin_env)
cmd.append('freeze')
# Include pip, setuptools, distribute, wheel
min_version = '8.0.3'
cur_version = version(bin_env)
if salt.utils.versions.compare(ver1=cur_version, oper='<', ver2=min_version):
logger.warning(
'The version of pip installed is %s, which is older than %s. '
'The packages pip, wheel, setuptools, and distribute will not be '
'included in the output of pip.freeze', cur_version, min_version
)
else:
cmd.append('--all')
cmd_kwargs = dict(runas=user, cwd=cwd, use_vt=use_vt, python_shell=False)
if kwargs:
cmd_kwargs.update(**kwargs)
if bin_env and os.path.isdir(bin_env):
cmd_kwargs['env'] = {'VIRTUAL_ENV': bin_env}
if env_vars:
cmd_kwargs.setdefault('env', {}).update(_format_env_vars(env_vars))
result = __salt__['cmd.run_all'](cmd, **cmd_kwargs)
if result['retcode']:
raise CommandExecutionError(result['stderr'], info=result)
return result['stdout'].splitlines()
def list_(prefix=None,
bin_env=None,
user=None,
cwd=None,
env_vars=None,
**kwargs):
'''
Filter list of installed apps from ``freeze`` and check to see if
``prefix`` exists in the list of packages installed.
.. note::
If the version of pip available is older than 8.0.3, the packages
``wheel``, ``setuptools``, and ``distribute`` will not be reported by
this function even if they are installed. Unlike :py:func:`pip.freeze
<salt.modules.pip.freeze>`, this function always reports the version of
pip which is installed.
CLI Example:
.. code-block:: bash
salt '*' pip.list salt
'''
packages = {}
if prefix is None or 'pip'.startswith(prefix):
packages['pip'] = version(bin_env)
for line in freeze(bin_env=bin_env,
user=user,
cwd=cwd,
env_vars=env_vars,
**kwargs):
if line.startswith('-f') or line.startswith('#'):
# ignore -f line as it contains --find-links directory
# ignore comment lines
continue
elif line.startswith('-e hg+not trust'):
# ignore hg + not trust problem
continue
elif line.startswith('-e'):
line = line.split('-e ')[1]
if '#egg=' in line:
version_, name = line.split('#egg=')
else:
if len(line.split('===')) >= 2:
name = line.split('===')[0]
version_ = line.split('===')[1]
elif len(line.split('==')) >= 2:
name = line.split('==')[0]
version_ = line.split('==')[1]
elif len(line.split('===')) >= 2:
name = line.split('===')[0]
version_ = line.split('===')[1]
elif len(line.split('==')) >= 2:
name = line.split('==')[0]
version_ = line.split('==')[1]
else:
logger.error('Can\'t parse line \'%s\'', line)
continue
if prefix:
if name.lower().startswith(prefix.lower()):
packages[name] = version_
else:
packages[name] = version_
return packages
def version(bin_env=None):
'''
.. versionadded:: 0.17.0
Returns the version of pip. Use ``bin_env`` to specify the path to a
virtualenv and get the version of pip in that virtualenv.
If unable to detect the pip version, returns ``None``.
CLI Example:
.. code-block:: bash
salt '*' pip.version
'''
contextkey = 'pip.version'
if bin_env is not None:
contextkey = '{0}.{1}'.format(contextkey, bin_env)
if contextkey in __context__:
return __context__[contextkey]
cmd = _get_pip_bin(bin_env)[:]
cmd.append('--version')
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
if ret['retcode']:
raise CommandNotFoundError('Could not find a `pip` binary')
try:
pip_version = re.match(r'^pip (\S+)', ret['stdout']).group(1)
except AttributeError:
pip_version = None
__context__[contextkey] = pip_version
return pip_version
def is_installed(pkgname=None,
bin_env=None,
user=None,
cwd=None):
'''
.. versionadded:: 2018.3.0
Filter list of installed apps from ``freeze`` and return True or False if
``pkgname`` exists in the list of packages installed.
.. note::
If the version of pip available is older than 8.0.3, the packages
wheel, setuptools, and distribute will not be reported by this function
even if they are installed. Unlike :py:func:`pip.freeze
<salt.modules.pip.freeze>`, this function always reports the version of
pip which is installed.
CLI Example:
.. code-block:: bash
salt '*' pip.is_installed salt
'''
for line in freeze(bin_env=bin_env, user=user, cwd=cwd):
if line.startswith('-f') or line.startswith('#'):
# ignore -f line as it contains --find-links directory
# ignore comment lines
continue
elif line.startswith('-e hg+not trust'):
# ignore hg + not trust problem
continue
elif line.startswith('-e'):
line = line.split('-e ')[1]
version_, name = line.split('#egg=')
elif len(line.split('===')) >= 2:
name = line.split('===')[0]
version_ = line.split('===')[1]
elif len(line.split('==')) >= 2:
name = line.split('==')[0]
version_ = line.split('==')[1]
else:
logger.error('Can\'t parse line \'%s\'', line)
continue
if pkgname:
if pkgname == name.lower():
return True
return False
def upgrade_available(pkg,
bin_env=None,
user=None,
cwd=None):
'''
.. versionadded:: 2015.5.0
Check whether or not an upgrade is available for a given package
CLI Example:
.. code-block:: bash
salt '*' pip.upgrade_available <package name>
'''
return pkg in list_upgrades(bin_env=bin_env, user=user, cwd=cwd)
def upgrade(bin_env=None,
user=None,
cwd=None,
use_vt=False):
'''
.. versionadded:: 2015.5.0
Upgrades outdated pip packages.
.. note::
On Windows you can't update salt from pip using salt, so salt will be
skipped
Returns a dict containing the changes.
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
CLI Example:
.. code-block:: bash
salt '*' pip.upgrade
'''
ret = {'changes': {},
'result': True,
'comment': '',
}
cmd = _get_pip_bin(bin_env)
cmd.extend(['install', '-U'])
old = list_(bin_env=bin_env, user=user, cwd=cwd)
cmd_kwargs = dict(cwd=cwd, use_vt=use_vt)
if bin_env and os.path.isdir(bin_env):
cmd_kwargs['env'] = {'VIRTUAL_ENV': bin_env}
errors = False
for pkg in list_upgrades(bin_env=bin_env, user=user, cwd=cwd):
if pkg == 'salt':
if salt.utils.platform.is_windows():
continue
result = __salt__['cmd.run_all'](cmd + [pkg], **cmd_kwargs)
if result['retcode'] != 0:
errors = True
if 'stderr' in result:
ret['comment'] += result['stderr']
if errors:
ret['result'] = False
_clear_context(bin_env)
new = list_(bin_env=bin_env, user=user, cwd=cwd)
ret['changes'] = salt.utils.data.compare_dicts(old, new)
return ret
def list_all_versions(pkg,
bin_env=None,
include_alpha=False,
include_beta=False,
include_rc=False,
user=None,
cwd=None,
index_url=None,
extra_index_url=None):
'''
.. versionadded:: 2017.7.3
List all available versions of a pip package
pkg
The package to check
bin_env
Path to pip (or to a virtualenv). This can be used to specify the path
to the pip to use when more than one Python release is installed (e.g.
``/usr/bin/pip-2.7`` or ``/usr/bin/pip-2.6``. If a directory path is
specified, it is assumed to be a virtualenv.
include_alpha
Include alpha versions in the list
include_beta
Include beta versions in the list
include_rc
Include release candidates versions in the list
user
The user under which to run pip
cwd
Directory from which to run pip
index_url
Base URL of Python Package Index
.. versionadded:: 2019.2.0
extra_index_url
Additional URL of Python Package Index
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' pip.list_all_versions <package name>
'''
cmd = _get_pip_bin(bin_env)
cmd.extend(['install', '{0}==versions'.format(pkg)])
if index_url:
if not salt.utils.url.validate(index_url, VALID_PROTOS):
raise CommandExecutionError(
'\'{0}\' is not a valid URL'.format(index_url)
)
cmd.extend(['--index-url', index_url])
if extra_index_url:
if not salt.utils.url.validate(extra_index_url, VALID_PROTOS):
raise CommandExecutionError(
'\'{0}\' is not a valid URL'.format(extra_index_url)
)
cmd.extend(['--extra-index-url', extra_index_url])
cmd_kwargs = dict(cwd=cwd, runas=user, output_loglevel='quiet', redirect_stderr=True)
if bin_env and os.path.isdir(bin_env):
cmd_kwargs['env'] = {'VIRTUAL_ENV': bin_env}
result = __salt__['cmd.run_all'](cmd, **cmd_kwargs)
filtered = []
if not include_alpha:
filtered.append('a')
if not include_beta:
filtered.append('b')
if not include_rc:
filtered.append('rc')
if filtered:
excludes = re.compile(r'^((?!{0}).)*$'.format('|'.join(filtered)))
else:
excludes = re.compile(r'')
versions = []
for line in result['stdout'].splitlines():
match = re.search(r'\s*Could not find a version.* \(from versions: (.*)\)', line)
if match:
versions = [v for v in match.group(1).split(', ') if v and excludes.match(v)]
versions.sort(key=pkg_resources.parse_version)
break
if not versions:
return None
return versions
|
saltstack/salt
|
salt/modules/pip.py
|
is_installed
|
python
|
def is_installed(pkgname=None,
bin_env=None,
user=None,
cwd=None):
'''
.. versionadded:: 2018.3.0
Filter list of installed apps from ``freeze`` and return True or False if
``pkgname`` exists in the list of packages installed.
.. note::
If the version of pip available is older than 8.0.3, the packages
wheel, setuptools, and distribute will not be reported by this function
even if they are installed. Unlike :py:func:`pip.freeze
<salt.modules.pip.freeze>`, this function always reports the version of
pip which is installed.
CLI Example:
.. code-block:: bash
salt '*' pip.is_installed salt
'''
for line in freeze(bin_env=bin_env, user=user, cwd=cwd):
if line.startswith('-f') or line.startswith('#'):
# ignore -f line as it contains --find-links directory
# ignore comment lines
continue
elif line.startswith('-e hg+not trust'):
# ignore hg + not trust problem
continue
elif line.startswith('-e'):
line = line.split('-e ')[1]
version_, name = line.split('#egg=')
elif len(line.split('===')) >= 2:
name = line.split('===')[0]
version_ = line.split('===')[1]
elif len(line.split('==')) >= 2:
name = line.split('==')[0]
version_ = line.split('==')[1]
else:
logger.error('Can\'t parse line \'%s\'', line)
continue
if pkgname:
if pkgname == name.lower():
return True
return False
|
.. versionadded:: 2018.3.0
Filter list of installed apps from ``freeze`` and return True or False if
``pkgname`` exists in the list of packages installed.
.. note::
If the version of pip available is older than 8.0.3, the packages
wheel, setuptools, and distribute will not be reported by this function
even if they are installed. Unlike :py:func:`pip.freeze
<salt.modules.pip.freeze>`, this function always reports the version of
pip which is installed.
CLI Example:
.. code-block:: bash
salt '*' pip.is_installed salt
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/pip.py#L1339-L1387
|
[
"def freeze(bin_env=None,\n user=None,\n cwd=None,\n use_vt=False,\n env_vars=None,\n **kwargs):\n '''\n Return a list of installed packages either globally or in the specified\n virtualenv\n\n bin_env\n Path to pip (or to a virtualenv). This can be used to specify the path\n to the pip to use when more than one Python release is installed (e.g.\n ``/usr/bin/pip-2.7`` or ``/usr/bin/pip-2.6``. If a directory path is\n specified, it is assumed to be a virtualenv.\n\n user\n The user under which to run pip\n\n cwd\n Directory from which to run pip\n\n .. note::\n If the version of pip available is older than 8.0.3, the list will not\n include the packages ``pip``, ``wheel``, ``setuptools``, or\n ``distribute`` even if they are installed.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' pip.freeze bin_env=/home/code/path/to/virtualenv\n '''\n cmd = _get_pip_bin(bin_env)\n cmd.append('freeze')\n\n # Include pip, setuptools, distribute, wheel\n min_version = '8.0.3'\n cur_version = version(bin_env)\n if salt.utils.versions.compare(ver1=cur_version, oper='<', ver2=min_version):\n logger.warning(\n 'The version of pip installed is %s, which is older than %s. '\n 'The packages pip, wheel, setuptools, and distribute will not be '\n 'included in the output of pip.freeze', cur_version, min_version\n )\n else:\n cmd.append('--all')\n\n cmd_kwargs = dict(runas=user, cwd=cwd, use_vt=use_vt, python_shell=False)\n if kwargs:\n cmd_kwargs.update(**kwargs)\n if bin_env and os.path.isdir(bin_env):\n cmd_kwargs['env'] = {'VIRTUAL_ENV': bin_env}\n if env_vars:\n cmd_kwargs.setdefault('env', {}).update(_format_env_vars(env_vars))\n result = __salt__['cmd.run_all'](cmd, **cmd_kwargs)\n\n if result['retcode']:\n raise CommandExecutionError(result['stderr'], info=result)\n\n return result['stdout'].splitlines()\n"
] |
# -*- coding: utf-8 -*-
r'''
Install Python packages with pip to either the system or a virtualenv
Windows Support
===============
.. versionadded:: 2014.7.4
Salt now uses a portable python. As a result the entire pip module is now
functional on the salt installation itself. You can pip install dependencies
for your custom modules. You can even upgrade salt itself using pip. For this
to work properly, you must specify the Current Working Directory (``cwd``) and
the Pip Binary (``bin_env``) salt should use. The variable ``pip_bin`` can be
either a virtualenv path or the path to the pip binary itself.
For example, the following command will list all software installed using pip
to your current salt environment:
.. code-block:: bat
salt <minion> pip.list cwd='C:\salt\bin\Scripts' bin_env='C:\salt\bin\Scripts\pip.exe'
Specifying the ``cwd`` and ``bin_env`` options ensures you're modifying the
salt environment. If these are omitted, it will default to the local
installation of python. If python is not installed locally it will fail saying
it couldn't find pip.
State File Support
------------------
This functionality works in states as well. If you need to pip install colorama
with a state, for example, the following will work:
.. code-block:: yaml
install_colorama:
pip.installed:
- name: colorama
- cwd: 'C:\salt\bin\scripts'
- bin_env: 'C:\salt\bin\scripts\pip.exe'
- upgrade: True
Upgrading Salt using Pip
------------------------
You can now update salt using pip to any version from the 2014.7 branch
forward. Previous version require recompiling some of the dependencies which is
painful in windows.
To do this you just use pip with git to update to the version you want and then
restart the service. Here is a sample state file that upgrades salt to the head
of the 2015.5 branch:
.. code-block:: yaml
install_salt:
pip.installed:
- cwd: 'C:\salt\bin\scripts'
- bin_env: 'C:\salt\bin\scripts\pip.exe'
- editable: git+https://github.com/saltstack/salt@2015.5#egg=salt
- upgrade: True
restart_service:
service.running:
- name: salt-minion
- enable: True
- watch:
- pip: install_salt
.. note::
If you're having problems, you might try doubling the back slashes. For
example, cwd: 'C:\\salt\\bin\\scripts'. Sometimes python thinks the single
back slash is an escape character.
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import logging
import os
try:
import pkg_resources
except ImportError:
pkg_resources = None
import re
import shutil
import sys
import tempfile
# Import Salt libs
import salt.utils.data
import salt.utils.files
import salt.utils.json
import salt.utils.locales
import salt.utils.platform
import salt.utils.stringutils
import salt.utils.url
import salt.utils.versions
from salt.ext import six
from salt.exceptions import CommandExecutionError, CommandNotFoundError
# This needs to be named logger so we don't shadow it in pip.install
logger = logging.getLogger(__name__) # pylint: disable=C0103
# Don't shadow built-in's.
__func_alias__ = {
'list_': 'list'
}
VALID_PROTOS = ['http', 'https', 'ftp', 'file']
rex_pip_chain_read = re.compile(r'-r\s(.*)\n?', re.MULTILINE)
def __virtual__():
'''
There is no way to verify that pip is installed without inspecting the
entire filesystem. If it's not installed in a conventional location, the
user is required to provide the location of pip each time it is used.
'''
if pkg_resources is None:
ret = False, 'Package dependency "pkg_resource" is missing'
else:
ret = 'pip'
return ret
def _clear_context(bin_env=None):
'''
Remove the cached pip version
'''
contextkey = 'pip.version'
if bin_env is not None:
contextkey = '{0}.{1}'.format(contextkey, bin_env)
__context__.pop(contextkey, None)
def _get_pip_bin(bin_env):
'''
Locate the pip binary, either from `bin_env` as a virtualenv, as the
executable itself, or from searching conventional filesystem locations
'''
if not bin_env:
logger.debug('pip: Using pip from currently-running Python')
return [os.path.normpath(sys.executable), '-m', 'pip']
python_bin = 'python.exe' if salt.utils.platform.is_windows() else 'python'
def _search_paths(*basedirs):
ret = []
for path in basedirs:
ret.extend([
os.path.join(path, python_bin),
os.path.join(path, 'bin', python_bin),
os.path.join(path, 'Scripts', python_bin)
])
return ret
# try to get python bin from virtualenv (i.e. bin_env)
if os.path.isdir(bin_env):
for bin_path in _search_paths(bin_env):
if os.path.isfile(bin_path):
if os.access(bin_path, os.X_OK):
logger.debug('pip: Found python binary: %s', bin_path)
return [os.path.normpath(bin_path), '-m', 'pip']
else:
logger.debug(
'pip: Found python binary by name but it is not '
'executable: %s', bin_path
)
raise CommandNotFoundError(
'Could not find a pip binary in virtualenv {0}'.format(bin_env)
)
# bin_env is the python or pip binary
elif os.access(bin_env, os.X_OK):
if os.path.isfile(bin_env):
# If the python binary was passed, return it
if 'python' in os.path.basename(bin_env):
return [os.path.normpath(bin_env), '-m', 'pip']
# We have been passed a pip binary, use the pip binary.
return [os.path.normpath(bin_env)]
raise CommandExecutionError(
'Could not find a pip binary within {0}'.format(bin_env)
)
else:
raise CommandNotFoundError(
'Access denied to {0}, could not find a pip binary'.format(bin_env)
)
def _get_cached_requirements(requirements, saltenv):
'''
Get the location of a cached requirements file; caching if necessary.
'''
req_file, senv = salt.utils.url.parse(requirements)
if senv:
saltenv = senv
if req_file not in __salt__['cp.list_master'](saltenv):
# Requirements file does not exist in the given saltenv.
return False
cached_requirements = __salt__['cp.is_cached'](
requirements, saltenv
)
if not cached_requirements:
# It's not cached, let's cache it.
cached_requirements = __salt__['cp.cache_file'](
requirements, saltenv
)
# Check if the master version has changed.
if __salt__['cp.hash_file'](requirements, saltenv) != \
__salt__['cp.hash_file'](cached_requirements, saltenv):
cached_requirements = __salt__['cp.cache_file'](
requirements, saltenv
)
return cached_requirements
def _get_env_activate(bin_env):
'''
Return the path to the activate binary
'''
if not bin_env:
raise CommandNotFoundError('Could not find a `activate` binary')
if os.path.isdir(bin_env):
if salt.utils.platform.is_windows():
activate_bin = os.path.join(bin_env, 'Scripts', 'activate.bat')
else:
activate_bin = os.path.join(bin_env, 'bin', 'activate')
if os.path.isfile(activate_bin):
return activate_bin
raise CommandNotFoundError('Could not find a `activate` binary')
def _find_req(link):
logger.info('_find_req -- link = %s', link)
with salt.utils.files.fopen(link) as fh_link:
child_links = rex_pip_chain_read.findall(
salt.utils.stringutils.to_unicode(fh_link.read())
)
base_path = os.path.dirname(link)
child_links = [os.path.join(base_path, d) for d in child_links]
return child_links
def _resolve_requirements_chain(requirements):
'''
Return an array of requirements file paths that can be used to complete
the no_chown==False && user != None conundrum
'''
chain = []
if isinstance(requirements, six.string_types):
requirements = [requirements]
for req_file in requirements:
chain.append(req_file)
chain.extend(_resolve_requirements_chain(_find_req(req_file)))
return chain
def _process_requirements(requirements, cmd, cwd, saltenv, user):
'''
Process the requirements argument
'''
cleanup_requirements = []
if requirements is not None:
if isinstance(requirements, six.string_types):
requirements = [r.strip() for r in requirements.split(',')]
elif not isinstance(requirements, list):
raise TypeError('requirements must be a string or list')
treq = None
for requirement in requirements:
logger.debug('TREQ IS: %s', treq)
if requirement.startswith('salt://'):
cached_requirements = _get_cached_requirements(
requirement, saltenv
)
if not cached_requirements:
ret = {'result': False,
'comment': 'pip requirements file \'{0}\' not found'
.format(requirement)}
return None, ret
requirement = cached_requirements
if user:
# Need to make a temporary copy since the user will, most
# likely, not have the right permissions to read the file
if not treq:
treq = tempfile.mkdtemp()
__salt__['file.chown'](treq, user, None)
# In Windows, just being owner of a file isn't enough. You also
# need permissions
if salt.utils.platform.is_windows():
__utils__['dacl.set_permissions'](
obj_name=treq,
principal=user,
permissions='read_execute')
current_directory = None
if not current_directory:
current_directory = os.path.abspath(os.curdir)
logger.info('_process_requirements from directory, '
'%s -- requirement: %s', cwd, requirement)
if cwd is None:
r = requirement
c = cwd
requirement_abspath = os.path.abspath(requirement)
cwd = os.path.dirname(requirement_abspath)
requirement = os.path.basename(requirement)
logger.debug('\n\tcwd: %s -> %s\n\trequirement: %s -> %s\n',
c, cwd, r, requirement
)
os.chdir(cwd)
reqs = _resolve_requirements_chain(requirement)
os.chdir(current_directory)
logger.info('request files: %s', reqs)
for req_file in reqs:
if not os.path.isabs(req_file):
req_file = os.path.join(cwd, req_file)
logger.debug('TREQ N CWD: %s -- %s -- for %s', treq, cwd, req_file)
target_path = os.path.join(treq, os.path.basename(req_file))
logger.debug('S: %s', req_file)
logger.debug('T: %s', target_path)
target_base = os.path.dirname(target_path)
if not os.path.exists(target_base):
os.makedirs(target_base, mode=0o755)
__salt__['file.chown'](target_base, user, None)
if not os.path.exists(target_path):
logger.debug(
'Copying %s to %s', req_file, target_path
)
__salt__['file.copy'](req_file, target_path)
logger.debug(
'Changing ownership of requirements file \'%s\' to '
'user \'%s\'', target_path, user
)
__salt__['file.chown'](target_path, user, None)
req_args = os.path.join(treq, requirement) if treq else requirement
cmd.extend(['--requirement', req_args])
cleanup_requirements.append(treq)
logger.debug('CLEANUP_REQUIREMENTS: %s', cleanup_requirements)
return cleanup_requirements, None
def _format_env_vars(env_vars):
ret = {}
if env_vars:
if isinstance(env_vars, dict):
for key, val in six.iteritems(env_vars):
if not isinstance(key, six.string_types):
key = str(key) # future lint: disable=blacklisted-function
if not isinstance(val, six.string_types):
val = str(val) # future lint: disable=blacklisted-function
ret[key] = val
else:
raise CommandExecutionError(
'env_vars {0} is not a dictionary'.format(env_vars))
return ret
def install(pkgs=None, # pylint: disable=R0912,R0913,R0914
requirements=None,
bin_env=None,
use_wheel=False,
no_use_wheel=False,
log=None,
proxy=None,
timeout=None,
editable=None,
find_links=None,
index_url=None,
extra_index_url=None,
no_index=False,
mirrors=None,
build=None,
target=None,
download=None,
download_cache=None,
source=None,
upgrade=False,
force_reinstall=False,
ignore_installed=False,
exists_action=None,
no_deps=False,
no_install=False,
no_download=False,
global_options=None,
install_options=None,
user=None,
cwd=None,
pre_releases=False,
cert=None,
allow_all_external=False,
allow_external=None,
allow_unverified=None,
process_dependency_links=False,
saltenv='base',
env_vars=None,
use_vt=False,
trusted_host=None,
no_cache_dir=False,
cache_dir=None,
no_binary=None,
extra_args=None,
**kwargs):
'''
Install packages with pip
Install packages individually or from a pip requirements file. Install
packages globally or to a virtualenv.
pkgs
Comma separated list of packages to install
requirements
Path to requirements
bin_env
Path to pip (or to a virtualenv). This can be used to specify the path
to the pip to use when more than one Python release is installed (e.g.
``/usr/bin/pip-2.7`` or ``/usr/bin/pip-2.6``. If a directory path is
specified, it is assumed to be a virtualenv.
.. note::
For Windows, if the pip module is being used to upgrade the pip
package, bin_env should be the path to the virtualenv or to the
python binary that should be used. The pip command is unable to
upgrade itself in Windows.
use_wheel
Prefer wheel archives (requires pip>=1.4)
no_use_wheel
Force to not use wheel archives (requires pip>=1.4,<10.0.0)
no_binary
Force to not use binary packages (requires pip >= 7.0.0)
Accepts either :all: to disable all binary packages, :none: to empty the set,
or one or more package names with commas between them
log
Log file where a complete (maximum verbosity) record will be kept
proxy
Specify a proxy in the form ``user:passwd@proxy.server:port``. Note
that the ``user:password@`` is optional and required only if you are
behind an authenticated proxy. If you provide
``user@proxy.server:port`` then you will be prompted for a password.
timeout
Set the socket timeout (default 15 seconds)
editable
install something editable (e.g.
``git+https://github.com/worldcompany/djangoembed.git#egg=djangoembed``)
find_links
URL to search for packages
index_url
Base URL of Python Package Index
extra_index_url
Extra URLs of package indexes to use in addition to ``index_url``
no_index
Ignore package index
mirrors
Specific mirror URL(s) to query (automatically adds --use-mirrors)
.. warning::
This option has been deprecated and removed in pip version 7.0.0.
Please use ``index_url`` and/or ``extra_index_url`` instead.
build
Unpack packages into ``build`` dir
target
Install packages into ``target`` dir
download
Download packages into ``download`` instead of installing them
download_cache | cache_dir
Cache downloaded packages in ``download_cache`` or ``cache_dir`` dir
source
Check out ``editable`` packages into ``source`` dir
upgrade
Upgrade all packages to the newest available version
force_reinstall
When upgrading, reinstall all packages even if they are already
up-to-date.
ignore_installed
Ignore the installed packages (reinstalling instead)
exists_action
Default action when a path already exists: (s)witch, (i)gnore, (w)ipe,
(b)ackup
no_deps
Ignore package dependencies
no_install
Download and unpack all packages, but don't actually install them
no_download
Don't download any packages, just install the ones already downloaded
(completes an install run with ``--no-install``)
install_options
Extra arguments to be supplied to the setup.py install command (e.g.
like ``--install-option='--install-scripts=/usr/local/bin'``). Use
multiple --install-option options to pass multiple options to setup.py
install. If you are using an option with a directory path, be sure to
use absolute path.
global_options
Extra global options to be supplied to the setup.py call before the
install command.
user
The user under which to run pip
cwd
Directory from which to run pip
pre_releases
Include pre-releases in the available versions
cert
Provide a path to an alternate CA bundle
allow_all_external
Allow the installation of all externally hosted files
allow_external
Allow the installation of externally hosted files (comma separated
list)
allow_unverified
Allow the installation of insecure and unverifiable files (comma
separated list)
process_dependency_links
Enable the processing of dependency links
env_vars
Set environment variables that some builds will depend on. For example,
a Python C-module may have a Makefile that needs INCLUDE_PATH set to
pick up a header file while compiling. This must be in the form of a
dictionary or a mapping.
Example:
.. code-block:: bash
salt '*' pip.install django_app env_vars="{'CUSTOM_PATH': '/opt/django_app'}"
trusted_host
Mark this host as trusted, even though it does not have valid or any
HTTPS.
use_vt
Use VT terminal emulation (see output while installing)
no_cache_dir
Disable the cache.
extra_args
pip keyword and positional arguments not yet implemented in salt
.. code-block:: yaml
salt '*' pip.install pandas extra_args="[{'--latest-pip-kwarg':'param'}, '--latest-pip-arg']"
.. warning::
If unsupported options are passed here that are not supported in a
minion's version of pip, a `No such option error` will be thrown.
Will be translated into the following pip command:
.. code-block:: bash
pip install pandas --latest-pip-kwarg param --latest-pip-arg
CLI Example:
.. code-block:: bash
salt '*' pip.install <package name>,<package2 name>
salt '*' pip.install requirements=/path/to/requirements.txt
salt '*' pip.install <package name> bin_env=/path/to/virtualenv
salt '*' pip.install <package name> bin_env=/path/to/pip_bin
Complicated CLI example::
salt '*' pip.install markdown,django \
editable=git+https://github.com/worldcompany/djangoembed.git#egg=djangoembed upgrade=True no_deps=True
'''
cmd = _get_pip_bin(bin_env)
cmd.append('install')
cleanup_requirements, error = _process_requirements(
requirements=requirements,
cmd=cmd,
cwd=cwd,
saltenv=saltenv,
user=user
)
if error:
return error
cur_version = version(bin_env)
if use_wheel:
min_version = '1.4'
max_version = '9.0.3'
too_low = salt.utils.versions.compare(ver1=cur_version, oper='<', ver2=min_version)
too_high = salt.utils.versions.compare(ver1=cur_version, oper='>', ver2=max_version)
if too_low or too_high:
logger.error(
'The --use-wheel option is only supported in pip between %s and '
'%s. The version of pip detected is %s. This option '
'will be ignored.', min_version, max_version, cur_version
)
else:
cmd.append('--use-wheel')
if no_use_wheel:
min_version = '1.4'
max_version = '9.0.3'
too_low = salt.utils.versions.compare(ver1=cur_version, oper='<', ver2=min_version)
too_high = salt.utils.versions.compare(ver1=cur_version, oper='>', ver2=max_version)
if too_low or too_high:
logger.error(
'The --no-use-wheel option is only supported in pip between %s and '
'%s. The version of pip detected is %s. This option '
'will be ignored.', min_version, max_version, cur_version
)
else:
cmd.append('--no-use-wheel')
if no_binary:
min_version = '7.0.0'
too_low = salt.utils.versions.compare(ver1=cur_version, oper='<', ver2=min_version)
if too_low:
logger.error(
'The --no-binary option is only supported in pip %s and '
'newer. The version of pip detected is %s. This option '
'will be ignored.', min_version, cur_version
)
else:
if isinstance(no_binary, list):
no_binary = ','.join(no_binary)
cmd.extend(['--no-binary', no_binary])
if log:
if os.path.isdir(log):
raise IOError(
'\'{0}\' is a directory. Use --log path_to_file'.format(log))
elif not os.access(log, os.W_OK):
raise IOError('\'{0}\' is not writeable'.format(log))
cmd.extend(['--log', log])
if proxy:
cmd.extend(['--proxy', proxy])
if timeout:
try:
if isinstance(timeout, float):
# Catch floating point input, exception will be caught in
# exception class below.
raise ValueError('Timeout cannot be a float')
int(timeout)
except ValueError:
raise ValueError(
'\'{0}\' is not a valid timeout, must be an integer'
.format(timeout)
)
cmd.extend(['--timeout', timeout])
if find_links:
if isinstance(find_links, six.string_types):
find_links = [l.strip() for l in find_links.split(',')]
for link in find_links:
if not (salt.utils.url.validate(link, VALID_PROTOS) or os.path.exists(link)):
raise CommandExecutionError(
'\'{0}\' is not a valid URL or path'.format(link)
)
cmd.extend(['--find-links', link])
if no_index and (index_url or extra_index_url):
raise CommandExecutionError(
'\'no_index\' and (\'index_url\' or \'extra_index_url\') are '
'mutually exclusive.'
)
if index_url:
if not salt.utils.url.validate(index_url, VALID_PROTOS):
raise CommandExecutionError(
'\'{0}\' is not a valid URL'.format(index_url)
)
cmd.extend(['--index-url', index_url])
if extra_index_url:
if not salt.utils.url.validate(extra_index_url, VALID_PROTOS):
raise CommandExecutionError(
'\'{0}\' is not a valid URL'.format(extra_index_url)
)
cmd.extend(['--extra-index-url', extra_index_url])
if no_index:
cmd.append('--no-index')
if mirrors:
# https://github.com/pypa/pip/pull/2641/files#diff-3ef137fb9ffdd400f117a565cd94c188L216
if salt.utils.versions.compare(ver1=cur_version, oper='>=', ver2='7.0.0'):
raise CommandExecutionError(
'pip >= 7.0.0 does not support mirror argument:'
' use index_url and/or extra_index_url instead'
)
if isinstance(mirrors, six.string_types):
mirrors = [m.strip() for m in mirrors.split(',')]
cmd.append('--use-mirrors')
for mirror in mirrors:
if not mirror.startswith('http://'):
raise CommandExecutionError(
'\'{0}\' is not a valid URL'.format(mirror)
)
cmd.extend(['--mirrors', mirror])
if build:
cmd.extend(['--build', build])
if target:
cmd.extend(['--target', target])
if download:
cmd.extend(['--download', download])
if download_cache or cache_dir:
cmd.extend(['--cache-dir' if salt.utils.versions.compare(
ver1=cur_version, oper='>=', ver2='6.0'
) else '--download-cache', download_cache or cache_dir])
if source:
cmd.extend(['--source', source])
if upgrade:
cmd.append('--upgrade')
if force_reinstall:
cmd.append('--force-reinstall')
if ignore_installed:
cmd.append('--ignore-installed')
if exists_action:
if exists_action.lower() not in ('s', 'i', 'w', 'b'):
raise CommandExecutionError(
'The exists_action pip option only supports the values '
's, i, w, and b. \'{0}\' is not valid.'.format(exists_action)
)
cmd.extend(['--exists-action', exists_action])
if no_deps:
cmd.append('--no-deps')
if no_install:
cmd.append('--no-install')
if no_download:
cmd.append('--no-download')
if no_cache_dir:
cmd.append('--no-cache-dir')
if pre_releases:
# Check the locally installed pip version
pip_version = cur_version
# From pip v1.4 the --pre flag is available
if salt.utils.versions.compare(ver1=pip_version, oper='>=', ver2='1.4'):
cmd.append('--pre')
if cert:
cmd.extend(['--cert', cert])
if global_options:
if isinstance(global_options, six.string_types):
global_options = [go.strip() for go in global_options.split(',')]
for opt in global_options:
cmd.extend(['--global-option', opt])
if install_options:
if isinstance(install_options, six.string_types):
install_options = [io.strip() for io in install_options.split(',')]
for opt in install_options:
cmd.extend(['--install-option', opt])
if pkgs:
if not isinstance(pkgs, list):
try:
pkgs = [p.strip() for p in pkgs.split(',')]
except AttributeError:
pkgs = [p.strip() for p in six.text_type(pkgs).split(',')]
pkgs = salt.utils.data.stringify(salt.utils.data.decode_list(pkgs))
# It's possible we replaced version-range commas with semicolons so
# they would survive the previous line (in the pip.installed state).
# Put the commas back in while making sure the names are contained in
# quotes, this allows for proper version spec passing salt>=0.17.0
cmd.extend([p.replace(';', ',') for p in pkgs])
elif not any([requirements, editable]):
# Starting with pip 10.0.0, if no packages are specified in the
# command, it returns a retcode 1. So instead of running the command,
# just return the output without running pip.
return {'retcode': 0, 'stdout': 'No packages to install.'}
if editable:
egg_match = re.compile(r'(?:#|#.*?&)egg=([^&]*)')
if isinstance(editable, six.string_types):
editable = [e.strip() for e in editable.split(',')]
for entry in editable:
# Is the editable local?
if not (entry == '.' or entry.startswith(('file://', '/'))):
match = egg_match.search(entry)
if not match or not match.group(1):
# Missing #egg=theEggName
raise CommandExecutionError(
'You must specify an egg for this editable'
)
cmd.extend(['--editable', entry])
if allow_all_external:
cmd.append('--allow-all-external')
if allow_external:
if isinstance(allow_external, six.string_types):
allow_external = [p.strip() for p in allow_external.split(',')]
for pkg in allow_external:
cmd.extend(['--allow-external', pkg])
if allow_unverified:
if isinstance(allow_unverified, six.string_types):
allow_unverified = \
[p.strip() for p in allow_unverified.split(',')]
for pkg in allow_unverified:
cmd.extend(['--allow-unverified', pkg])
if process_dependency_links:
cmd.append('--process-dependency-links')
if trusted_host:
cmd.extend(['--trusted-host', trusted_host])
if extra_args:
# These are arguments from the latest version of pip that
# have not yet been implemented in salt
for arg in extra_args:
# It is a keyword argument
if isinstance(arg, dict):
# There will only ever be one item in this dictionary
key, val = arg.popitem()
# Don't allow any recursion into keyword arg definitions
# Don't allow multiple definitions of a keyword
if isinstance(val, (dict, list)):
raise TypeError("Too many levels in: {}".format(key))
# This is a a normal one-to-one keyword argument
cmd.extend([key, val])
# It is a positional argument, append it to the list
else:
cmd.append(arg)
cmd_kwargs = dict(saltenv=saltenv, use_vt=use_vt, runas=user)
if kwargs:
cmd_kwargs.update(kwargs)
if env_vars:
cmd_kwargs.setdefault('env', {}).update(_format_env_vars(env_vars))
try:
if cwd:
cmd_kwargs['cwd'] = cwd
if bin_env and os.path.isdir(bin_env):
cmd_kwargs.setdefault('env', {})['VIRTUAL_ENV'] = bin_env
logger.debug(
'TRY BLOCK: end of pip.install -- cmd: %s, cmd_kwargs: %s',
cmd, cmd_kwargs
)
return __salt__['cmd.run_all'](cmd, python_shell=False, **cmd_kwargs)
finally:
_clear_context(bin_env)
for tempdir in [cr for cr in cleanup_requirements if cr is not None]:
if os.path.isdir(tempdir):
shutil.rmtree(tempdir)
def uninstall(pkgs=None,
requirements=None,
bin_env=None,
log=None,
proxy=None,
timeout=None,
user=None,
cwd=None,
saltenv='base',
use_vt=False):
'''
Uninstall packages individually or from a pip requirements file
pkgs
comma separated list of packages to install
requirements
Path to requirements file
bin_env
Path to pip (or to a virtualenv). This can be used to specify the path
to the pip to use when more than one Python release is installed (e.g.
``/usr/bin/pip-2.7`` or ``/usr/bin/pip-2.6``. If a directory path is
specified, it is assumed to be a virtualenv.
log
Log file where a complete (maximum verbosity) record will be kept
proxy
Specify a proxy in the format ``user:passwd@proxy.server:port``. Note
that the ``user:password@`` is optional and required only if you are
behind an authenticated proxy. If you provide
``user@proxy.server:port`` then you will be prompted for a password.
timeout
Set the socket timeout (default 15 seconds)
user
The user under which to run pip
cwd
Directory from which to run pip
use_vt
Use VT terminal emulation (see output while installing)
CLI Example:
.. code-block:: bash
salt '*' pip.uninstall <package name>,<package2 name>
salt '*' pip.uninstall requirements=/path/to/requirements.txt
salt '*' pip.uninstall <package name> bin_env=/path/to/virtualenv
salt '*' pip.uninstall <package name> bin_env=/path/to/pip_bin
'''
cmd = _get_pip_bin(bin_env)
cmd.extend(['uninstall', '-y'])
cleanup_requirements, error = _process_requirements(
requirements=requirements, cmd=cmd, saltenv=saltenv, user=user,
cwd=cwd
)
if error:
return error
if log:
try:
# TODO make this check if writeable
os.path.exists(log)
except IOError:
raise IOError('\'{0}\' is not writeable'.format(log))
cmd.extend(['--log', log])
if proxy:
cmd.extend(['--proxy', proxy])
if timeout:
try:
if isinstance(timeout, float):
# Catch floating point input, exception will be caught in
# exception class below.
raise ValueError('Timeout cannot be a float')
int(timeout)
except ValueError:
raise ValueError(
'\'{0}\' is not a valid timeout, must be an integer'
.format(timeout)
)
cmd.extend(['--timeout', timeout])
if pkgs:
if isinstance(pkgs, six.string_types):
pkgs = [p.strip() for p in pkgs.split(',')]
if requirements:
for requirement in requirements:
with salt.utils.files.fopen(requirement) as rq_:
for req in rq_:
req = salt.utils.stringutils.to_unicode(req)
try:
req_pkg, _ = req.split('==')
if req_pkg in pkgs:
pkgs.remove(req_pkg)
except ValueError:
pass
cmd.extend(pkgs)
cmd_kwargs = dict(python_shell=False, runas=user,
cwd=cwd, saltenv=saltenv, use_vt=use_vt)
if bin_env and os.path.isdir(bin_env):
cmd_kwargs['env'] = {'VIRTUAL_ENV': bin_env}
try:
return __salt__['cmd.run_all'](cmd, **cmd_kwargs)
finally:
_clear_context(bin_env)
for requirement in cleanup_requirements:
if requirement:
try:
os.remove(requirement)
except OSError:
pass
def freeze(bin_env=None,
user=None,
cwd=None,
use_vt=False,
env_vars=None,
**kwargs):
'''
Return a list of installed packages either globally or in the specified
virtualenv
bin_env
Path to pip (or to a virtualenv). This can be used to specify the path
to the pip to use when more than one Python release is installed (e.g.
``/usr/bin/pip-2.7`` or ``/usr/bin/pip-2.6``. If a directory path is
specified, it is assumed to be a virtualenv.
user
The user under which to run pip
cwd
Directory from which to run pip
.. note::
If the version of pip available is older than 8.0.3, the list will not
include the packages ``pip``, ``wheel``, ``setuptools``, or
``distribute`` even if they are installed.
CLI Example:
.. code-block:: bash
salt '*' pip.freeze bin_env=/home/code/path/to/virtualenv
'''
cmd = _get_pip_bin(bin_env)
cmd.append('freeze')
# Include pip, setuptools, distribute, wheel
min_version = '8.0.3'
cur_version = version(bin_env)
if salt.utils.versions.compare(ver1=cur_version, oper='<', ver2=min_version):
logger.warning(
'The version of pip installed is %s, which is older than %s. '
'The packages pip, wheel, setuptools, and distribute will not be '
'included in the output of pip.freeze', cur_version, min_version
)
else:
cmd.append('--all')
cmd_kwargs = dict(runas=user, cwd=cwd, use_vt=use_vt, python_shell=False)
if kwargs:
cmd_kwargs.update(**kwargs)
if bin_env and os.path.isdir(bin_env):
cmd_kwargs['env'] = {'VIRTUAL_ENV': bin_env}
if env_vars:
cmd_kwargs.setdefault('env', {}).update(_format_env_vars(env_vars))
result = __salt__['cmd.run_all'](cmd, **cmd_kwargs)
if result['retcode']:
raise CommandExecutionError(result['stderr'], info=result)
return result['stdout'].splitlines()
def list_(prefix=None,
bin_env=None,
user=None,
cwd=None,
env_vars=None,
**kwargs):
'''
Filter list of installed apps from ``freeze`` and check to see if
``prefix`` exists in the list of packages installed.
.. note::
If the version of pip available is older than 8.0.3, the packages
``wheel``, ``setuptools``, and ``distribute`` will not be reported by
this function even if they are installed. Unlike :py:func:`pip.freeze
<salt.modules.pip.freeze>`, this function always reports the version of
pip which is installed.
CLI Example:
.. code-block:: bash
salt '*' pip.list salt
'''
packages = {}
if prefix is None or 'pip'.startswith(prefix):
packages['pip'] = version(bin_env)
for line in freeze(bin_env=bin_env,
user=user,
cwd=cwd,
env_vars=env_vars,
**kwargs):
if line.startswith('-f') or line.startswith('#'):
# ignore -f line as it contains --find-links directory
# ignore comment lines
continue
elif line.startswith('-e hg+not trust'):
# ignore hg + not trust problem
continue
elif line.startswith('-e'):
line = line.split('-e ')[1]
if '#egg=' in line:
version_, name = line.split('#egg=')
else:
if len(line.split('===')) >= 2:
name = line.split('===')[0]
version_ = line.split('===')[1]
elif len(line.split('==')) >= 2:
name = line.split('==')[0]
version_ = line.split('==')[1]
elif len(line.split('===')) >= 2:
name = line.split('===')[0]
version_ = line.split('===')[1]
elif len(line.split('==')) >= 2:
name = line.split('==')[0]
version_ = line.split('==')[1]
else:
logger.error('Can\'t parse line \'%s\'', line)
continue
if prefix:
if name.lower().startswith(prefix.lower()):
packages[name] = version_
else:
packages[name] = version_
return packages
def version(bin_env=None):
'''
.. versionadded:: 0.17.0
Returns the version of pip. Use ``bin_env`` to specify the path to a
virtualenv and get the version of pip in that virtualenv.
If unable to detect the pip version, returns ``None``.
CLI Example:
.. code-block:: bash
salt '*' pip.version
'''
contextkey = 'pip.version'
if bin_env is not None:
contextkey = '{0}.{1}'.format(contextkey, bin_env)
if contextkey in __context__:
return __context__[contextkey]
cmd = _get_pip_bin(bin_env)[:]
cmd.append('--version')
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
if ret['retcode']:
raise CommandNotFoundError('Could not find a `pip` binary')
try:
pip_version = re.match(r'^pip (\S+)', ret['stdout']).group(1)
except AttributeError:
pip_version = None
__context__[contextkey] = pip_version
return pip_version
def list_upgrades(bin_env=None,
user=None,
cwd=None):
'''
Check whether or not an upgrade is available for all packages
CLI Example:
.. code-block:: bash
salt '*' pip.list_upgrades
'''
cmd = _get_pip_bin(bin_env)
cmd.extend(['list', '--outdated'])
pip_version = version(bin_env)
# Pip started supporting the ability to output json starting with 9.0.0
min_version = '9.0'
if salt.utils.versions.compare(ver1=pip_version,
oper='>=',
ver2=min_version):
cmd.append('--format=json')
cmd_kwargs = dict(cwd=cwd, runas=user)
if bin_env and os.path.isdir(bin_env):
cmd_kwargs['env'] = {'VIRTUAL_ENV': bin_env}
result = __salt__['cmd.run_all'](cmd, **cmd_kwargs)
if result['retcode']:
raise CommandExecutionError(result['stderr'], info=result)
packages = {}
# Pip started supporting the ability to output json starting with 9.0.0
# Older versions will have to parse stdout
if salt.utils.versions.compare(ver1=pip_version, oper='<', ver2='9.0.0'):
# Pip versions < 8.0.0 had a different output format
# Sample data:
# pip (Current: 7.1.2 Latest: 10.0.1 [wheel])
# psutil (Current: 5.2.2 Latest: 5.4.5 [wheel])
# pyasn1 (Current: 0.2.3 Latest: 0.4.2 [wheel])
# pycparser (Current: 2.17 Latest: 2.18 [sdist])
if salt.utils.versions.compare(ver1=pip_version, oper='<', ver2='8.0.0'):
logger.debug('pip module: Old output format')
pat = re.compile(r'(\S*)\s+\(.*Latest:\s+(.*)\)')
# New output format for version 8.0.0+
# Sample data:
# pip (8.0.0) - Latest: 10.0.1 [wheel]
# psutil (5.2.2) - Latest: 5.4.5 [wheel]
# pyasn1 (0.2.3) - Latest: 0.4.2 [wheel]
# pycparser (2.17) - Latest: 2.18 [sdist]
else:
logger.debug('pip module: New output format')
pat = re.compile(r'(\S*)\s+\(.*\)\s+-\s+Latest:\s+(.*)')
for line in result['stdout'].splitlines():
match = pat.search(line)
if match:
name, version_ = match.groups()
else:
logger.error('Can\'t parse line \'%s\'', line)
continue
packages[name] = version_
else:
logger.debug('pip module: JSON output format')
try:
pkgs = salt.utils.json.loads(result['stdout'], strict=False)
except ValueError:
raise CommandExecutionError('Invalid JSON', info=result)
for pkg in pkgs:
packages[pkg['name']] = '{0} [{1}]'.format(pkg['latest_version'],
pkg['latest_filetype'])
return packages
def upgrade_available(pkg,
bin_env=None,
user=None,
cwd=None):
'''
.. versionadded:: 2015.5.0
Check whether or not an upgrade is available for a given package
CLI Example:
.. code-block:: bash
salt '*' pip.upgrade_available <package name>
'''
return pkg in list_upgrades(bin_env=bin_env, user=user, cwd=cwd)
def upgrade(bin_env=None,
user=None,
cwd=None,
use_vt=False):
'''
.. versionadded:: 2015.5.0
Upgrades outdated pip packages.
.. note::
On Windows you can't update salt from pip using salt, so salt will be
skipped
Returns a dict containing the changes.
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
CLI Example:
.. code-block:: bash
salt '*' pip.upgrade
'''
ret = {'changes': {},
'result': True,
'comment': '',
}
cmd = _get_pip_bin(bin_env)
cmd.extend(['install', '-U'])
old = list_(bin_env=bin_env, user=user, cwd=cwd)
cmd_kwargs = dict(cwd=cwd, use_vt=use_vt)
if bin_env and os.path.isdir(bin_env):
cmd_kwargs['env'] = {'VIRTUAL_ENV': bin_env}
errors = False
for pkg in list_upgrades(bin_env=bin_env, user=user, cwd=cwd):
if pkg == 'salt':
if salt.utils.platform.is_windows():
continue
result = __salt__['cmd.run_all'](cmd + [pkg], **cmd_kwargs)
if result['retcode'] != 0:
errors = True
if 'stderr' in result:
ret['comment'] += result['stderr']
if errors:
ret['result'] = False
_clear_context(bin_env)
new = list_(bin_env=bin_env, user=user, cwd=cwd)
ret['changes'] = salt.utils.data.compare_dicts(old, new)
return ret
def list_all_versions(pkg,
bin_env=None,
include_alpha=False,
include_beta=False,
include_rc=False,
user=None,
cwd=None,
index_url=None,
extra_index_url=None):
'''
.. versionadded:: 2017.7.3
List all available versions of a pip package
pkg
The package to check
bin_env
Path to pip (or to a virtualenv). This can be used to specify the path
to the pip to use when more than one Python release is installed (e.g.
``/usr/bin/pip-2.7`` or ``/usr/bin/pip-2.6``. If a directory path is
specified, it is assumed to be a virtualenv.
include_alpha
Include alpha versions in the list
include_beta
Include beta versions in the list
include_rc
Include release candidates versions in the list
user
The user under which to run pip
cwd
Directory from which to run pip
index_url
Base URL of Python Package Index
.. versionadded:: 2019.2.0
extra_index_url
Additional URL of Python Package Index
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' pip.list_all_versions <package name>
'''
cmd = _get_pip_bin(bin_env)
cmd.extend(['install', '{0}==versions'.format(pkg)])
if index_url:
if not salt.utils.url.validate(index_url, VALID_PROTOS):
raise CommandExecutionError(
'\'{0}\' is not a valid URL'.format(index_url)
)
cmd.extend(['--index-url', index_url])
if extra_index_url:
if not salt.utils.url.validate(extra_index_url, VALID_PROTOS):
raise CommandExecutionError(
'\'{0}\' is not a valid URL'.format(extra_index_url)
)
cmd.extend(['--extra-index-url', extra_index_url])
cmd_kwargs = dict(cwd=cwd, runas=user, output_loglevel='quiet', redirect_stderr=True)
if bin_env and os.path.isdir(bin_env):
cmd_kwargs['env'] = {'VIRTUAL_ENV': bin_env}
result = __salt__['cmd.run_all'](cmd, **cmd_kwargs)
filtered = []
if not include_alpha:
filtered.append('a')
if not include_beta:
filtered.append('b')
if not include_rc:
filtered.append('rc')
if filtered:
excludes = re.compile(r'^((?!{0}).)*$'.format('|'.join(filtered)))
else:
excludes = re.compile(r'')
versions = []
for line in result['stdout'].splitlines():
match = re.search(r'\s*Could not find a version.* \(from versions: (.*)\)', line)
if match:
versions = [v for v in match.group(1).split(', ') if v and excludes.match(v)]
versions.sort(key=pkg_resources.parse_version)
break
if not versions:
return None
return versions
|
saltstack/salt
|
salt/modules/pip.py
|
upgrade_available
|
python
|
def upgrade_available(pkg,
bin_env=None,
user=None,
cwd=None):
'''
.. versionadded:: 2015.5.0
Check whether or not an upgrade is available for a given package
CLI Example:
.. code-block:: bash
salt '*' pip.upgrade_available <package name>
'''
return pkg in list_upgrades(bin_env=bin_env, user=user, cwd=cwd)
|
.. versionadded:: 2015.5.0
Check whether or not an upgrade is available for a given package
CLI Example:
.. code-block:: bash
salt '*' pip.upgrade_available <package name>
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/pip.py#L1390-L1405
|
[
"def list_upgrades(bin_env=None,\n user=None,\n cwd=None):\n '''\n Check whether or not an upgrade is available for all packages\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' pip.list_upgrades\n '''\n cmd = _get_pip_bin(bin_env)\n cmd.extend(['list', '--outdated'])\n\n pip_version = version(bin_env)\n # Pip started supporting the ability to output json starting with 9.0.0\n min_version = '9.0'\n if salt.utils.versions.compare(ver1=pip_version,\n oper='>=',\n ver2=min_version):\n cmd.append('--format=json')\n\n cmd_kwargs = dict(cwd=cwd, runas=user)\n if bin_env and os.path.isdir(bin_env):\n cmd_kwargs['env'] = {'VIRTUAL_ENV': bin_env}\n\n result = __salt__['cmd.run_all'](cmd, **cmd_kwargs)\n if result['retcode']:\n raise CommandExecutionError(result['stderr'], info=result)\n\n packages = {}\n # Pip started supporting the ability to output json starting with 9.0.0\n # Older versions will have to parse stdout\n if salt.utils.versions.compare(ver1=pip_version, oper='<', ver2='9.0.0'):\n # Pip versions < 8.0.0 had a different output format\n # Sample data:\n # pip (Current: 7.1.2 Latest: 10.0.1 [wheel])\n # psutil (Current: 5.2.2 Latest: 5.4.5 [wheel])\n # pyasn1 (Current: 0.2.3 Latest: 0.4.2 [wheel])\n # pycparser (Current: 2.17 Latest: 2.18 [sdist])\n if salt.utils.versions.compare(ver1=pip_version, oper='<', ver2='8.0.0'):\n logger.debug('pip module: Old output format')\n pat = re.compile(r'(\\S*)\\s+\\(.*Latest:\\s+(.*)\\)')\n\n # New output format for version 8.0.0+\n # Sample data:\n # pip (8.0.0) - Latest: 10.0.1 [wheel]\n # psutil (5.2.2) - Latest: 5.4.5 [wheel]\n # pyasn1 (0.2.3) - Latest: 0.4.2 [wheel]\n # pycparser (2.17) - Latest: 2.18 [sdist]\n else:\n logger.debug('pip module: New output format')\n pat = re.compile(r'(\\S*)\\s+\\(.*\\)\\s+-\\s+Latest:\\s+(.*)')\n\n for line in result['stdout'].splitlines():\n match = pat.search(line)\n if match:\n name, version_ = match.groups()\n else:\n logger.error('Can\\'t parse line \\'%s\\'', line)\n continue\n packages[name] = version_\n\n else:\n logger.debug('pip module: JSON output format')\n try:\n pkgs = salt.utils.json.loads(result['stdout'], strict=False)\n except ValueError:\n raise CommandExecutionError('Invalid JSON', info=result)\n\n for pkg in pkgs:\n packages[pkg['name']] = '{0} [{1}]'.format(pkg['latest_version'],\n pkg['latest_filetype'])\n\n return packages\n"
] |
# -*- coding: utf-8 -*-
r'''
Install Python packages with pip to either the system or a virtualenv
Windows Support
===============
.. versionadded:: 2014.7.4
Salt now uses a portable python. As a result the entire pip module is now
functional on the salt installation itself. You can pip install dependencies
for your custom modules. You can even upgrade salt itself using pip. For this
to work properly, you must specify the Current Working Directory (``cwd``) and
the Pip Binary (``bin_env``) salt should use. The variable ``pip_bin`` can be
either a virtualenv path or the path to the pip binary itself.
For example, the following command will list all software installed using pip
to your current salt environment:
.. code-block:: bat
salt <minion> pip.list cwd='C:\salt\bin\Scripts' bin_env='C:\salt\bin\Scripts\pip.exe'
Specifying the ``cwd`` and ``bin_env`` options ensures you're modifying the
salt environment. If these are omitted, it will default to the local
installation of python. If python is not installed locally it will fail saying
it couldn't find pip.
State File Support
------------------
This functionality works in states as well. If you need to pip install colorama
with a state, for example, the following will work:
.. code-block:: yaml
install_colorama:
pip.installed:
- name: colorama
- cwd: 'C:\salt\bin\scripts'
- bin_env: 'C:\salt\bin\scripts\pip.exe'
- upgrade: True
Upgrading Salt using Pip
------------------------
You can now update salt using pip to any version from the 2014.7 branch
forward. Previous version require recompiling some of the dependencies which is
painful in windows.
To do this you just use pip with git to update to the version you want and then
restart the service. Here is a sample state file that upgrades salt to the head
of the 2015.5 branch:
.. code-block:: yaml
install_salt:
pip.installed:
- cwd: 'C:\salt\bin\scripts'
- bin_env: 'C:\salt\bin\scripts\pip.exe'
- editable: git+https://github.com/saltstack/salt@2015.5#egg=salt
- upgrade: True
restart_service:
service.running:
- name: salt-minion
- enable: True
- watch:
- pip: install_salt
.. note::
If you're having problems, you might try doubling the back slashes. For
example, cwd: 'C:\\salt\\bin\\scripts'. Sometimes python thinks the single
back slash is an escape character.
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import logging
import os
try:
import pkg_resources
except ImportError:
pkg_resources = None
import re
import shutil
import sys
import tempfile
# Import Salt libs
import salt.utils.data
import salt.utils.files
import salt.utils.json
import salt.utils.locales
import salt.utils.platform
import salt.utils.stringutils
import salt.utils.url
import salt.utils.versions
from salt.ext import six
from salt.exceptions import CommandExecutionError, CommandNotFoundError
# This needs to be named logger so we don't shadow it in pip.install
logger = logging.getLogger(__name__) # pylint: disable=C0103
# Don't shadow built-in's.
__func_alias__ = {
'list_': 'list'
}
VALID_PROTOS = ['http', 'https', 'ftp', 'file']
rex_pip_chain_read = re.compile(r'-r\s(.*)\n?', re.MULTILINE)
def __virtual__():
'''
There is no way to verify that pip is installed without inspecting the
entire filesystem. If it's not installed in a conventional location, the
user is required to provide the location of pip each time it is used.
'''
if pkg_resources is None:
ret = False, 'Package dependency "pkg_resource" is missing'
else:
ret = 'pip'
return ret
def _clear_context(bin_env=None):
'''
Remove the cached pip version
'''
contextkey = 'pip.version'
if bin_env is not None:
contextkey = '{0}.{1}'.format(contextkey, bin_env)
__context__.pop(contextkey, None)
def _get_pip_bin(bin_env):
'''
Locate the pip binary, either from `bin_env` as a virtualenv, as the
executable itself, or from searching conventional filesystem locations
'''
if not bin_env:
logger.debug('pip: Using pip from currently-running Python')
return [os.path.normpath(sys.executable), '-m', 'pip']
python_bin = 'python.exe' if salt.utils.platform.is_windows() else 'python'
def _search_paths(*basedirs):
ret = []
for path in basedirs:
ret.extend([
os.path.join(path, python_bin),
os.path.join(path, 'bin', python_bin),
os.path.join(path, 'Scripts', python_bin)
])
return ret
# try to get python bin from virtualenv (i.e. bin_env)
if os.path.isdir(bin_env):
for bin_path in _search_paths(bin_env):
if os.path.isfile(bin_path):
if os.access(bin_path, os.X_OK):
logger.debug('pip: Found python binary: %s', bin_path)
return [os.path.normpath(bin_path), '-m', 'pip']
else:
logger.debug(
'pip: Found python binary by name but it is not '
'executable: %s', bin_path
)
raise CommandNotFoundError(
'Could not find a pip binary in virtualenv {0}'.format(bin_env)
)
# bin_env is the python or pip binary
elif os.access(bin_env, os.X_OK):
if os.path.isfile(bin_env):
# If the python binary was passed, return it
if 'python' in os.path.basename(bin_env):
return [os.path.normpath(bin_env), '-m', 'pip']
# We have been passed a pip binary, use the pip binary.
return [os.path.normpath(bin_env)]
raise CommandExecutionError(
'Could not find a pip binary within {0}'.format(bin_env)
)
else:
raise CommandNotFoundError(
'Access denied to {0}, could not find a pip binary'.format(bin_env)
)
def _get_cached_requirements(requirements, saltenv):
'''
Get the location of a cached requirements file; caching if necessary.
'''
req_file, senv = salt.utils.url.parse(requirements)
if senv:
saltenv = senv
if req_file not in __salt__['cp.list_master'](saltenv):
# Requirements file does not exist in the given saltenv.
return False
cached_requirements = __salt__['cp.is_cached'](
requirements, saltenv
)
if not cached_requirements:
# It's not cached, let's cache it.
cached_requirements = __salt__['cp.cache_file'](
requirements, saltenv
)
# Check if the master version has changed.
if __salt__['cp.hash_file'](requirements, saltenv) != \
__salt__['cp.hash_file'](cached_requirements, saltenv):
cached_requirements = __salt__['cp.cache_file'](
requirements, saltenv
)
return cached_requirements
def _get_env_activate(bin_env):
'''
Return the path to the activate binary
'''
if not bin_env:
raise CommandNotFoundError('Could not find a `activate` binary')
if os.path.isdir(bin_env):
if salt.utils.platform.is_windows():
activate_bin = os.path.join(bin_env, 'Scripts', 'activate.bat')
else:
activate_bin = os.path.join(bin_env, 'bin', 'activate')
if os.path.isfile(activate_bin):
return activate_bin
raise CommandNotFoundError('Could not find a `activate` binary')
def _find_req(link):
logger.info('_find_req -- link = %s', link)
with salt.utils.files.fopen(link) as fh_link:
child_links = rex_pip_chain_read.findall(
salt.utils.stringutils.to_unicode(fh_link.read())
)
base_path = os.path.dirname(link)
child_links = [os.path.join(base_path, d) for d in child_links]
return child_links
def _resolve_requirements_chain(requirements):
'''
Return an array of requirements file paths that can be used to complete
the no_chown==False && user != None conundrum
'''
chain = []
if isinstance(requirements, six.string_types):
requirements = [requirements]
for req_file in requirements:
chain.append(req_file)
chain.extend(_resolve_requirements_chain(_find_req(req_file)))
return chain
def _process_requirements(requirements, cmd, cwd, saltenv, user):
'''
Process the requirements argument
'''
cleanup_requirements = []
if requirements is not None:
if isinstance(requirements, six.string_types):
requirements = [r.strip() for r in requirements.split(',')]
elif not isinstance(requirements, list):
raise TypeError('requirements must be a string or list')
treq = None
for requirement in requirements:
logger.debug('TREQ IS: %s', treq)
if requirement.startswith('salt://'):
cached_requirements = _get_cached_requirements(
requirement, saltenv
)
if not cached_requirements:
ret = {'result': False,
'comment': 'pip requirements file \'{0}\' not found'
.format(requirement)}
return None, ret
requirement = cached_requirements
if user:
# Need to make a temporary copy since the user will, most
# likely, not have the right permissions to read the file
if not treq:
treq = tempfile.mkdtemp()
__salt__['file.chown'](treq, user, None)
# In Windows, just being owner of a file isn't enough. You also
# need permissions
if salt.utils.platform.is_windows():
__utils__['dacl.set_permissions'](
obj_name=treq,
principal=user,
permissions='read_execute')
current_directory = None
if not current_directory:
current_directory = os.path.abspath(os.curdir)
logger.info('_process_requirements from directory, '
'%s -- requirement: %s', cwd, requirement)
if cwd is None:
r = requirement
c = cwd
requirement_abspath = os.path.abspath(requirement)
cwd = os.path.dirname(requirement_abspath)
requirement = os.path.basename(requirement)
logger.debug('\n\tcwd: %s -> %s\n\trequirement: %s -> %s\n',
c, cwd, r, requirement
)
os.chdir(cwd)
reqs = _resolve_requirements_chain(requirement)
os.chdir(current_directory)
logger.info('request files: %s', reqs)
for req_file in reqs:
if not os.path.isabs(req_file):
req_file = os.path.join(cwd, req_file)
logger.debug('TREQ N CWD: %s -- %s -- for %s', treq, cwd, req_file)
target_path = os.path.join(treq, os.path.basename(req_file))
logger.debug('S: %s', req_file)
logger.debug('T: %s', target_path)
target_base = os.path.dirname(target_path)
if not os.path.exists(target_base):
os.makedirs(target_base, mode=0o755)
__salt__['file.chown'](target_base, user, None)
if not os.path.exists(target_path):
logger.debug(
'Copying %s to %s', req_file, target_path
)
__salt__['file.copy'](req_file, target_path)
logger.debug(
'Changing ownership of requirements file \'%s\' to '
'user \'%s\'', target_path, user
)
__salt__['file.chown'](target_path, user, None)
req_args = os.path.join(treq, requirement) if treq else requirement
cmd.extend(['--requirement', req_args])
cleanup_requirements.append(treq)
logger.debug('CLEANUP_REQUIREMENTS: %s', cleanup_requirements)
return cleanup_requirements, None
def _format_env_vars(env_vars):
ret = {}
if env_vars:
if isinstance(env_vars, dict):
for key, val in six.iteritems(env_vars):
if not isinstance(key, six.string_types):
key = str(key) # future lint: disable=blacklisted-function
if not isinstance(val, six.string_types):
val = str(val) # future lint: disable=blacklisted-function
ret[key] = val
else:
raise CommandExecutionError(
'env_vars {0} is not a dictionary'.format(env_vars))
return ret
def install(pkgs=None, # pylint: disable=R0912,R0913,R0914
requirements=None,
bin_env=None,
use_wheel=False,
no_use_wheel=False,
log=None,
proxy=None,
timeout=None,
editable=None,
find_links=None,
index_url=None,
extra_index_url=None,
no_index=False,
mirrors=None,
build=None,
target=None,
download=None,
download_cache=None,
source=None,
upgrade=False,
force_reinstall=False,
ignore_installed=False,
exists_action=None,
no_deps=False,
no_install=False,
no_download=False,
global_options=None,
install_options=None,
user=None,
cwd=None,
pre_releases=False,
cert=None,
allow_all_external=False,
allow_external=None,
allow_unverified=None,
process_dependency_links=False,
saltenv='base',
env_vars=None,
use_vt=False,
trusted_host=None,
no_cache_dir=False,
cache_dir=None,
no_binary=None,
extra_args=None,
**kwargs):
'''
Install packages with pip
Install packages individually or from a pip requirements file. Install
packages globally or to a virtualenv.
pkgs
Comma separated list of packages to install
requirements
Path to requirements
bin_env
Path to pip (or to a virtualenv). This can be used to specify the path
to the pip to use when more than one Python release is installed (e.g.
``/usr/bin/pip-2.7`` or ``/usr/bin/pip-2.6``. If a directory path is
specified, it is assumed to be a virtualenv.
.. note::
For Windows, if the pip module is being used to upgrade the pip
package, bin_env should be the path to the virtualenv or to the
python binary that should be used. The pip command is unable to
upgrade itself in Windows.
use_wheel
Prefer wheel archives (requires pip>=1.4)
no_use_wheel
Force to not use wheel archives (requires pip>=1.4,<10.0.0)
no_binary
Force to not use binary packages (requires pip >= 7.0.0)
Accepts either :all: to disable all binary packages, :none: to empty the set,
or one or more package names with commas between them
log
Log file where a complete (maximum verbosity) record will be kept
proxy
Specify a proxy in the form ``user:passwd@proxy.server:port``. Note
that the ``user:password@`` is optional and required only if you are
behind an authenticated proxy. If you provide
``user@proxy.server:port`` then you will be prompted for a password.
timeout
Set the socket timeout (default 15 seconds)
editable
install something editable (e.g.
``git+https://github.com/worldcompany/djangoembed.git#egg=djangoembed``)
find_links
URL to search for packages
index_url
Base URL of Python Package Index
extra_index_url
Extra URLs of package indexes to use in addition to ``index_url``
no_index
Ignore package index
mirrors
Specific mirror URL(s) to query (automatically adds --use-mirrors)
.. warning::
This option has been deprecated and removed in pip version 7.0.0.
Please use ``index_url`` and/or ``extra_index_url`` instead.
build
Unpack packages into ``build`` dir
target
Install packages into ``target`` dir
download
Download packages into ``download`` instead of installing them
download_cache | cache_dir
Cache downloaded packages in ``download_cache`` or ``cache_dir`` dir
source
Check out ``editable`` packages into ``source`` dir
upgrade
Upgrade all packages to the newest available version
force_reinstall
When upgrading, reinstall all packages even if they are already
up-to-date.
ignore_installed
Ignore the installed packages (reinstalling instead)
exists_action
Default action when a path already exists: (s)witch, (i)gnore, (w)ipe,
(b)ackup
no_deps
Ignore package dependencies
no_install
Download and unpack all packages, but don't actually install them
no_download
Don't download any packages, just install the ones already downloaded
(completes an install run with ``--no-install``)
install_options
Extra arguments to be supplied to the setup.py install command (e.g.
like ``--install-option='--install-scripts=/usr/local/bin'``). Use
multiple --install-option options to pass multiple options to setup.py
install. If you are using an option with a directory path, be sure to
use absolute path.
global_options
Extra global options to be supplied to the setup.py call before the
install command.
user
The user under which to run pip
cwd
Directory from which to run pip
pre_releases
Include pre-releases in the available versions
cert
Provide a path to an alternate CA bundle
allow_all_external
Allow the installation of all externally hosted files
allow_external
Allow the installation of externally hosted files (comma separated
list)
allow_unverified
Allow the installation of insecure and unverifiable files (comma
separated list)
process_dependency_links
Enable the processing of dependency links
env_vars
Set environment variables that some builds will depend on. For example,
a Python C-module may have a Makefile that needs INCLUDE_PATH set to
pick up a header file while compiling. This must be in the form of a
dictionary or a mapping.
Example:
.. code-block:: bash
salt '*' pip.install django_app env_vars="{'CUSTOM_PATH': '/opt/django_app'}"
trusted_host
Mark this host as trusted, even though it does not have valid or any
HTTPS.
use_vt
Use VT terminal emulation (see output while installing)
no_cache_dir
Disable the cache.
extra_args
pip keyword and positional arguments not yet implemented in salt
.. code-block:: yaml
salt '*' pip.install pandas extra_args="[{'--latest-pip-kwarg':'param'}, '--latest-pip-arg']"
.. warning::
If unsupported options are passed here that are not supported in a
minion's version of pip, a `No such option error` will be thrown.
Will be translated into the following pip command:
.. code-block:: bash
pip install pandas --latest-pip-kwarg param --latest-pip-arg
CLI Example:
.. code-block:: bash
salt '*' pip.install <package name>,<package2 name>
salt '*' pip.install requirements=/path/to/requirements.txt
salt '*' pip.install <package name> bin_env=/path/to/virtualenv
salt '*' pip.install <package name> bin_env=/path/to/pip_bin
Complicated CLI example::
salt '*' pip.install markdown,django \
editable=git+https://github.com/worldcompany/djangoembed.git#egg=djangoembed upgrade=True no_deps=True
'''
cmd = _get_pip_bin(bin_env)
cmd.append('install')
cleanup_requirements, error = _process_requirements(
requirements=requirements,
cmd=cmd,
cwd=cwd,
saltenv=saltenv,
user=user
)
if error:
return error
cur_version = version(bin_env)
if use_wheel:
min_version = '1.4'
max_version = '9.0.3'
too_low = salt.utils.versions.compare(ver1=cur_version, oper='<', ver2=min_version)
too_high = salt.utils.versions.compare(ver1=cur_version, oper='>', ver2=max_version)
if too_low or too_high:
logger.error(
'The --use-wheel option is only supported in pip between %s and '
'%s. The version of pip detected is %s. This option '
'will be ignored.', min_version, max_version, cur_version
)
else:
cmd.append('--use-wheel')
if no_use_wheel:
min_version = '1.4'
max_version = '9.0.3'
too_low = salt.utils.versions.compare(ver1=cur_version, oper='<', ver2=min_version)
too_high = salt.utils.versions.compare(ver1=cur_version, oper='>', ver2=max_version)
if too_low or too_high:
logger.error(
'The --no-use-wheel option is only supported in pip between %s and '
'%s. The version of pip detected is %s. This option '
'will be ignored.', min_version, max_version, cur_version
)
else:
cmd.append('--no-use-wheel')
if no_binary:
min_version = '7.0.0'
too_low = salt.utils.versions.compare(ver1=cur_version, oper='<', ver2=min_version)
if too_low:
logger.error(
'The --no-binary option is only supported in pip %s and '
'newer. The version of pip detected is %s. This option '
'will be ignored.', min_version, cur_version
)
else:
if isinstance(no_binary, list):
no_binary = ','.join(no_binary)
cmd.extend(['--no-binary', no_binary])
if log:
if os.path.isdir(log):
raise IOError(
'\'{0}\' is a directory. Use --log path_to_file'.format(log))
elif not os.access(log, os.W_OK):
raise IOError('\'{0}\' is not writeable'.format(log))
cmd.extend(['--log', log])
if proxy:
cmd.extend(['--proxy', proxy])
if timeout:
try:
if isinstance(timeout, float):
# Catch floating point input, exception will be caught in
# exception class below.
raise ValueError('Timeout cannot be a float')
int(timeout)
except ValueError:
raise ValueError(
'\'{0}\' is not a valid timeout, must be an integer'
.format(timeout)
)
cmd.extend(['--timeout', timeout])
if find_links:
if isinstance(find_links, six.string_types):
find_links = [l.strip() for l in find_links.split(',')]
for link in find_links:
if not (salt.utils.url.validate(link, VALID_PROTOS) or os.path.exists(link)):
raise CommandExecutionError(
'\'{0}\' is not a valid URL or path'.format(link)
)
cmd.extend(['--find-links', link])
if no_index and (index_url or extra_index_url):
raise CommandExecutionError(
'\'no_index\' and (\'index_url\' or \'extra_index_url\') are '
'mutually exclusive.'
)
if index_url:
if not salt.utils.url.validate(index_url, VALID_PROTOS):
raise CommandExecutionError(
'\'{0}\' is not a valid URL'.format(index_url)
)
cmd.extend(['--index-url', index_url])
if extra_index_url:
if not salt.utils.url.validate(extra_index_url, VALID_PROTOS):
raise CommandExecutionError(
'\'{0}\' is not a valid URL'.format(extra_index_url)
)
cmd.extend(['--extra-index-url', extra_index_url])
if no_index:
cmd.append('--no-index')
if mirrors:
# https://github.com/pypa/pip/pull/2641/files#diff-3ef137fb9ffdd400f117a565cd94c188L216
if salt.utils.versions.compare(ver1=cur_version, oper='>=', ver2='7.0.0'):
raise CommandExecutionError(
'pip >= 7.0.0 does not support mirror argument:'
' use index_url and/or extra_index_url instead'
)
if isinstance(mirrors, six.string_types):
mirrors = [m.strip() for m in mirrors.split(',')]
cmd.append('--use-mirrors')
for mirror in mirrors:
if not mirror.startswith('http://'):
raise CommandExecutionError(
'\'{0}\' is not a valid URL'.format(mirror)
)
cmd.extend(['--mirrors', mirror])
if build:
cmd.extend(['--build', build])
if target:
cmd.extend(['--target', target])
if download:
cmd.extend(['--download', download])
if download_cache or cache_dir:
cmd.extend(['--cache-dir' if salt.utils.versions.compare(
ver1=cur_version, oper='>=', ver2='6.0'
) else '--download-cache', download_cache or cache_dir])
if source:
cmd.extend(['--source', source])
if upgrade:
cmd.append('--upgrade')
if force_reinstall:
cmd.append('--force-reinstall')
if ignore_installed:
cmd.append('--ignore-installed')
if exists_action:
if exists_action.lower() not in ('s', 'i', 'w', 'b'):
raise CommandExecutionError(
'The exists_action pip option only supports the values '
's, i, w, and b. \'{0}\' is not valid.'.format(exists_action)
)
cmd.extend(['--exists-action', exists_action])
if no_deps:
cmd.append('--no-deps')
if no_install:
cmd.append('--no-install')
if no_download:
cmd.append('--no-download')
if no_cache_dir:
cmd.append('--no-cache-dir')
if pre_releases:
# Check the locally installed pip version
pip_version = cur_version
# From pip v1.4 the --pre flag is available
if salt.utils.versions.compare(ver1=pip_version, oper='>=', ver2='1.4'):
cmd.append('--pre')
if cert:
cmd.extend(['--cert', cert])
if global_options:
if isinstance(global_options, six.string_types):
global_options = [go.strip() for go in global_options.split(',')]
for opt in global_options:
cmd.extend(['--global-option', opt])
if install_options:
if isinstance(install_options, six.string_types):
install_options = [io.strip() for io in install_options.split(',')]
for opt in install_options:
cmd.extend(['--install-option', opt])
if pkgs:
if not isinstance(pkgs, list):
try:
pkgs = [p.strip() for p in pkgs.split(',')]
except AttributeError:
pkgs = [p.strip() for p in six.text_type(pkgs).split(',')]
pkgs = salt.utils.data.stringify(salt.utils.data.decode_list(pkgs))
# It's possible we replaced version-range commas with semicolons so
# they would survive the previous line (in the pip.installed state).
# Put the commas back in while making sure the names are contained in
# quotes, this allows for proper version spec passing salt>=0.17.0
cmd.extend([p.replace(';', ',') for p in pkgs])
elif not any([requirements, editable]):
# Starting with pip 10.0.0, if no packages are specified in the
# command, it returns a retcode 1. So instead of running the command,
# just return the output without running pip.
return {'retcode': 0, 'stdout': 'No packages to install.'}
if editable:
egg_match = re.compile(r'(?:#|#.*?&)egg=([^&]*)')
if isinstance(editable, six.string_types):
editable = [e.strip() for e in editable.split(',')]
for entry in editable:
# Is the editable local?
if not (entry == '.' or entry.startswith(('file://', '/'))):
match = egg_match.search(entry)
if not match or not match.group(1):
# Missing #egg=theEggName
raise CommandExecutionError(
'You must specify an egg for this editable'
)
cmd.extend(['--editable', entry])
if allow_all_external:
cmd.append('--allow-all-external')
if allow_external:
if isinstance(allow_external, six.string_types):
allow_external = [p.strip() for p in allow_external.split(',')]
for pkg in allow_external:
cmd.extend(['--allow-external', pkg])
if allow_unverified:
if isinstance(allow_unverified, six.string_types):
allow_unverified = \
[p.strip() for p in allow_unverified.split(',')]
for pkg in allow_unverified:
cmd.extend(['--allow-unverified', pkg])
if process_dependency_links:
cmd.append('--process-dependency-links')
if trusted_host:
cmd.extend(['--trusted-host', trusted_host])
if extra_args:
# These are arguments from the latest version of pip that
# have not yet been implemented in salt
for arg in extra_args:
# It is a keyword argument
if isinstance(arg, dict):
# There will only ever be one item in this dictionary
key, val = arg.popitem()
# Don't allow any recursion into keyword arg definitions
# Don't allow multiple definitions of a keyword
if isinstance(val, (dict, list)):
raise TypeError("Too many levels in: {}".format(key))
# This is a a normal one-to-one keyword argument
cmd.extend([key, val])
# It is a positional argument, append it to the list
else:
cmd.append(arg)
cmd_kwargs = dict(saltenv=saltenv, use_vt=use_vt, runas=user)
if kwargs:
cmd_kwargs.update(kwargs)
if env_vars:
cmd_kwargs.setdefault('env', {}).update(_format_env_vars(env_vars))
try:
if cwd:
cmd_kwargs['cwd'] = cwd
if bin_env and os.path.isdir(bin_env):
cmd_kwargs.setdefault('env', {})['VIRTUAL_ENV'] = bin_env
logger.debug(
'TRY BLOCK: end of pip.install -- cmd: %s, cmd_kwargs: %s',
cmd, cmd_kwargs
)
return __salt__['cmd.run_all'](cmd, python_shell=False, **cmd_kwargs)
finally:
_clear_context(bin_env)
for tempdir in [cr for cr in cleanup_requirements if cr is not None]:
if os.path.isdir(tempdir):
shutil.rmtree(tempdir)
def uninstall(pkgs=None,
requirements=None,
bin_env=None,
log=None,
proxy=None,
timeout=None,
user=None,
cwd=None,
saltenv='base',
use_vt=False):
'''
Uninstall packages individually or from a pip requirements file
pkgs
comma separated list of packages to install
requirements
Path to requirements file
bin_env
Path to pip (or to a virtualenv). This can be used to specify the path
to the pip to use when more than one Python release is installed (e.g.
``/usr/bin/pip-2.7`` or ``/usr/bin/pip-2.6``. If a directory path is
specified, it is assumed to be a virtualenv.
log
Log file where a complete (maximum verbosity) record will be kept
proxy
Specify a proxy in the format ``user:passwd@proxy.server:port``. Note
that the ``user:password@`` is optional and required only if you are
behind an authenticated proxy. If you provide
``user@proxy.server:port`` then you will be prompted for a password.
timeout
Set the socket timeout (default 15 seconds)
user
The user under which to run pip
cwd
Directory from which to run pip
use_vt
Use VT terminal emulation (see output while installing)
CLI Example:
.. code-block:: bash
salt '*' pip.uninstall <package name>,<package2 name>
salt '*' pip.uninstall requirements=/path/to/requirements.txt
salt '*' pip.uninstall <package name> bin_env=/path/to/virtualenv
salt '*' pip.uninstall <package name> bin_env=/path/to/pip_bin
'''
cmd = _get_pip_bin(bin_env)
cmd.extend(['uninstall', '-y'])
cleanup_requirements, error = _process_requirements(
requirements=requirements, cmd=cmd, saltenv=saltenv, user=user,
cwd=cwd
)
if error:
return error
if log:
try:
# TODO make this check if writeable
os.path.exists(log)
except IOError:
raise IOError('\'{0}\' is not writeable'.format(log))
cmd.extend(['--log', log])
if proxy:
cmd.extend(['--proxy', proxy])
if timeout:
try:
if isinstance(timeout, float):
# Catch floating point input, exception will be caught in
# exception class below.
raise ValueError('Timeout cannot be a float')
int(timeout)
except ValueError:
raise ValueError(
'\'{0}\' is not a valid timeout, must be an integer'
.format(timeout)
)
cmd.extend(['--timeout', timeout])
if pkgs:
if isinstance(pkgs, six.string_types):
pkgs = [p.strip() for p in pkgs.split(',')]
if requirements:
for requirement in requirements:
with salt.utils.files.fopen(requirement) as rq_:
for req in rq_:
req = salt.utils.stringutils.to_unicode(req)
try:
req_pkg, _ = req.split('==')
if req_pkg in pkgs:
pkgs.remove(req_pkg)
except ValueError:
pass
cmd.extend(pkgs)
cmd_kwargs = dict(python_shell=False, runas=user,
cwd=cwd, saltenv=saltenv, use_vt=use_vt)
if bin_env and os.path.isdir(bin_env):
cmd_kwargs['env'] = {'VIRTUAL_ENV': bin_env}
try:
return __salt__['cmd.run_all'](cmd, **cmd_kwargs)
finally:
_clear_context(bin_env)
for requirement in cleanup_requirements:
if requirement:
try:
os.remove(requirement)
except OSError:
pass
def freeze(bin_env=None,
user=None,
cwd=None,
use_vt=False,
env_vars=None,
**kwargs):
'''
Return a list of installed packages either globally or in the specified
virtualenv
bin_env
Path to pip (or to a virtualenv). This can be used to specify the path
to the pip to use when more than one Python release is installed (e.g.
``/usr/bin/pip-2.7`` or ``/usr/bin/pip-2.6``. If a directory path is
specified, it is assumed to be a virtualenv.
user
The user under which to run pip
cwd
Directory from which to run pip
.. note::
If the version of pip available is older than 8.0.3, the list will not
include the packages ``pip``, ``wheel``, ``setuptools``, or
``distribute`` even if they are installed.
CLI Example:
.. code-block:: bash
salt '*' pip.freeze bin_env=/home/code/path/to/virtualenv
'''
cmd = _get_pip_bin(bin_env)
cmd.append('freeze')
# Include pip, setuptools, distribute, wheel
min_version = '8.0.3'
cur_version = version(bin_env)
if salt.utils.versions.compare(ver1=cur_version, oper='<', ver2=min_version):
logger.warning(
'The version of pip installed is %s, which is older than %s. '
'The packages pip, wheel, setuptools, and distribute will not be '
'included in the output of pip.freeze', cur_version, min_version
)
else:
cmd.append('--all')
cmd_kwargs = dict(runas=user, cwd=cwd, use_vt=use_vt, python_shell=False)
if kwargs:
cmd_kwargs.update(**kwargs)
if bin_env and os.path.isdir(bin_env):
cmd_kwargs['env'] = {'VIRTUAL_ENV': bin_env}
if env_vars:
cmd_kwargs.setdefault('env', {}).update(_format_env_vars(env_vars))
result = __salt__['cmd.run_all'](cmd, **cmd_kwargs)
if result['retcode']:
raise CommandExecutionError(result['stderr'], info=result)
return result['stdout'].splitlines()
def list_(prefix=None,
bin_env=None,
user=None,
cwd=None,
env_vars=None,
**kwargs):
'''
Filter list of installed apps from ``freeze`` and check to see if
``prefix`` exists in the list of packages installed.
.. note::
If the version of pip available is older than 8.0.3, the packages
``wheel``, ``setuptools``, and ``distribute`` will not be reported by
this function even if they are installed. Unlike :py:func:`pip.freeze
<salt.modules.pip.freeze>`, this function always reports the version of
pip which is installed.
CLI Example:
.. code-block:: bash
salt '*' pip.list salt
'''
packages = {}
if prefix is None or 'pip'.startswith(prefix):
packages['pip'] = version(bin_env)
for line in freeze(bin_env=bin_env,
user=user,
cwd=cwd,
env_vars=env_vars,
**kwargs):
if line.startswith('-f') or line.startswith('#'):
# ignore -f line as it contains --find-links directory
# ignore comment lines
continue
elif line.startswith('-e hg+not trust'):
# ignore hg + not trust problem
continue
elif line.startswith('-e'):
line = line.split('-e ')[1]
if '#egg=' in line:
version_, name = line.split('#egg=')
else:
if len(line.split('===')) >= 2:
name = line.split('===')[0]
version_ = line.split('===')[1]
elif len(line.split('==')) >= 2:
name = line.split('==')[0]
version_ = line.split('==')[1]
elif len(line.split('===')) >= 2:
name = line.split('===')[0]
version_ = line.split('===')[1]
elif len(line.split('==')) >= 2:
name = line.split('==')[0]
version_ = line.split('==')[1]
else:
logger.error('Can\'t parse line \'%s\'', line)
continue
if prefix:
if name.lower().startswith(prefix.lower()):
packages[name] = version_
else:
packages[name] = version_
return packages
def version(bin_env=None):
'''
.. versionadded:: 0.17.0
Returns the version of pip. Use ``bin_env`` to specify the path to a
virtualenv and get the version of pip in that virtualenv.
If unable to detect the pip version, returns ``None``.
CLI Example:
.. code-block:: bash
salt '*' pip.version
'''
contextkey = 'pip.version'
if bin_env is not None:
contextkey = '{0}.{1}'.format(contextkey, bin_env)
if contextkey in __context__:
return __context__[contextkey]
cmd = _get_pip_bin(bin_env)[:]
cmd.append('--version')
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
if ret['retcode']:
raise CommandNotFoundError('Could not find a `pip` binary')
try:
pip_version = re.match(r'^pip (\S+)', ret['stdout']).group(1)
except AttributeError:
pip_version = None
__context__[contextkey] = pip_version
return pip_version
def list_upgrades(bin_env=None,
user=None,
cwd=None):
'''
Check whether or not an upgrade is available for all packages
CLI Example:
.. code-block:: bash
salt '*' pip.list_upgrades
'''
cmd = _get_pip_bin(bin_env)
cmd.extend(['list', '--outdated'])
pip_version = version(bin_env)
# Pip started supporting the ability to output json starting with 9.0.0
min_version = '9.0'
if salt.utils.versions.compare(ver1=pip_version,
oper='>=',
ver2=min_version):
cmd.append('--format=json')
cmd_kwargs = dict(cwd=cwd, runas=user)
if bin_env and os.path.isdir(bin_env):
cmd_kwargs['env'] = {'VIRTUAL_ENV': bin_env}
result = __salt__['cmd.run_all'](cmd, **cmd_kwargs)
if result['retcode']:
raise CommandExecutionError(result['stderr'], info=result)
packages = {}
# Pip started supporting the ability to output json starting with 9.0.0
# Older versions will have to parse stdout
if salt.utils.versions.compare(ver1=pip_version, oper='<', ver2='9.0.0'):
# Pip versions < 8.0.0 had a different output format
# Sample data:
# pip (Current: 7.1.2 Latest: 10.0.1 [wheel])
# psutil (Current: 5.2.2 Latest: 5.4.5 [wheel])
# pyasn1 (Current: 0.2.3 Latest: 0.4.2 [wheel])
# pycparser (Current: 2.17 Latest: 2.18 [sdist])
if salt.utils.versions.compare(ver1=pip_version, oper='<', ver2='8.0.0'):
logger.debug('pip module: Old output format')
pat = re.compile(r'(\S*)\s+\(.*Latest:\s+(.*)\)')
# New output format for version 8.0.0+
# Sample data:
# pip (8.0.0) - Latest: 10.0.1 [wheel]
# psutil (5.2.2) - Latest: 5.4.5 [wheel]
# pyasn1 (0.2.3) - Latest: 0.4.2 [wheel]
# pycparser (2.17) - Latest: 2.18 [sdist]
else:
logger.debug('pip module: New output format')
pat = re.compile(r'(\S*)\s+\(.*\)\s+-\s+Latest:\s+(.*)')
for line in result['stdout'].splitlines():
match = pat.search(line)
if match:
name, version_ = match.groups()
else:
logger.error('Can\'t parse line \'%s\'', line)
continue
packages[name] = version_
else:
logger.debug('pip module: JSON output format')
try:
pkgs = salt.utils.json.loads(result['stdout'], strict=False)
except ValueError:
raise CommandExecutionError('Invalid JSON', info=result)
for pkg in pkgs:
packages[pkg['name']] = '{0} [{1}]'.format(pkg['latest_version'],
pkg['latest_filetype'])
return packages
def is_installed(pkgname=None,
bin_env=None,
user=None,
cwd=None):
'''
.. versionadded:: 2018.3.0
Filter list of installed apps from ``freeze`` and return True or False if
``pkgname`` exists in the list of packages installed.
.. note::
If the version of pip available is older than 8.0.3, the packages
wheel, setuptools, and distribute will not be reported by this function
even if they are installed. Unlike :py:func:`pip.freeze
<salt.modules.pip.freeze>`, this function always reports the version of
pip which is installed.
CLI Example:
.. code-block:: bash
salt '*' pip.is_installed salt
'''
for line in freeze(bin_env=bin_env, user=user, cwd=cwd):
if line.startswith('-f') or line.startswith('#'):
# ignore -f line as it contains --find-links directory
# ignore comment lines
continue
elif line.startswith('-e hg+not trust'):
# ignore hg + not trust problem
continue
elif line.startswith('-e'):
line = line.split('-e ')[1]
version_, name = line.split('#egg=')
elif len(line.split('===')) >= 2:
name = line.split('===')[0]
version_ = line.split('===')[1]
elif len(line.split('==')) >= 2:
name = line.split('==')[0]
version_ = line.split('==')[1]
else:
logger.error('Can\'t parse line \'%s\'', line)
continue
if pkgname:
if pkgname == name.lower():
return True
return False
def upgrade(bin_env=None,
user=None,
cwd=None,
use_vt=False):
'''
.. versionadded:: 2015.5.0
Upgrades outdated pip packages.
.. note::
On Windows you can't update salt from pip using salt, so salt will be
skipped
Returns a dict containing the changes.
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
CLI Example:
.. code-block:: bash
salt '*' pip.upgrade
'''
ret = {'changes': {},
'result': True,
'comment': '',
}
cmd = _get_pip_bin(bin_env)
cmd.extend(['install', '-U'])
old = list_(bin_env=bin_env, user=user, cwd=cwd)
cmd_kwargs = dict(cwd=cwd, use_vt=use_vt)
if bin_env and os.path.isdir(bin_env):
cmd_kwargs['env'] = {'VIRTUAL_ENV': bin_env}
errors = False
for pkg in list_upgrades(bin_env=bin_env, user=user, cwd=cwd):
if pkg == 'salt':
if salt.utils.platform.is_windows():
continue
result = __salt__['cmd.run_all'](cmd + [pkg], **cmd_kwargs)
if result['retcode'] != 0:
errors = True
if 'stderr' in result:
ret['comment'] += result['stderr']
if errors:
ret['result'] = False
_clear_context(bin_env)
new = list_(bin_env=bin_env, user=user, cwd=cwd)
ret['changes'] = salt.utils.data.compare_dicts(old, new)
return ret
def list_all_versions(pkg,
bin_env=None,
include_alpha=False,
include_beta=False,
include_rc=False,
user=None,
cwd=None,
index_url=None,
extra_index_url=None):
'''
.. versionadded:: 2017.7.3
List all available versions of a pip package
pkg
The package to check
bin_env
Path to pip (or to a virtualenv). This can be used to specify the path
to the pip to use when more than one Python release is installed (e.g.
``/usr/bin/pip-2.7`` or ``/usr/bin/pip-2.6``. If a directory path is
specified, it is assumed to be a virtualenv.
include_alpha
Include alpha versions in the list
include_beta
Include beta versions in the list
include_rc
Include release candidates versions in the list
user
The user under which to run pip
cwd
Directory from which to run pip
index_url
Base URL of Python Package Index
.. versionadded:: 2019.2.0
extra_index_url
Additional URL of Python Package Index
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' pip.list_all_versions <package name>
'''
cmd = _get_pip_bin(bin_env)
cmd.extend(['install', '{0}==versions'.format(pkg)])
if index_url:
if not salt.utils.url.validate(index_url, VALID_PROTOS):
raise CommandExecutionError(
'\'{0}\' is not a valid URL'.format(index_url)
)
cmd.extend(['--index-url', index_url])
if extra_index_url:
if not salt.utils.url.validate(extra_index_url, VALID_PROTOS):
raise CommandExecutionError(
'\'{0}\' is not a valid URL'.format(extra_index_url)
)
cmd.extend(['--extra-index-url', extra_index_url])
cmd_kwargs = dict(cwd=cwd, runas=user, output_loglevel='quiet', redirect_stderr=True)
if bin_env and os.path.isdir(bin_env):
cmd_kwargs['env'] = {'VIRTUAL_ENV': bin_env}
result = __salt__['cmd.run_all'](cmd, **cmd_kwargs)
filtered = []
if not include_alpha:
filtered.append('a')
if not include_beta:
filtered.append('b')
if not include_rc:
filtered.append('rc')
if filtered:
excludes = re.compile(r'^((?!{0}).)*$'.format('|'.join(filtered)))
else:
excludes = re.compile(r'')
versions = []
for line in result['stdout'].splitlines():
match = re.search(r'\s*Could not find a version.* \(from versions: (.*)\)', line)
if match:
versions = [v for v in match.group(1).split(', ') if v and excludes.match(v)]
versions.sort(key=pkg_resources.parse_version)
break
if not versions:
return None
return versions
|
saltstack/salt
|
salt/modules/pip.py
|
upgrade
|
python
|
def upgrade(bin_env=None,
user=None,
cwd=None,
use_vt=False):
'''
.. versionadded:: 2015.5.0
Upgrades outdated pip packages.
.. note::
On Windows you can't update salt from pip using salt, so salt will be
skipped
Returns a dict containing the changes.
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
CLI Example:
.. code-block:: bash
salt '*' pip.upgrade
'''
ret = {'changes': {},
'result': True,
'comment': '',
}
cmd = _get_pip_bin(bin_env)
cmd.extend(['install', '-U'])
old = list_(bin_env=bin_env, user=user, cwd=cwd)
cmd_kwargs = dict(cwd=cwd, use_vt=use_vt)
if bin_env and os.path.isdir(bin_env):
cmd_kwargs['env'] = {'VIRTUAL_ENV': bin_env}
errors = False
for pkg in list_upgrades(bin_env=bin_env, user=user, cwd=cwd):
if pkg == 'salt':
if salt.utils.platform.is_windows():
continue
result = __salt__['cmd.run_all'](cmd + [pkg], **cmd_kwargs)
if result['retcode'] != 0:
errors = True
if 'stderr' in result:
ret['comment'] += result['stderr']
if errors:
ret['result'] = False
_clear_context(bin_env)
new = list_(bin_env=bin_env, user=user, cwd=cwd)
ret['changes'] = salt.utils.data.compare_dicts(old, new)
return ret
|
.. versionadded:: 2015.5.0
Upgrades outdated pip packages.
.. note::
On Windows you can't update salt from pip using salt, so salt will be
skipped
Returns a dict containing the changes.
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
CLI Example:
.. code-block:: bash
salt '*' pip.upgrade
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/pip.py#L1408-L1463
|
[
"def list_(prefix=None,\n bin_env=None,\n user=None,\n cwd=None,\n env_vars=None,\n **kwargs):\n '''\n Filter list of installed apps from ``freeze`` and check to see if\n ``prefix`` exists in the list of packages installed.\n\n .. note::\n\n If the version of pip available is older than 8.0.3, the packages\n ``wheel``, ``setuptools``, and ``distribute`` will not be reported by\n this function even if they are installed. Unlike :py:func:`pip.freeze\n <salt.modules.pip.freeze>`, this function always reports the version of\n pip which is installed.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' pip.list salt\n '''\n packages = {}\n\n if prefix is None or 'pip'.startswith(prefix):\n packages['pip'] = version(bin_env)\n\n for line in freeze(bin_env=bin_env,\n user=user,\n cwd=cwd,\n env_vars=env_vars,\n **kwargs):\n if line.startswith('-f') or line.startswith('#'):\n # ignore -f line as it contains --find-links directory\n # ignore comment lines\n continue\n elif line.startswith('-e hg+not trust'):\n # ignore hg + not trust problem\n continue\n elif line.startswith('-e'):\n line = line.split('-e ')[1]\n if '#egg=' in line:\n version_, name = line.split('#egg=')\n else:\n if len(line.split('===')) >= 2:\n name = line.split('===')[0]\n version_ = line.split('===')[1]\n elif len(line.split('==')) >= 2:\n name = line.split('==')[0]\n version_ = line.split('==')[1]\n elif len(line.split('===')) >= 2:\n name = line.split('===')[0]\n version_ = line.split('===')[1]\n elif len(line.split('==')) >= 2:\n name = line.split('==')[0]\n version_ = line.split('==')[1]\n else:\n logger.error('Can\\'t parse line \\'%s\\'', line)\n continue\n\n if prefix:\n if name.lower().startswith(prefix.lower()):\n packages[name] = version_\n else:\n packages[name] = version_\n\n return packages\n",
"def list_upgrades(bin_env=None,\n user=None,\n cwd=None):\n '''\n Check whether or not an upgrade is available for all packages\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' pip.list_upgrades\n '''\n cmd = _get_pip_bin(bin_env)\n cmd.extend(['list', '--outdated'])\n\n pip_version = version(bin_env)\n # Pip started supporting the ability to output json starting with 9.0.0\n min_version = '9.0'\n if salt.utils.versions.compare(ver1=pip_version,\n oper='>=',\n ver2=min_version):\n cmd.append('--format=json')\n\n cmd_kwargs = dict(cwd=cwd, runas=user)\n if bin_env and os.path.isdir(bin_env):\n cmd_kwargs['env'] = {'VIRTUAL_ENV': bin_env}\n\n result = __salt__['cmd.run_all'](cmd, **cmd_kwargs)\n if result['retcode']:\n raise CommandExecutionError(result['stderr'], info=result)\n\n packages = {}\n # Pip started supporting the ability to output json starting with 9.0.0\n # Older versions will have to parse stdout\n if salt.utils.versions.compare(ver1=pip_version, oper='<', ver2='9.0.0'):\n # Pip versions < 8.0.0 had a different output format\n # Sample data:\n # pip (Current: 7.1.2 Latest: 10.0.1 [wheel])\n # psutil (Current: 5.2.2 Latest: 5.4.5 [wheel])\n # pyasn1 (Current: 0.2.3 Latest: 0.4.2 [wheel])\n # pycparser (Current: 2.17 Latest: 2.18 [sdist])\n if salt.utils.versions.compare(ver1=pip_version, oper='<', ver2='8.0.0'):\n logger.debug('pip module: Old output format')\n pat = re.compile(r'(\\S*)\\s+\\(.*Latest:\\s+(.*)\\)')\n\n # New output format for version 8.0.0+\n # Sample data:\n # pip (8.0.0) - Latest: 10.0.1 [wheel]\n # psutil (5.2.2) - Latest: 5.4.5 [wheel]\n # pyasn1 (0.2.3) - Latest: 0.4.2 [wheel]\n # pycparser (2.17) - Latest: 2.18 [sdist]\n else:\n logger.debug('pip module: New output format')\n pat = re.compile(r'(\\S*)\\s+\\(.*\\)\\s+-\\s+Latest:\\s+(.*)')\n\n for line in result['stdout'].splitlines():\n match = pat.search(line)\n if match:\n name, version_ = match.groups()\n else:\n logger.error('Can\\'t parse line \\'%s\\'', line)\n continue\n packages[name] = version_\n\n else:\n logger.debug('pip module: JSON output format')\n try:\n pkgs = salt.utils.json.loads(result['stdout'], strict=False)\n except ValueError:\n raise CommandExecutionError('Invalid JSON', info=result)\n\n for pkg in pkgs:\n packages[pkg['name']] = '{0} [{1}]'.format(pkg['latest_version'],\n pkg['latest_filetype'])\n\n return packages\n",
"def _clear_context(bin_env=None):\n '''\n Remove the cached pip version\n '''\n contextkey = 'pip.version'\n if bin_env is not None:\n contextkey = '{0}.{1}'.format(contextkey, bin_env)\n __context__.pop(contextkey, None)\n",
"def _get_pip_bin(bin_env):\n '''\n Locate the pip binary, either from `bin_env` as a virtualenv, as the\n executable itself, or from searching conventional filesystem locations\n '''\n if not bin_env:\n logger.debug('pip: Using pip from currently-running Python')\n return [os.path.normpath(sys.executable), '-m', 'pip']\n\n python_bin = 'python.exe' if salt.utils.platform.is_windows() else 'python'\n\n def _search_paths(*basedirs):\n ret = []\n for path in basedirs:\n ret.extend([\n os.path.join(path, python_bin),\n os.path.join(path, 'bin', python_bin),\n os.path.join(path, 'Scripts', python_bin)\n ])\n return ret\n\n # try to get python bin from virtualenv (i.e. bin_env)\n if os.path.isdir(bin_env):\n for bin_path in _search_paths(bin_env):\n if os.path.isfile(bin_path):\n if os.access(bin_path, os.X_OK):\n logger.debug('pip: Found python binary: %s', bin_path)\n return [os.path.normpath(bin_path), '-m', 'pip']\n else:\n logger.debug(\n 'pip: Found python binary by name but it is not '\n 'executable: %s', bin_path\n )\n raise CommandNotFoundError(\n 'Could not find a pip binary in virtualenv {0}'.format(bin_env)\n )\n\n # bin_env is the python or pip binary\n elif os.access(bin_env, os.X_OK):\n if os.path.isfile(bin_env):\n # If the python binary was passed, return it\n if 'python' in os.path.basename(bin_env):\n return [os.path.normpath(bin_env), '-m', 'pip']\n # We have been passed a pip binary, use the pip binary.\n return [os.path.normpath(bin_env)]\n\n raise CommandExecutionError(\n 'Could not find a pip binary within {0}'.format(bin_env)\n )\n else:\n raise CommandNotFoundError(\n 'Access denied to {0}, could not find a pip binary'.format(bin_env)\n )\n"
] |
# -*- coding: utf-8 -*-
r'''
Install Python packages with pip to either the system or a virtualenv
Windows Support
===============
.. versionadded:: 2014.7.4
Salt now uses a portable python. As a result the entire pip module is now
functional on the salt installation itself. You can pip install dependencies
for your custom modules. You can even upgrade salt itself using pip. For this
to work properly, you must specify the Current Working Directory (``cwd``) and
the Pip Binary (``bin_env``) salt should use. The variable ``pip_bin`` can be
either a virtualenv path or the path to the pip binary itself.
For example, the following command will list all software installed using pip
to your current salt environment:
.. code-block:: bat
salt <minion> pip.list cwd='C:\salt\bin\Scripts' bin_env='C:\salt\bin\Scripts\pip.exe'
Specifying the ``cwd`` and ``bin_env`` options ensures you're modifying the
salt environment. If these are omitted, it will default to the local
installation of python. If python is not installed locally it will fail saying
it couldn't find pip.
State File Support
------------------
This functionality works in states as well. If you need to pip install colorama
with a state, for example, the following will work:
.. code-block:: yaml
install_colorama:
pip.installed:
- name: colorama
- cwd: 'C:\salt\bin\scripts'
- bin_env: 'C:\salt\bin\scripts\pip.exe'
- upgrade: True
Upgrading Salt using Pip
------------------------
You can now update salt using pip to any version from the 2014.7 branch
forward. Previous version require recompiling some of the dependencies which is
painful in windows.
To do this you just use pip with git to update to the version you want and then
restart the service. Here is a sample state file that upgrades salt to the head
of the 2015.5 branch:
.. code-block:: yaml
install_salt:
pip.installed:
- cwd: 'C:\salt\bin\scripts'
- bin_env: 'C:\salt\bin\scripts\pip.exe'
- editable: git+https://github.com/saltstack/salt@2015.5#egg=salt
- upgrade: True
restart_service:
service.running:
- name: salt-minion
- enable: True
- watch:
- pip: install_salt
.. note::
If you're having problems, you might try doubling the back slashes. For
example, cwd: 'C:\\salt\\bin\\scripts'. Sometimes python thinks the single
back slash is an escape character.
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import logging
import os
try:
import pkg_resources
except ImportError:
pkg_resources = None
import re
import shutil
import sys
import tempfile
# Import Salt libs
import salt.utils.data
import salt.utils.files
import salt.utils.json
import salt.utils.locales
import salt.utils.platform
import salt.utils.stringutils
import salt.utils.url
import salt.utils.versions
from salt.ext import six
from salt.exceptions import CommandExecutionError, CommandNotFoundError
# This needs to be named logger so we don't shadow it in pip.install
logger = logging.getLogger(__name__) # pylint: disable=C0103
# Don't shadow built-in's.
__func_alias__ = {
'list_': 'list'
}
VALID_PROTOS = ['http', 'https', 'ftp', 'file']
rex_pip_chain_read = re.compile(r'-r\s(.*)\n?', re.MULTILINE)
def __virtual__():
'''
There is no way to verify that pip is installed without inspecting the
entire filesystem. If it's not installed in a conventional location, the
user is required to provide the location of pip each time it is used.
'''
if pkg_resources is None:
ret = False, 'Package dependency "pkg_resource" is missing'
else:
ret = 'pip'
return ret
def _clear_context(bin_env=None):
'''
Remove the cached pip version
'''
contextkey = 'pip.version'
if bin_env is not None:
contextkey = '{0}.{1}'.format(contextkey, bin_env)
__context__.pop(contextkey, None)
def _get_pip_bin(bin_env):
'''
Locate the pip binary, either from `bin_env` as a virtualenv, as the
executable itself, or from searching conventional filesystem locations
'''
if not bin_env:
logger.debug('pip: Using pip from currently-running Python')
return [os.path.normpath(sys.executable), '-m', 'pip']
python_bin = 'python.exe' if salt.utils.platform.is_windows() else 'python'
def _search_paths(*basedirs):
ret = []
for path in basedirs:
ret.extend([
os.path.join(path, python_bin),
os.path.join(path, 'bin', python_bin),
os.path.join(path, 'Scripts', python_bin)
])
return ret
# try to get python bin from virtualenv (i.e. bin_env)
if os.path.isdir(bin_env):
for bin_path in _search_paths(bin_env):
if os.path.isfile(bin_path):
if os.access(bin_path, os.X_OK):
logger.debug('pip: Found python binary: %s', bin_path)
return [os.path.normpath(bin_path), '-m', 'pip']
else:
logger.debug(
'pip: Found python binary by name but it is not '
'executable: %s', bin_path
)
raise CommandNotFoundError(
'Could not find a pip binary in virtualenv {0}'.format(bin_env)
)
# bin_env is the python or pip binary
elif os.access(bin_env, os.X_OK):
if os.path.isfile(bin_env):
# If the python binary was passed, return it
if 'python' in os.path.basename(bin_env):
return [os.path.normpath(bin_env), '-m', 'pip']
# We have been passed a pip binary, use the pip binary.
return [os.path.normpath(bin_env)]
raise CommandExecutionError(
'Could not find a pip binary within {0}'.format(bin_env)
)
else:
raise CommandNotFoundError(
'Access denied to {0}, could not find a pip binary'.format(bin_env)
)
def _get_cached_requirements(requirements, saltenv):
'''
Get the location of a cached requirements file; caching if necessary.
'''
req_file, senv = salt.utils.url.parse(requirements)
if senv:
saltenv = senv
if req_file not in __salt__['cp.list_master'](saltenv):
# Requirements file does not exist in the given saltenv.
return False
cached_requirements = __salt__['cp.is_cached'](
requirements, saltenv
)
if not cached_requirements:
# It's not cached, let's cache it.
cached_requirements = __salt__['cp.cache_file'](
requirements, saltenv
)
# Check if the master version has changed.
if __salt__['cp.hash_file'](requirements, saltenv) != \
__salt__['cp.hash_file'](cached_requirements, saltenv):
cached_requirements = __salt__['cp.cache_file'](
requirements, saltenv
)
return cached_requirements
def _get_env_activate(bin_env):
'''
Return the path to the activate binary
'''
if not bin_env:
raise CommandNotFoundError('Could not find a `activate` binary')
if os.path.isdir(bin_env):
if salt.utils.platform.is_windows():
activate_bin = os.path.join(bin_env, 'Scripts', 'activate.bat')
else:
activate_bin = os.path.join(bin_env, 'bin', 'activate')
if os.path.isfile(activate_bin):
return activate_bin
raise CommandNotFoundError('Could not find a `activate` binary')
def _find_req(link):
logger.info('_find_req -- link = %s', link)
with salt.utils.files.fopen(link) as fh_link:
child_links = rex_pip_chain_read.findall(
salt.utils.stringutils.to_unicode(fh_link.read())
)
base_path = os.path.dirname(link)
child_links = [os.path.join(base_path, d) for d in child_links]
return child_links
def _resolve_requirements_chain(requirements):
'''
Return an array of requirements file paths that can be used to complete
the no_chown==False && user != None conundrum
'''
chain = []
if isinstance(requirements, six.string_types):
requirements = [requirements]
for req_file in requirements:
chain.append(req_file)
chain.extend(_resolve_requirements_chain(_find_req(req_file)))
return chain
def _process_requirements(requirements, cmd, cwd, saltenv, user):
'''
Process the requirements argument
'''
cleanup_requirements = []
if requirements is not None:
if isinstance(requirements, six.string_types):
requirements = [r.strip() for r in requirements.split(',')]
elif not isinstance(requirements, list):
raise TypeError('requirements must be a string or list')
treq = None
for requirement in requirements:
logger.debug('TREQ IS: %s', treq)
if requirement.startswith('salt://'):
cached_requirements = _get_cached_requirements(
requirement, saltenv
)
if not cached_requirements:
ret = {'result': False,
'comment': 'pip requirements file \'{0}\' not found'
.format(requirement)}
return None, ret
requirement = cached_requirements
if user:
# Need to make a temporary copy since the user will, most
# likely, not have the right permissions to read the file
if not treq:
treq = tempfile.mkdtemp()
__salt__['file.chown'](treq, user, None)
# In Windows, just being owner of a file isn't enough. You also
# need permissions
if salt.utils.platform.is_windows():
__utils__['dacl.set_permissions'](
obj_name=treq,
principal=user,
permissions='read_execute')
current_directory = None
if not current_directory:
current_directory = os.path.abspath(os.curdir)
logger.info('_process_requirements from directory, '
'%s -- requirement: %s', cwd, requirement)
if cwd is None:
r = requirement
c = cwd
requirement_abspath = os.path.abspath(requirement)
cwd = os.path.dirname(requirement_abspath)
requirement = os.path.basename(requirement)
logger.debug('\n\tcwd: %s -> %s\n\trequirement: %s -> %s\n',
c, cwd, r, requirement
)
os.chdir(cwd)
reqs = _resolve_requirements_chain(requirement)
os.chdir(current_directory)
logger.info('request files: %s', reqs)
for req_file in reqs:
if not os.path.isabs(req_file):
req_file = os.path.join(cwd, req_file)
logger.debug('TREQ N CWD: %s -- %s -- for %s', treq, cwd, req_file)
target_path = os.path.join(treq, os.path.basename(req_file))
logger.debug('S: %s', req_file)
logger.debug('T: %s', target_path)
target_base = os.path.dirname(target_path)
if not os.path.exists(target_base):
os.makedirs(target_base, mode=0o755)
__salt__['file.chown'](target_base, user, None)
if not os.path.exists(target_path):
logger.debug(
'Copying %s to %s', req_file, target_path
)
__salt__['file.copy'](req_file, target_path)
logger.debug(
'Changing ownership of requirements file \'%s\' to '
'user \'%s\'', target_path, user
)
__salt__['file.chown'](target_path, user, None)
req_args = os.path.join(treq, requirement) if treq else requirement
cmd.extend(['--requirement', req_args])
cleanup_requirements.append(treq)
logger.debug('CLEANUP_REQUIREMENTS: %s', cleanup_requirements)
return cleanup_requirements, None
def _format_env_vars(env_vars):
ret = {}
if env_vars:
if isinstance(env_vars, dict):
for key, val in six.iteritems(env_vars):
if not isinstance(key, six.string_types):
key = str(key) # future lint: disable=blacklisted-function
if not isinstance(val, six.string_types):
val = str(val) # future lint: disable=blacklisted-function
ret[key] = val
else:
raise CommandExecutionError(
'env_vars {0} is not a dictionary'.format(env_vars))
return ret
def install(pkgs=None, # pylint: disable=R0912,R0913,R0914
requirements=None,
bin_env=None,
use_wheel=False,
no_use_wheel=False,
log=None,
proxy=None,
timeout=None,
editable=None,
find_links=None,
index_url=None,
extra_index_url=None,
no_index=False,
mirrors=None,
build=None,
target=None,
download=None,
download_cache=None,
source=None,
upgrade=False,
force_reinstall=False,
ignore_installed=False,
exists_action=None,
no_deps=False,
no_install=False,
no_download=False,
global_options=None,
install_options=None,
user=None,
cwd=None,
pre_releases=False,
cert=None,
allow_all_external=False,
allow_external=None,
allow_unverified=None,
process_dependency_links=False,
saltenv='base',
env_vars=None,
use_vt=False,
trusted_host=None,
no_cache_dir=False,
cache_dir=None,
no_binary=None,
extra_args=None,
**kwargs):
'''
Install packages with pip
Install packages individually or from a pip requirements file. Install
packages globally or to a virtualenv.
pkgs
Comma separated list of packages to install
requirements
Path to requirements
bin_env
Path to pip (or to a virtualenv). This can be used to specify the path
to the pip to use when more than one Python release is installed (e.g.
``/usr/bin/pip-2.7`` or ``/usr/bin/pip-2.6``. If a directory path is
specified, it is assumed to be a virtualenv.
.. note::
For Windows, if the pip module is being used to upgrade the pip
package, bin_env should be the path to the virtualenv or to the
python binary that should be used. The pip command is unable to
upgrade itself in Windows.
use_wheel
Prefer wheel archives (requires pip>=1.4)
no_use_wheel
Force to not use wheel archives (requires pip>=1.4,<10.0.0)
no_binary
Force to not use binary packages (requires pip >= 7.0.0)
Accepts either :all: to disable all binary packages, :none: to empty the set,
or one or more package names with commas between them
log
Log file where a complete (maximum verbosity) record will be kept
proxy
Specify a proxy in the form ``user:passwd@proxy.server:port``. Note
that the ``user:password@`` is optional and required only if you are
behind an authenticated proxy. If you provide
``user@proxy.server:port`` then you will be prompted for a password.
timeout
Set the socket timeout (default 15 seconds)
editable
install something editable (e.g.
``git+https://github.com/worldcompany/djangoembed.git#egg=djangoembed``)
find_links
URL to search for packages
index_url
Base URL of Python Package Index
extra_index_url
Extra URLs of package indexes to use in addition to ``index_url``
no_index
Ignore package index
mirrors
Specific mirror URL(s) to query (automatically adds --use-mirrors)
.. warning::
This option has been deprecated and removed in pip version 7.0.0.
Please use ``index_url`` and/or ``extra_index_url`` instead.
build
Unpack packages into ``build`` dir
target
Install packages into ``target`` dir
download
Download packages into ``download`` instead of installing them
download_cache | cache_dir
Cache downloaded packages in ``download_cache`` or ``cache_dir`` dir
source
Check out ``editable`` packages into ``source`` dir
upgrade
Upgrade all packages to the newest available version
force_reinstall
When upgrading, reinstall all packages even if they are already
up-to-date.
ignore_installed
Ignore the installed packages (reinstalling instead)
exists_action
Default action when a path already exists: (s)witch, (i)gnore, (w)ipe,
(b)ackup
no_deps
Ignore package dependencies
no_install
Download and unpack all packages, but don't actually install them
no_download
Don't download any packages, just install the ones already downloaded
(completes an install run with ``--no-install``)
install_options
Extra arguments to be supplied to the setup.py install command (e.g.
like ``--install-option='--install-scripts=/usr/local/bin'``). Use
multiple --install-option options to pass multiple options to setup.py
install. If you are using an option with a directory path, be sure to
use absolute path.
global_options
Extra global options to be supplied to the setup.py call before the
install command.
user
The user under which to run pip
cwd
Directory from which to run pip
pre_releases
Include pre-releases in the available versions
cert
Provide a path to an alternate CA bundle
allow_all_external
Allow the installation of all externally hosted files
allow_external
Allow the installation of externally hosted files (comma separated
list)
allow_unverified
Allow the installation of insecure and unverifiable files (comma
separated list)
process_dependency_links
Enable the processing of dependency links
env_vars
Set environment variables that some builds will depend on. For example,
a Python C-module may have a Makefile that needs INCLUDE_PATH set to
pick up a header file while compiling. This must be in the form of a
dictionary or a mapping.
Example:
.. code-block:: bash
salt '*' pip.install django_app env_vars="{'CUSTOM_PATH': '/opt/django_app'}"
trusted_host
Mark this host as trusted, even though it does not have valid or any
HTTPS.
use_vt
Use VT terminal emulation (see output while installing)
no_cache_dir
Disable the cache.
extra_args
pip keyword and positional arguments not yet implemented in salt
.. code-block:: yaml
salt '*' pip.install pandas extra_args="[{'--latest-pip-kwarg':'param'}, '--latest-pip-arg']"
.. warning::
If unsupported options are passed here that are not supported in a
minion's version of pip, a `No such option error` will be thrown.
Will be translated into the following pip command:
.. code-block:: bash
pip install pandas --latest-pip-kwarg param --latest-pip-arg
CLI Example:
.. code-block:: bash
salt '*' pip.install <package name>,<package2 name>
salt '*' pip.install requirements=/path/to/requirements.txt
salt '*' pip.install <package name> bin_env=/path/to/virtualenv
salt '*' pip.install <package name> bin_env=/path/to/pip_bin
Complicated CLI example::
salt '*' pip.install markdown,django \
editable=git+https://github.com/worldcompany/djangoembed.git#egg=djangoembed upgrade=True no_deps=True
'''
cmd = _get_pip_bin(bin_env)
cmd.append('install')
cleanup_requirements, error = _process_requirements(
requirements=requirements,
cmd=cmd,
cwd=cwd,
saltenv=saltenv,
user=user
)
if error:
return error
cur_version = version(bin_env)
if use_wheel:
min_version = '1.4'
max_version = '9.0.3'
too_low = salt.utils.versions.compare(ver1=cur_version, oper='<', ver2=min_version)
too_high = salt.utils.versions.compare(ver1=cur_version, oper='>', ver2=max_version)
if too_low or too_high:
logger.error(
'The --use-wheel option is only supported in pip between %s and '
'%s. The version of pip detected is %s. This option '
'will be ignored.', min_version, max_version, cur_version
)
else:
cmd.append('--use-wheel')
if no_use_wheel:
min_version = '1.4'
max_version = '9.0.3'
too_low = salt.utils.versions.compare(ver1=cur_version, oper='<', ver2=min_version)
too_high = salt.utils.versions.compare(ver1=cur_version, oper='>', ver2=max_version)
if too_low or too_high:
logger.error(
'The --no-use-wheel option is only supported in pip between %s and '
'%s. The version of pip detected is %s. This option '
'will be ignored.', min_version, max_version, cur_version
)
else:
cmd.append('--no-use-wheel')
if no_binary:
min_version = '7.0.0'
too_low = salt.utils.versions.compare(ver1=cur_version, oper='<', ver2=min_version)
if too_low:
logger.error(
'The --no-binary option is only supported in pip %s and '
'newer. The version of pip detected is %s. This option '
'will be ignored.', min_version, cur_version
)
else:
if isinstance(no_binary, list):
no_binary = ','.join(no_binary)
cmd.extend(['--no-binary', no_binary])
if log:
if os.path.isdir(log):
raise IOError(
'\'{0}\' is a directory. Use --log path_to_file'.format(log))
elif not os.access(log, os.W_OK):
raise IOError('\'{0}\' is not writeable'.format(log))
cmd.extend(['--log', log])
if proxy:
cmd.extend(['--proxy', proxy])
if timeout:
try:
if isinstance(timeout, float):
# Catch floating point input, exception will be caught in
# exception class below.
raise ValueError('Timeout cannot be a float')
int(timeout)
except ValueError:
raise ValueError(
'\'{0}\' is not a valid timeout, must be an integer'
.format(timeout)
)
cmd.extend(['--timeout', timeout])
if find_links:
if isinstance(find_links, six.string_types):
find_links = [l.strip() for l in find_links.split(',')]
for link in find_links:
if not (salt.utils.url.validate(link, VALID_PROTOS) or os.path.exists(link)):
raise CommandExecutionError(
'\'{0}\' is not a valid URL or path'.format(link)
)
cmd.extend(['--find-links', link])
if no_index and (index_url or extra_index_url):
raise CommandExecutionError(
'\'no_index\' and (\'index_url\' or \'extra_index_url\') are '
'mutually exclusive.'
)
if index_url:
if not salt.utils.url.validate(index_url, VALID_PROTOS):
raise CommandExecutionError(
'\'{0}\' is not a valid URL'.format(index_url)
)
cmd.extend(['--index-url', index_url])
if extra_index_url:
if not salt.utils.url.validate(extra_index_url, VALID_PROTOS):
raise CommandExecutionError(
'\'{0}\' is not a valid URL'.format(extra_index_url)
)
cmd.extend(['--extra-index-url', extra_index_url])
if no_index:
cmd.append('--no-index')
if mirrors:
# https://github.com/pypa/pip/pull/2641/files#diff-3ef137fb9ffdd400f117a565cd94c188L216
if salt.utils.versions.compare(ver1=cur_version, oper='>=', ver2='7.0.0'):
raise CommandExecutionError(
'pip >= 7.0.0 does not support mirror argument:'
' use index_url and/or extra_index_url instead'
)
if isinstance(mirrors, six.string_types):
mirrors = [m.strip() for m in mirrors.split(',')]
cmd.append('--use-mirrors')
for mirror in mirrors:
if not mirror.startswith('http://'):
raise CommandExecutionError(
'\'{0}\' is not a valid URL'.format(mirror)
)
cmd.extend(['--mirrors', mirror])
if build:
cmd.extend(['--build', build])
if target:
cmd.extend(['--target', target])
if download:
cmd.extend(['--download', download])
if download_cache or cache_dir:
cmd.extend(['--cache-dir' if salt.utils.versions.compare(
ver1=cur_version, oper='>=', ver2='6.0'
) else '--download-cache', download_cache or cache_dir])
if source:
cmd.extend(['--source', source])
if upgrade:
cmd.append('--upgrade')
if force_reinstall:
cmd.append('--force-reinstall')
if ignore_installed:
cmd.append('--ignore-installed')
if exists_action:
if exists_action.lower() not in ('s', 'i', 'w', 'b'):
raise CommandExecutionError(
'The exists_action pip option only supports the values '
's, i, w, and b. \'{0}\' is not valid.'.format(exists_action)
)
cmd.extend(['--exists-action', exists_action])
if no_deps:
cmd.append('--no-deps')
if no_install:
cmd.append('--no-install')
if no_download:
cmd.append('--no-download')
if no_cache_dir:
cmd.append('--no-cache-dir')
if pre_releases:
# Check the locally installed pip version
pip_version = cur_version
# From pip v1.4 the --pre flag is available
if salt.utils.versions.compare(ver1=pip_version, oper='>=', ver2='1.4'):
cmd.append('--pre')
if cert:
cmd.extend(['--cert', cert])
if global_options:
if isinstance(global_options, six.string_types):
global_options = [go.strip() for go in global_options.split(',')]
for opt in global_options:
cmd.extend(['--global-option', opt])
if install_options:
if isinstance(install_options, six.string_types):
install_options = [io.strip() for io in install_options.split(',')]
for opt in install_options:
cmd.extend(['--install-option', opt])
if pkgs:
if not isinstance(pkgs, list):
try:
pkgs = [p.strip() for p in pkgs.split(',')]
except AttributeError:
pkgs = [p.strip() for p in six.text_type(pkgs).split(',')]
pkgs = salt.utils.data.stringify(salt.utils.data.decode_list(pkgs))
# It's possible we replaced version-range commas with semicolons so
# they would survive the previous line (in the pip.installed state).
# Put the commas back in while making sure the names are contained in
# quotes, this allows for proper version spec passing salt>=0.17.0
cmd.extend([p.replace(';', ',') for p in pkgs])
elif not any([requirements, editable]):
# Starting with pip 10.0.0, if no packages are specified in the
# command, it returns a retcode 1. So instead of running the command,
# just return the output without running pip.
return {'retcode': 0, 'stdout': 'No packages to install.'}
if editable:
egg_match = re.compile(r'(?:#|#.*?&)egg=([^&]*)')
if isinstance(editable, six.string_types):
editable = [e.strip() for e in editable.split(',')]
for entry in editable:
# Is the editable local?
if not (entry == '.' or entry.startswith(('file://', '/'))):
match = egg_match.search(entry)
if not match or not match.group(1):
# Missing #egg=theEggName
raise CommandExecutionError(
'You must specify an egg for this editable'
)
cmd.extend(['--editable', entry])
if allow_all_external:
cmd.append('--allow-all-external')
if allow_external:
if isinstance(allow_external, six.string_types):
allow_external = [p.strip() for p in allow_external.split(',')]
for pkg in allow_external:
cmd.extend(['--allow-external', pkg])
if allow_unverified:
if isinstance(allow_unverified, six.string_types):
allow_unverified = \
[p.strip() for p in allow_unverified.split(',')]
for pkg in allow_unverified:
cmd.extend(['--allow-unverified', pkg])
if process_dependency_links:
cmd.append('--process-dependency-links')
if trusted_host:
cmd.extend(['--trusted-host', trusted_host])
if extra_args:
# These are arguments from the latest version of pip that
# have not yet been implemented in salt
for arg in extra_args:
# It is a keyword argument
if isinstance(arg, dict):
# There will only ever be one item in this dictionary
key, val = arg.popitem()
# Don't allow any recursion into keyword arg definitions
# Don't allow multiple definitions of a keyword
if isinstance(val, (dict, list)):
raise TypeError("Too many levels in: {}".format(key))
# This is a a normal one-to-one keyword argument
cmd.extend([key, val])
# It is a positional argument, append it to the list
else:
cmd.append(arg)
cmd_kwargs = dict(saltenv=saltenv, use_vt=use_vt, runas=user)
if kwargs:
cmd_kwargs.update(kwargs)
if env_vars:
cmd_kwargs.setdefault('env', {}).update(_format_env_vars(env_vars))
try:
if cwd:
cmd_kwargs['cwd'] = cwd
if bin_env and os.path.isdir(bin_env):
cmd_kwargs.setdefault('env', {})['VIRTUAL_ENV'] = bin_env
logger.debug(
'TRY BLOCK: end of pip.install -- cmd: %s, cmd_kwargs: %s',
cmd, cmd_kwargs
)
return __salt__['cmd.run_all'](cmd, python_shell=False, **cmd_kwargs)
finally:
_clear_context(bin_env)
for tempdir in [cr for cr in cleanup_requirements if cr is not None]:
if os.path.isdir(tempdir):
shutil.rmtree(tempdir)
def uninstall(pkgs=None,
requirements=None,
bin_env=None,
log=None,
proxy=None,
timeout=None,
user=None,
cwd=None,
saltenv='base',
use_vt=False):
'''
Uninstall packages individually or from a pip requirements file
pkgs
comma separated list of packages to install
requirements
Path to requirements file
bin_env
Path to pip (or to a virtualenv). This can be used to specify the path
to the pip to use when more than one Python release is installed (e.g.
``/usr/bin/pip-2.7`` or ``/usr/bin/pip-2.6``. If a directory path is
specified, it is assumed to be a virtualenv.
log
Log file where a complete (maximum verbosity) record will be kept
proxy
Specify a proxy in the format ``user:passwd@proxy.server:port``. Note
that the ``user:password@`` is optional and required only if you are
behind an authenticated proxy. If you provide
``user@proxy.server:port`` then you will be prompted for a password.
timeout
Set the socket timeout (default 15 seconds)
user
The user under which to run pip
cwd
Directory from which to run pip
use_vt
Use VT terminal emulation (see output while installing)
CLI Example:
.. code-block:: bash
salt '*' pip.uninstall <package name>,<package2 name>
salt '*' pip.uninstall requirements=/path/to/requirements.txt
salt '*' pip.uninstall <package name> bin_env=/path/to/virtualenv
salt '*' pip.uninstall <package name> bin_env=/path/to/pip_bin
'''
cmd = _get_pip_bin(bin_env)
cmd.extend(['uninstall', '-y'])
cleanup_requirements, error = _process_requirements(
requirements=requirements, cmd=cmd, saltenv=saltenv, user=user,
cwd=cwd
)
if error:
return error
if log:
try:
# TODO make this check if writeable
os.path.exists(log)
except IOError:
raise IOError('\'{0}\' is not writeable'.format(log))
cmd.extend(['--log', log])
if proxy:
cmd.extend(['--proxy', proxy])
if timeout:
try:
if isinstance(timeout, float):
# Catch floating point input, exception will be caught in
# exception class below.
raise ValueError('Timeout cannot be a float')
int(timeout)
except ValueError:
raise ValueError(
'\'{0}\' is not a valid timeout, must be an integer'
.format(timeout)
)
cmd.extend(['--timeout', timeout])
if pkgs:
if isinstance(pkgs, six.string_types):
pkgs = [p.strip() for p in pkgs.split(',')]
if requirements:
for requirement in requirements:
with salt.utils.files.fopen(requirement) as rq_:
for req in rq_:
req = salt.utils.stringutils.to_unicode(req)
try:
req_pkg, _ = req.split('==')
if req_pkg in pkgs:
pkgs.remove(req_pkg)
except ValueError:
pass
cmd.extend(pkgs)
cmd_kwargs = dict(python_shell=False, runas=user,
cwd=cwd, saltenv=saltenv, use_vt=use_vt)
if bin_env and os.path.isdir(bin_env):
cmd_kwargs['env'] = {'VIRTUAL_ENV': bin_env}
try:
return __salt__['cmd.run_all'](cmd, **cmd_kwargs)
finally:
_clear_context(bin_env)
for requirement in cleanup_requirements:
if requirement:
try:
os.remove(requirement)
except OSError:
pass
def freeze(bin_env=None,
user=None,
cwd=None,
use_vt=False,
env_vars=None,
**kwargs):
'''
Return a list of installed packages either globally or in the specified
virtualenv
bin_env
Path to pip (or to a virtualenv). This can be used to specify the path
to the pip to use when more than one Python release is installed (e.g.
``/usr/bin/pip-2.7`` or ``/usr/bin/pip-2.6``. If a directory path is
specified, it is assumed to be a virtualenv.
user
The user under which to run pip
cwd
Directory from which to run pip
.. note::
If the version of pip available is older than 8.0.3, the list will not
include the packages ``pip``, ``wheel``, ``setuptools``, or
``distribute`` even if they are installed.
CLI Example:
.. code-block:: bash
salt '*' pip.freeze bin_env=/home/code/path/to/virtualenv
'''
cmd = _get_pip_bin(bin_env)
cmd.append('freeze')
# Include pip, setuptools, distribute, wheel
min_version = '8.0.3'
cur_version = version(bin_env)
if salt.utils.versions.compare(ver1=cur_version, oper='<', ver2=min_version):
logger.warning(
'The version of pip installed is %s, which is older than %s. '
'The packages pip, wheel, setuptools, and distribute will not be '
'included in the output of pip.freeze', cur_version, min_version
)
else:
cmd.append('--all')
cmd_kwargs = dict(runas=user, cwd=cwd, use_vt=use_vt, python_shell=False)
if kwargs:
cmd_kwargs.update(**kwargs)
if bin_env and os.path.isdir(bin_env):
cmd_kwargs['env'] = {'VIRTUAL_ENV': bin_env}
if env_vars:
cmd_kwargs.setdefault('env', {}).update(_format_env_vars(env_vars))
result = __salt__['cmd.run_all'](cmd, **cmd_kwargs)
if result['retcode']:
raise CommandExecutionError(result['stderr'], info=result)
return result['stdout'].splitlines()
def list_(prefix=None,
bin_env=None,
user=None,
cwd=None,
env_vars=None,
**kwargs):
'''
Filter list of installed apps from ``freeze`` and check to see if
``prefix`` exists in the list of packages installed.
.. note::
If the version of pip available is older than 8.0.3, the packages
``wheel``, ``setuptools``, and ``distribute`` will not be reported by
this function even if they are installed. Unlike :py:func:`pip.freeze
<salt.modules.pip.freeze>`, this function always reports the version of
pip which is installed.
CLI Example:
.. code-block:: bash
salt '*' pip.list salt
'''
packages = {}
if prefix is None or 'pip'.startswith(prefix):
packages['pip'] = version(bin_env)
for line in freeze(bin_env=bin_env,
user=user,
cwd=cwd,
env_vars=env_vars,
**kwargs):
if line.startswith('-f') or line.startswith('#'):
# ignore -f line as it contains --find-links directory
# ignore comment lines
continue
elif line.startswith('-e hg+not trust'):
# ignore hg + not trust problem
continue
elif line.startswith('-e'):
line = line.split('-e ')[1]
if '#egg=' in line:
version_, name = line.split('#egg=')
else:
if len(line.split('===')) >= 2:
name = line.split('===')[0]
version_ = line.split('===')[1]
elif len(line.split('==')) >= 2:
name = line.split('==')[0]
version_ = line.split('==')[1]
elif len(line.split('===')) >= 2:
name = line.split('===')[0]
version_ = line.split('===')[1]
elif len(line.split('==')) >= 2:
name = line.split('==')[0]
version_ = line.split('==')[1]
else:
logger.error('Can\'t parse line \'%s\'', line)
continue
if prefix:
if name.lower().startswith(prefix.lower()):
packages[name] = version_
else:
packages[name] = version_
return packages
def version(bin_env=None):
'''
.. versionadded:: 0.17.0
Returns the version of pip. Use ``bin_env`` to specify the path to a
virtualenv and get the version of pip in that virtualenv.
If unable to detect the pip version, returns ``None``.
CLI Example:
.. code-block:: bash
salt '*' pip.version
'''
contextkey = 'pip.version'
if bin_env is not None:
contextkey = '{0}.{1}'.format(contextkey, bin_env)
if contextkey in __context__:
return __context__[contextkey]
cmd = _get_pip_bin(bin_env)[:]
cmd.append('--version')
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
if ret['retcode']:
raise CommandNotFoundError('Could not find a `pip` binary')
try:
pip_version = re.match(r'^pip (\S+)', ret['stdout']).group(1)
except AttributeError:
pip_version = None
__context__[contextkey] = pip_version
return pip_version
def list_upgrades(bin_env=None,
user=None,
cwd=None):
'''
Check whether or not an upgrade is available for all packages
CLI Example:
.. code-block:: bash
salt '*' pip.list_upgrades
'''
cmd = _get_pip_bin(bin_env)
cmd.extend(['list', '--outdated'])
pip_version = version(bin_env)
# Pip started supporting the ability to output json starting with 9.0.0
min_version = '9.0'
if salt.utils.versions.compare(ver1=pip_version,
oper='>=',
ver2=min_version):
cmd.append('--format=json')
cmd_kwargs = dict(cwd=cwd, runas=user)
if bin_env and os.path.isdir(bin_env):
cmd_kwargs['env'] = {'VIRTUAL_ENV': bin_env}
result = __salt__['cmd.run_all'](cmd, **cmd_kwargs)
if result['retcode']:
raise CommandExecutionError(result['stderr'], info=result)
packages = {}
# Pip started supporting the ability to output json starting with 9.0.0
# Older versions will have to parse stdout
if salt.utils.versions.compare(ver1=pip_version, oper='<', ver2='9.0.0'):
# Pip versions < 8.0.0 had a different output format
# Sample data:
# pip (Current: 7.1.2 Latest: 10.0.1 [wheel])
# psutil (Current: 5.2.2 Latest: 5.4.5 [wheel])
# pyasn1 (Current: 0.2.3 Latest: 0.4.2 [wheel])
# pycparser (Current: 2.17 Latest: 2.18 [sdist])
if salt.utils.versions.compare(ver1=pip_version, oper='<', ver2='8.0.0'):
logger.debug('pip module: Old output format')
pat = re.compile(r'(\S*)\s+\(.*Latest:\s+(.*)\)')
# New output format for version 8.0.0+
# Sample data:
# pip (8.0.0) - Latest: 10.0.1 [wheel]
# psutil (5.2.2) - Latest: 5.4.5 [wheel]
# pyasn1 (0.2.3) - Latest: 0.4.2 [wheel]
# pycparser (2.17) - Latest: 2.18 [sdist]
else:
logger.debug('pip module: New output format')
pat = re.compile(r'(\S*)\s+\(.*\)\s+-\s+Latest:\s+(.*)')
for line in result['stdout'].splitlines():
match = pat.search(line)
if match:
name, version_ = match.groups()
else:
logger.error('Can\'t parse line \'%s\'', line)
continue
packages[name] = version_
else:
logger.debug('pip module: JSON output format')
try:
pkgs = salt.utils.json.loads(result['stdout'], strict=False)
except ValueError:
raise CommandExecutionError('Invalid JSON', info=result)
for pkg in pkgs:
packages[pkg['name']] = '{0} [{1}]'.format(pkg['latest_version'],
pkg['latest_filetype'])
return packages
def is_installed(pkgname=None,
bin_env=None,
user=None,
cwd=None):
'''
.. versionadded:: 2018.3.0
Filter list of installed apps from ``freeze`` and return True or False if
``pkgname`` exists in the list of packages installed.
.. note::
If the version of pip available is older than 8.0.3, the packages
wheel, setuptools, and distribute will not be reported by this function
even if they are installed. Unlike :py:func:`pip.freeze
<salt.modules.pip.freeze>`, this function always reports the version of
pip which is installed.
CLI Example:
.. code-block:: bash
salt '*' pip.is_installed salt
'''
for line in freeze(bin_env=bin_env, user=user, cwd=cwd):
if line.startswith('-f') or line.startswith('#'):
# ignore -f line as it contains --find-links directory
# ignore comment lines
continue
elif line.startswith('-e hg+not trust'):
# ignore hg + not trust problem
continue
elif line.startswith('-e'):
line = line.split('-e ')[1]
version_, name = line.split('#egg=')
elif len(line.split('===')) >= 2:
name = line.split('===')[0]
version_ = line.split('===')[1]
elif len(line.split('==')) >= 2:
name = line.split('==')[0]
version_ = line.split('==')[1]
else:
logger.error('Can\'t parse line \'%s\'', line)
continue
if pkgname:
if pkgname == name.lower():
return True
return False
def upgrade_available(pkg,
bin_env=None,
user=None,
cwd=None):
'''
.. versionadded:: 2015.5.0
Check whether or not an upgrade is available for a given package
CLI Example:
.. code-block:: bash
salt '*' pip.upgrade_available <package name>
'''
return pkg in list_upgrades(bin_env=bin_env, user=user, cwd=cwd)
def list_all_versions(pkg,
bin_env=None,
include_alpha=False,
include_beta=False,
include_rc=False,
user=None,
cwd=None,
index_url=None,
extra_index_url=None):
'''
.. versionadded:: 2017.7.3
List all available versions of a pip package
pkg
The package to check
bin_env
Path to pip (or to a virtualenv). This can be used to specify the path
to the pip to use when more than one Python release is installed (e.g.
``/usr/bin/pip-2.7`` or ``/usr/bin/pip-2.6``. If a directory path is
specified, it is assumed to be a virtualenv.
include_alpha
Include alpha versions in the list
include_beta
Include beta versions in the list
include_rc
Include release candidates versions in the list
user
The user under which to run pip
cwd
Directory from which to run pip
index_url
Base URL of Python Package Index
.. versionadded:: 2019.2.0
extra_index_url
Additional URL of Python Package Index
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' pip.list_all_versions <package name>
'''
cmd = _get_pip_bin(bin_env)
cmd.extend(['install', '{0}==versions'.format(pkg)])
if index_url:
if not salt.utils.url.validate(index_url, VALID_PROTOS):
raise CommandExecutionError(
'\'{0}\' is not a valid URL'.format(index_url)
)
cmd.extend(['--index-url', index_url])
if extra_index_url:
if not salt.utils.url.validate(extra_index_url, VALID_PROTOS):
raise CommandExecutionError(
'\'{0}\' is not a valid URL'.format(extra_index_url)
)
cmd.extend(['--extra-index-url', extra_index_url])
cmd_kwargs = dict(cwd=cwd, runas=user, output_loglevel='quiet', redirect_stderr=True)
if bin_env and os.path.isdir(bin_env):
cmd_kwargs['env'] = {'VIRTUAL_ENV': bin_env}
result = __salt__['cmd.run_all'](cmd, **cmd_kwargs)
filtered = []
if not include_alpha:
filtered.append('a')
if not include_beta:
filtered.append('b')
if not include_rc:
filtered.append('rc')
if filtered:
excludes = re.compile(r'^((?!{0}).)*$'.format('|'.join(filtered)))
else:
excludes = re.compile(r'')
versions = []
for line in result['stdout'].splitlines():
match = re.search(r'\s*Could not find a version.* \(from versions: (.*)\)', line)
if match:
versions = [v for v in match.group(1).split(', ') if v and excludes.match(v)]
versions.sort(key=pkg_resources.parse_version)
break
if not versions:
return None
return versions
|
saltstack/salt
|
salt/modules/pip.py
|
list_all_versions
|
python
|
def list_all_versions(pkg,
bin_env=None,
include_alpha=False,
include_beta=False,
include_rc=False,
user=None,
cwd=None,
index_url=None,
extra_index_url=None):
'''
.. versionadded:: 2017.7.3
List all available versions of a pip package
pkg
The package to check
bin_env
Path to pip (or to a virtualenv). This can be used to specify the path
to the pip to use when more than one Python release is installed (e.g.
``/usr/bin/pip-2.7`` or ``/usr/bin/pip-2.6``. If a directory path is
specified, it is assumed to be a virtualenv.
include_alpha
Include alpha versions in the list
include_beta
Include beta versions in the list
include_rc
Include release candidates versions in the list
user
The user under which to run pip
cwd
Directory from which to run pip
index_url
Base URL of Python Package Index
.. versionadded:: 2019.2.0
extra_index_url
Additional URL of Python Package Index
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' pip.list_all_versions <package name>
'''
cmd = _get_pip_bin(bin_env)
cmd.extend(['install', '{0}==versions'.format(pkg)])
if index_url:
if not salt.utils.url.validate(index_url, VALID_PROTOS):
raise CommandExecutionError(
'\'{0}\' is not a valid URL'.format(index_url)
)
cmd.extend(['--index-url', index_url])
if extra_index_url:
if not salt.utils.url.validate(extra_index_url, VALID_PROTOS):
raise CommandExecutionError(
'\'{0}\' is not a valid URL'.format(extra_index_url)
)
cmd.extend(['--extra-index-url', extra_index_url])
cmd_kwargs = dict(cwd=cwd, runas=user, output_loglevel='quiet', redirect_stderr=True)
if bin_env and os.path.isdir(bin_env):
cmd_kwargs['env'] = {'VIRTUAL_ENV': bin_env}
result = __salt__['cmd.run_all'](cmd, **cmd_kwargs)
filtered = []
if not include_alpha:
filtered.append('a')
if not include_beta:
filtered.append('b')
if not include_rc:
filtered.append('rc')
if filtered:
excludes = re.compile(r'^((?!{0}).)*$'.format('|'.join(filtered)))
else:
excludes = re.compile(r'')
versions = []
for line in result['stdout'].splitlines():
match = re.search(r'\s*Could not find a version.* \(from versions: (.*)\)', line)
if match:
versions = [v for v in match.group(1).split(', ') if v and excludes.match(v)]
versions.sort(key=pkg_resources.parse_version)
break
if not versions:
return None
return versions
|
.. versionadded:: 2017.7.3
List all available versions of a pip package
pkg
The package to check
bin_env
Path to pip (or to a virtualenv). This can be used to specify the path
to the pip to use when more than one Python release is installed (e.g.
``/usr/bin/pip-2.7`` or ``/usr/bin/pip-2.6``. If a directory path is
specified, it is assumed to be a virtualenv.
include_alpha
Include alpha versions in the list
include_beta
Include beta versions in the list
include_rc
Include release candidates versions in the list
user
The user under which to run pip
cwd
Directory from which to run pip
index_url
Base URL of Python Package Index
.. versionadded:: 2019.2.0
extra_index_url
Additional URL of Python Package Index
.. versionadded:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' pip.list_all_versions <package name>
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/pip.py#L1466-L1563
|
[
"def validate(url, protos):\n '''\n Return true if the passed URL scheme is in the list of accepted protos\n '''\n if urlparse(url).scheme in protos:\n return True\n return False\n",
"def _get_pip_bin(bin_env):\n '''\n Locate the pip binary, either from `bin_env` as a virtualenv, as the\n executable itself, or from searching conventional filesystem locations\n '''\n if not bin_env:\n logger.debug('pip: Using pip from currently-running Python')\n return [os.path.normpath(sys.executable), '-m', 'pip']\n\n python_bin = 'python.exe' if salt.utils.platform.is_windows() else 'python'\n\n def _search_paths(*basedirs):\n ret = []\n for path in basedirs:\n ret.extend([\n os.path.join(path, python_bin),\n os.path.join(path, 'bin', python_bin),\n os.path.join(path, 'Scripts', python_bin)\n ])\n return ret\n\n # try to get python bin from virtualenv (i.e. bin_env)\n if os.path.isdir(bin_env):\n for bin_path in _search_paths(bin_env):\n if os.path.isfile(bin_path):\n if os.access(bin_path, os.X_OK):\n logger.debug('pip: Found python binary: %s', bin_path)\n return [os.path.normpath(bin_path), '-m', 'pip']\n else:\n logger.debug(\n 'pip: Found python binary by name but it is not '\n 'executable: %s', bin_path\n )\n raise CommandNotFoundError(\n 'Could not find a pip binary in virtualenv {0}'.format(bin_env)\n )\n\n # bin_env is the python or pip binary\n elif os.access(bin_env, os.X_OK):\n if os.path.isfile(bin_env):\n # If the python binary was passed, return it\n if 'python' in os.path.basename(bin_env):\n return [os.path.normpath(bin_env), '-m', 'pip']\n # We have been passed a pip binary, use the pip binary.\n return [os.path.normpath(bin_env)]\n\n raise CommandExecutionError(\n 'Could not find a pip binary within {0}'.format(bin_env)\n )\n else:\n raise CommandNotFoundError(\n 'Access denied to {0}, could not find a pip binary'.format(bin_env)\n )\n"
] |
# -*- coding: utf-8 -*-
r'''
Install Python packages with pip to either the system or a virtualenv
Windows Support
===============
.. versionadded:: 2014.7.4
Salt now uses a portable python. As a result the entire pip module is now
functional on the salt installation itself. You can pip install dependencies
for your custom modules. You can even upgrade salt itself using pip. For this
to work properly, you must specify the Current Working Directory (``cwd``) and
the Pip Binary (``bin_env``) salt should use. The variable ``pip_bin`` can be
either a virtualenv path or the path to the pip binary itself.
For example, the following command will list all software installed using pip
to your current salt environment:
.. code-block:: bat
salt <minion> pip.list cwd='C:\salt\bin\Scripts' bin_env='C:\salt\bin\Scripts\pip.exe'
Specifying the ``cwd`` and ``bin_env`` options ensures you're modifying the
salt environment. If these are omitted, it will default to the local
installation of python. If python is not installed locally it will fail saying
it couldn't find pip.
State File Support
------------------
This functionality works in states as well. If you need to pip install colorama
with a state, for example, the following will work:
.. code-block:: yaml
install_colorama:
pip.installed:
- name: colorama
- cwd: 'C:\salt\bin\scripts'
- bin_env: 'C:\salt\bin\scripts\pip.exe'
- upgrade: True
Upgrading Salt using Pip
------------------------
You can now update salt using pip to any version from the 2014.7 branch
forward. Previous version require recompiling some of the dependencies which is
painful in windows.
To do this you just use pip with git to update to the version you want and then
restart the service. Here is a sample state file that upgrades salt to the head
of the 2015.5 branch:
.. code-block:: yaml
install_salt:
pip.installed:
- cwd: 'C:\salt\bin\scripts'
- bin_env: 'C:\salt\bin\scripts\pip.exe'
- editable: git+https://github.com/saltstack/salt@2015.5#egg=salt
- upgrade: True
restart_service:
service.running:
- name: salt-minion
- enable: True
- watch:
- pip: install_salt
.. note::
If you're having problems, you might try doubling the back slashes. For
example, cwd: 'C:\\salt\\bin\\scripts'. Sometimes python thinks the single
back slash is an escape character.
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import logging
import os
try:
import pkg_resources
except ImportError:
pkg_resources = None
import re
import shutil
import sys
import tempfile
# Import Salt libs
import salt.utils.data
import salt.utils.files
import salt.utils.json
import salt.utils.locales
import salt.utils.platform
import salt.utils.stringutils
import salt.utils.url
import salt.utils.versions
from salt.ext import six
from salt.exceptions import CommandExecutionError, CommandNotFoundError
# This needs to be named logger so we don't shadow it in pip.install
logger = logging.getLogger(__name__) # pylint: disable=C0103
# Don't shadow built-in's.
__func_alias__ = {
'list_': 'list'
}
VALID_PROTOS = ['http', 'https', 'ftp', 'file']
rex_pip_chain_read = re.compile(r'-r\s(.*)\n?', re.MULTILINE)
def __virtual__():
'''
There is no way to verify that pip is installed without inspecting the
entire filesystem. If it's not installed in a conventional location, the
user is required to provide the location of pip each time it is used.
'''
if pkg_resources is None:
ret = False, 'Package dependency "pkg_resource" is missing'
else:
ret = 'pip'
return ret
def _clear_context(bin_env=None):
'''
Remove the cached pip version
'''
contextkey = 'pip.version'
if bin_env is not None:
contextkey = '{0}.{1}'.format(contextkey, bin_env)
__context__.pop(contextkey, None)
def _get_pip_bin(bin_env):
'''
Locate the pip binary, either from `bin_env` as a virtualenv, as the
executable itself, or from searching conventional filesystem locations
'''
if not bin_env:
logger.debug('pip: Using pip from currently-running Python')
return [os.path.normpath(sys.executable), '-m', 'pip']
python_bin = 'python.exe' if salt.utils.platform.is_windows() else 'python'
def _search_paths(*basedirs):
ret = []
for path in basedirs:
ret.extend([
os.path.join(path, python_bin),
os.path.join(path, 'bin', python_bin),
os.path.join(path, 'Scripts', python_bin)
])
return ret
# try to get python bin from virtualenv (i.e. bin_env)
if os.path.isdir(bin_env):
for bin_path in _search_paths(bin_env):
if os.path.isfile(bin_path):
if os.access(bin_path, os.X_OK):
logger.debug('pip: Found python binary: %s', bin_path)
return [os.path.normpath(bin_path), '-m', 'pip']
else:
logger.debug(
'pip: Found python binary by name but it is not '
'executable: %s', bin_path
)
raise CommandNotFoundError(
'Could not find a pip binary in virtualenv {0}'.format(bin_env)
)
# bin_env is the python or pip binary
elif os.access(bin_env, os.X_OK):
if os.path.isfile(bin_env):
# If the python binary was passed, return it
if 'python' in os.path.basename(bin_env):
return [os.path.normpath(bin_env), '-m', 'pip']
# We have been passed a pip binary, use the pip binary.
return [os.path.normpath(bin_env)]
raise CommandExecutionError(
'Could not find a pip binary within {0}'.format(bin_env)
)
else:
raise CommandNotFoundError(
'Access denied to {0}, could not find a pip binary'.format(bin_env)
)
def _get_cached_requirements(requirements, saltenv):
'''
Get the location of a cached requirements file; caching if necessary.
'''
req_file, senv = salt.utils.url.parse(requirements)
if senv:
saltenv = senv
if req_file not in __salt__['cp.list_master'](saltenv):
# Requirements file does not exist in the given saltenv.
return False
cached_requirements = __salt__['cp.is_cached'](
requirements, saltenv
)
if not cached_requirements:
# It's not cached, let's cache it.
cached_requirements = __salt__['cp.cache_file'](
requirements, saltenv
)
# Check if the master version has changed.
if __salt__['cp.hash_file'](requirements, saltenv) != \
__salt__['cp.hash_file'](cached_requirements, saltenv):
cached_requirements = __salt__['cp.cache_file'](
requirements, saltenv
)
return cached_requirements
def _get_env_activate(bin_env):
'''
Return the path to the activate binary
'''
if not bin_env:
raise CommandNotFoundError('Could not find a `activate` binary')
if os.path.isdir(bin_env):
if salt.utils.platform.is_windows():
activate_bin = os.path.join(bin_env, 'Scripts', 'activate.bat')
else:
activate_bin = os.path.join(bin_env, 'bin', 'activate')
if os.path.isfile(activate_bin):
return activate_bin
raise CommandNotFoundError('Could not find a `activate` binary')
def _find_req(link):
logger.info('_find_req -- link = %s', link)
with salt.utils.files.fopen(link) as fh_link:
child_links = rex_pip_chain_read.findall(
salt.utils.stringutils.to_unicode(fh_link.read())
)
base_path = os.path.dirname(link)
child_links = [os.path.join(base_path, d) for d in child_links]
return child_links
def _resolve_requirements_chain(requirements):
'''
Return an array of requirements file paths that can be used to complete
the no_chown==False && user != None conundrum
'''
chain = []
if isinstance(requirements, six.string_types):
requirements = [requirements]
for req_file in requirements:
chain.append(req_file)
chain.extend(_resolve_requirements_chain(_find_req(req_file)))
return chain
def _process_requirements(requirements, cmd, cwd, saltenv, user):
'''
Process the requirements argument
'''
cleanup_requirements = []
if requirements is not None:
if isinstance(requirements, six.string_types):
requirements = [r.strip() for r in requirements.split(',')]
elif not isinstance(requirements, list):
raise TypeError('requirements must be a string or list')
treq = None
for requirement in requirements:
logger.debug('TREQ IS: %s', treq)
if requirement.startswith('salt://'):
cached_requirements = _get_cached_requirements(
requirement, saltenv
)
if not cached_requirements:
ret = {'result': False,
'comment': 'pip requirements file \'{0}\' not found'
.format(requirement)}
return None, ret
requirement = cached_requirements
if user:
# Need to make a temporary copy since the user will, most
# likely, not have the right permissions to read the file
if not treq:
treq = tempfile.mkdtemp()
__salt__['file.chown'](treq, user, None)
# In Windows, just being owner of a file isn't enough. You also
# need permissions
if salt.utils.platform.is_windows():
__utils__['dacl.set_permissions'](
obj_name=treq,
principal=user,
permissions='read_execute')
current_directory = None
if not current_directory:
current_directory = os.path.abspath(os.curdir)
logger.info('_process_requirements from directory, '
'%s -- requirement: %s', cwd, requirement)
if cwd is None:
r = requirement
c = cwd
requirement_abspath = os.path.abspath(requirement)
cwd = os.path.dirname(requirement_abspath)
requirement = os.path.basename(requirement)
logger.debug('\n\tcwd: %s -> %s\n\trequirement: %s -> %s\n',
c, cwd, r, requirement
)
os.chdir(cwd)
reqs = _resolve_requirements_chain(requirement)
os.chdir(current_directory)
logger.info('request files: %s', reqs)
for req_file in reqs:
if not os.path.isabs(req_file):
req_file = os.path.join(cwd, req_file)
logger.debug('TREQ N CWD: %s -- %s -- for %s', treq, cwd, req_file)
target_path = os.path.join(treq, os.path.basename(req_file))
logger.debug('S: %s', req_file)
logger.debug('T: %s', target_path)
target_base = os.path.dirname(target_path)
if not os.path.exists(target_base):
os.makedirs(target_base, mode=0o755)
__salt__['file.chown'](target_base, user, None)
if not os.path.exists(target_path):
logger.debug(
'Copying %s to %s', req_file, target_path
)
__salt__['file.copy'](req_file, target_path)
logger.debug(
'Changing ownership of requirements file \'%s\' to '
'user \'%s\'', target_path, user
)
__salt__['file.chown'](target_path, user, None)
req_args = os.path.join(treq, requirement) if treq else requirement
cmd.extend(['--requirement', req_args])
cleanup_requirements.append(treq)
logger.debug('CLEANUP_REQUIREMENTS: %s', cleanup_requirements)
return cleanup_requirements, None
def _format_env_vars(env_vars):
ret = {}
if env_vars:
if isinstance(env_vars, dict):
for key, val in six.iteritems(env_vars):
if not isinstance(key, six.string_types):
key = str(key) # future lint: disable=blacklisted-function
if not isinstance(val, six.string_types):
val = str(val) # future lint: disable=blacklisted-function
ret[key] = val
else:
raise CommandExecutionError(
'env_vars {0} is not a dictionary'.format(env_vars))
return ret
def install(pkgs=None, # pylint: disable=R0912,R0913,R0914
requirements=None,
bin_env=None,
use_wheel=False,
no_use_wheel=False,
log=None,
proxy=None,
timeout=None,
editable=None,
find_links=None,
index_url=None,
extra_index_url=None,
no_index=False,
mirrors=None,
build=None,
target=None,
download=None,
download_cache=None,
source=None,
upgrade=False,
force_reinstall=False,
ignore_installed=False,
exists_action=None,
no_deps=False,
no_install=False,
no_download=False,
global_options=None,
install_options=None,
user=None,
cwd=None,
pre_releases=False,
cert=None,
allow_all_external=False,
allow_external=None,
allow_unverified=None,
process_dependency_links=False,
saltenv='base',
env_vars=None,
use_vt=False,
trusted_host=None,
no_cache_dir=False,
cache_dir=None,
no_binary=None,
extra_args=None,
**kwargs):
'''
Install packages with pip
Install packages individually or from a pip requirements file. Install
packages globally or to a virtualenv.
pkgs
Comma separated list of packages to install
requirements
Path to requirements
bin_env
Path to pip (or to a virtualenv). This can be used to specify the path
to the pip to use when more than one Python release is installed (e.g.
``/usr/bin/pip-2.7`` or ``/usr/bin/pip-2.6``. If a directory path is
specified, it is assumed to be a virtualenv.
.. note::
For Windows, if the pip module is being used to upgrade the pip
package, bin_env should be the path to the virtualenv or to the
python binary that should be used. The pip command is unable to
upgrade itself in Windows.
use_wheel
Prefer wheel archives (requires pip>=1.4)
no_use_wheel
Force to not use wheel archives (requires pip>=1.4,<10.0.0)
no_binary
Force to not use binary packages (requires pip >= 7.0.0)
Accepts either :all: to disable all binary packages, :none: to empty the set,
or one or more package names with commas between them
log
Log file where a complete (maximum verbosity) record will be kept
proxy
Specify a proxy in the form ``user:passwd@proxy.server:port``. Note
that the ``user:password@`` is optional and required only if you are
behind an authenticated proxy. If you provide
``user@proxy.server:port`` then you will be prompted for a password.
timeout
Set the socket timeout (default 15 seconds)
editable
install something editable (e.g.
``git+https://github.com/worldcompany/djangoembed.git#egg=djangoembed``)
find_links
URL to search for packages
index_url
Base URL of Python Package Index
extra_index_url
Extra URLs of package indexes to use in addition to ``index_url``
no_index
Ignore package index
mirrors
Specific mirror URL(s) to query (automatically adds --use-mirrors)
.. warning::
This option has been deprecated and removed in pip version 7.0.0.
Please use ``index_url`` and/or ``extra_index_url`` instead.
build
Unpack packages into ``build`` dir
target
Install packages into ``target`` dir
download
Download packages into ``download`` instead of installing them
download_cache | cache_dir
Cache downloaded packages in ``download_cache`` or ``cache_dir`` dir
source
Check out ``editable`` packages into ``source`` dir
upgrade
Upgrade all packages to the newest available version
force_reinstall
When upgrading, reinstall all packages even if they are already
up-to-date.
ignore_installed
Ignore the installed packages (reinstalling instead)
exists_action
Default action when a path already exists: (s)witch, (i)gnore, (w)ipe,
(b)ackup
no_deps
Ignore package dependencies
no_install
Download and unpack all packages, but don't actually install them
no_download
Don't download any packages, just install the ones already downloaded
(completes an install run with ``--no-install``)
install_options
Extra arguments to be supplied to the setup.py install command (e.g.
like ``--install-option='--install-scripts=/usr/local/bin'``). Use
multiple --install-option options to pass multiple options to setup.py
install. If you are using an option with a directory path, be sure to
use absolute path.
global_options
Extra global options to be supplied to the setup.py call before the
install command.
user
The user under which to run pip
cwd
Directory from which to run pip
pre_releases
Include pre-releases in the available versions
cert
Provide a path to an alternate CA bundle
allow_all_external
Allow the installation of all externally hosted files
allow_external
Allow the installation of externally hosted files (comma separated
list)
allow_unverified
Allow the installation of insecure and unverifiable files (comma
separated list)
process_dependency_links
Enable the processing of dependency links
env_vars
Set environment variables that some builds will depend on. For example,
a Python C-module may have a Makefile that needs INCLUDE_PATH set to
pick up a header file while compiling. This must be in the form of a
dictionary or a mapping.
Example:
.. code-block:: bash
salt '*' pip.install django_app env_vars="{'CUSTOM_PATH': '/opt/django_app'}"
trusted_host
Mark this host as trusted, even though it does not have valid or any
HTTPS.
use_vt
Use VT terminal emulation (see output while installing)
no_cache_dir
Disable the cache.
extra_args
pip keyword and positional arguments not yet implemented in salt
.. code-block:: yaml
salt '*' pip.install pandas extra_args="[{'--latest-pip-kwarg':'param'}, '--latest-pip-arg']"
.. warning::
If unsupported options are passed here that are not supported in a
minion's version of pip, a `No such option error` will be thrown.
Will be translated into the following pip command:
.. code-block:: bash
pip install pandas --latest-pip-kwarg param --latest-pip-arg
CLI Example:
.. code-block:: bash
salt '*' pip.install <package name>,<package2 name>
salt '*' pip.install requirements=/path/to/requirements.txt
salt '*' pip.install <package name> bin_env=/path/to/virtualenv
salt '*' pip.install <package name> bin_env=/path/to/pip_bin
Complicated CLI example::
salt '*' pip.install markdown,django \
editable=git+https://github.com/worldcompany/djangoembed.git#egg=djangoembed upgrade=True no_deps=True
'''
cmd = _get_pip_bin(bin_env)
cmd.append('install')
cleanup_requirements, error = _process_requirements(
requirements=requirements,
cmd=cmd,
cwd=cwd,
saltenv=saltenv,
user=user
)
if error:
return error
cur_version = version(bin_env)
if use_wheel:
min_version = '1.4'
max_version = '9.0.3'
too_low = salt.utils.versions.compare(ver1=cur_version, oper='<', ver2=min_version)
too_high = salt.utils.versions.compare(ver1=cur_version, oper='>', ver2=max_version)
if too_low or too_high:
logger.error(
'The --use-wheel option is only supported in pip between %s and '
'%s. The version of pip detected is %s. This option '
'will be ignored.', min_version, max_version, cur_version
)
else:
cmd.append('--use-wheel')
if no_use_wheel:
min_version = '1.4'
max_version = '9.0.3'
too_low = salt.utils.versions.compare(ver1=cur_version, oper='<', ver2=min_version)
too_high = salt.utils.versions.compare(ver1=cur_version, oper='>', ver2=max_version)
if too_low or too_high:
logger.error(
'The --no-use-wheel option is only supported in pip between %s and '
'%s. The version of pip detected is %s. This option '
'will be ignored.', min_version, max_version, cur_version
)
else:
cmd.append('--no-use-wheel')
if no_binary:
min_version = '7.0.0'
too_low = salt.utils.versions.compare(ver1=cur_version, oper='<', ver2=min_version)
if too_low:
logger.error(
'The --no-binary option is only supported in pip %s and '
'newer. The version of pip detected is %s. This option '
'will be ignored.', min_version, cur_version
)
else:
if isinstance(no_binary, list):
no_binary = ','.join(no_binary)
cmd.extend(['--no-binary', no_binary])
if log:
if os.path.isdir(log):
raise IOError(
'\'{0}\' is a directory. Use --log path_to_file'.format(log))
elif not os.access(log, os.W_OK):
raise IOError('\'{0}\' is not writeable'.format(log))
cmd.extend(['--log', log])
if proxy:
cmd.extend(['--proxy', proxy])
if timeout:
try:
if isinstance(timeout, float):
# Catch floating point input, exception will be caught in
# exception class below.
raise ValueError('Timeout cannot be a float')
int(timeout)
except ValueError:
raise ValueError(
'\'{0}\' is not a valid timeout, must be an integer'
.format(timeout)
)
cmd.extend(['--timeout', timeout])
if find_links:
if isinstance(find_links, six.string_types):
find_links = [l.strip() for l in find_links.split(',')]
for link in find_links:
if not (salt.utils.url.validate(link, VALID_PROTOS) or os.path.exists(link)):
raise CommandExecutionError(
'\'{0}\' is not a valid URL or path'.format(link)
)
cmd.extend(['--find-links', link])
if no_index and (index_url or extra_index_url):
raise CommandExecutionError(
'\'no_index\' and (\'index_url\' or \'extra_index_url\') are '
'mutually exclusive.'
)
if index_url:
if not salt.utils.url.validate(index_url, VALID_PROTOS):
raise CommandExecutionError(
'\'{0}\' is not a valid URL'.format(index_url)
)
cmd.extend(['--index-url', index_url])
if extra_index_url:
if not salt.utils.url.validate(extra_index_url, VALID_PROTOS):
raise CommandExecutionError(
'\'{0}\' is not a valid URL'.format(extra_index_url)
)
cmd.extend(['--extra-index-url', extra_index_url])
if no_index:
cmd.append('--no-index')
if mirrors:
# https://github.com/pypa/pip/pull/2641/files#diff-3ef137fb9ffdd400f117a565cd94c188L216
if salt.utils.versions.compare(ver1=cur_version, oper='>=', ver2='7.0.0'):
raise CommandExecutionError(
'pip >= 7.0.0 does not support mirror argument:'
' use index_url and/or extra_index_url instead'
)
if isinstance(mirrors, six.string_types):
mirrors = [m.strip() for m in mirrors.split(',')]
cmd.append('--use-mirrors')
for mirror in mirrors:
if not mirror.startswith('http://'):
raise CommandExecutionError(
'\'{0}\' is not a valid URL'.format(mirror)
)
cmd.extend(['--mirrors', mirror])
if build:
cmd.extend(['--build', build])
if target:
cmd.extend(['--target', target])
if download:
cmd.extend(['--download', download])
if download_cache or cache_dir:
cmd.extend(['--cache-dir' if salt.utils.versions.compare(
ver1=cur_version, oper='>=', ver2='6.0'
) else '--download-cache', download_cache or cache_dir])
if source:
cmd.extend(['--source', source])
if upgrade:
cmd.append('--upgrade')
if force_reinstall:
cmd.append('--force-reinstall')
if ignore_installed:
cmd.append('--ignore-installed')
if exists_action:
if exists_action.lower() not in ('s', 'i', 'w', 'b'):
raise CommandExecutionError(
'The exists_action pip option only supports the values '
's, i, w, and b. \'{0}\' is not valid.'.format(exists_action)
)
cmd.extend(['--exists-action', exists_action])
if no_deps:
cmd.append('--no-deps')
if no_install:
cmd.append('--no-install')
if no_download:
cmd.append('--no-download')
if no_cache_dir:
cmd.append('--no-cache-dir')
if pre_releases:
# Check the locally installed pip version
pip_version = cur_version
# From pip v1.4 the --pre flag is available
if salt.utils.versions.compare(ver1=pip_version, oper='>=', ver2='1.4'):
cmd.append('--pre')
if cert:
cmd.extend(['--cert', cert])
if global_options:
if isinstance(global_options, six.string_types):
global_options = [go.strip() for go in global_options.split(',')]
for opt in global_options:
cmd.extend(['--global-option', opt])
if install_options:
if isinstance(install_options, six.string_types):
install_options = [io.strip() for io in install_options.split(',')]
for opt in install_options:
cmd.extend(['--install-option', opt])
if pkgs:
if not isinstance(pkgs, list):
try:
pkgs = [p.strip() for p in pkgs.split(',')]
except AttributeError:
pkgs = [p.strip() for p in six.text_type(pkgs).split(',')]
pkgs = salt.utils.data.stringify(salt.utils.data.decode_list(pkgs))
# It's possible we replaced version-range commas with semicolons so
# they would survive the previous line (in the pip.installed state).
# Put the commas back in while making sure the names are contained in
# quotes, this allows for proper version spec passing salt>=0.17.0
cmd.extend([p.replace(';', ',') for p in pkgs])
elif not any([requirements, editable]):
# Starting with pip 10.0.0, if no packages are specified in the
# command, it returns a retcode 1. So instead of running the command,
# just return the output without running pip.
return {'retcode': 0, 'stdout': 'No packages to install.'}
if editable:
egg_match = re.compile(r'(?:#|#.*?&)egg=([^&]*)')
if isinstance(editable, six.string_types):
editable = [e.strip() for e in editable.split(',')]
for entry in editable:
# Is the editable local?
if not (entry == '.' or entry.startswith(('file://', '/'))):
match = egg_match.search(entry)
if not match or not match.group(1):
# Missing #egg=theEggName
raise CommandExecutionError(
'You must specify an egg for this editable'
)
cmd.extend(['--editable', entry])
if allow_all_external:
cmd.append('--allow-all-external')
if allow_external:
if isinstance(allow_external, six.string_types):
allow_external = [p.strip() for p in allow_external.split(',')]
for pkg in allow_external:
cmd.extend(['--allow-external', pkg])
if allow_unverified:
if isinstance(allow_unverified, six.string_types):
allow_unverified = \
[p.strip() for p in allow_unverified.split(',')]
for pkg in allow_unverified:
cmd.extend(['--allow-unverified', pkg])
if process_dependency_links:
cmd.append('--process-dependency-links')
if trusted_host:
cmd.extend(['--trusted-host', trusted_host])
if extra_args:
# These are arguments from the latest version of pip that
# have not yet been implemented in salt
for arg in extra_args:
# It is a keyword argument
if isinstance(arg, dict):
# There will only ever be one item in this dictionary
key, val = arg.popitem()
# Don't allow any recursion into keyword arg definitions
# Don't allow multiple definitions of a keyword
if isinstance(val, (dict, list)):
raise TypeError("Too many levels in: {}".format(key))
# This is a a normal one-to-one keyword argument
cmd.extend([key, val])
# It is a positional argument, append it to the list
else:
cmd.append(arg)
cmd_kwargs = dict(saltenv=saltenv, use_vt=use_vt, runas=user)
if kwargs:
cmd_kwargs.update(kwargs)
if env_vars:
cmd_kwargs.setdefault('env', {}).update(_format_env_vars(env_vars))
try:
if cwd:
cmd_kwargs['cwd'] = cwd
if bin_env and os.path.isdir(bin_env):
cmd_kwargs.setdefault('env', {})['VIRTUAL_ENV'] = bin_env
logger.debug(
'TRY BLOCK: end of pip.install -- cmd: %s, cmd_kwargs: %s',
cmd, cmd_kwargs
)
return __salt__['cmd.run_all'](cmd, python_shell=False, **cmd_kwargs)
finally:
_clear_context(bin_env)
for tempdir in [cr for cr in cleanup_requirements if cr is not None]:
if os.path.isdir(tempdir):
shutil.rmtree(tempdir)
def uninstall(pkgs=None,
requirements=None,
bin_env=None,
log=None,
proxy=None,
timeout=None,
user=None,
cwd=None,
saltenv='base',
use_vt=False):
'''
Uninstall packages individually or from a pip requirements file
pkgs
comma separated list of packages to install
requirements
Path to requirements file
bin_env
Path to pip (or to a virtualenv). This can be used to specify the path
to the pip to use when more than one Python release is installed (e.g.
``/usr/bin/pip-2.7`` or ``/usr/bin/pip-2.6``. If a directory path is
specified, it is assumed to be a virtualenv.
log
Log file where a complete (maximum verbosity) record will be kept
proxy
Specify a proxy in the format ``user:passwd@proxy.server:port``. Note
that the ``user:password@`` is optional and required only if you are
behind an authenticated proxy. If you provide
``user@proxy.server:port`` then you will be prompted for a password.
timeout
Set the socket timeout (default 15 seconds)
user
The user under which to run pip
cwd
Directory from which to run pip
use_vt
Use VT terminal emulation (see output while installing)
CLI Example:
.. code-block:: bash
salt '*' pip.uninstall <package name>,<package2 name>
salt '*' pip.uninstall requirements=/path/to/requirements.txt
salt '*' pip.uninstall <package name> bin_env=/path/to/virtualenv
salt '*' pip.uninstall <package name> bin_env=/path/to/pip_bin
'''
cmd = _get_pip_bin(bin_env)
cmd.extend(['uninstall', '-y'])
cleanup_requirements, error = _process_requirements(
requirements=requirements, cmd=cmd, saltenv=saltenv, user=user,
cwd=cwd
)
if error:
return error
if log:
try:
# TODO make this check if writeable
os.path.exists(log)
except IOError:
raise IOError('\'{0}\' is not writeable'.format(log))
cmd.extend(['--log', log])
if proxy:
cmd.extend(['--proxy', proxy])
if timeout:
try:
if isinstance(timeout, float):
# Catch floating point input, exception will be caught in
# exception class below.
raise ValueError('Timeout cannot be a float')
int(timeout)
except ValueError:
raise ValueError(
'\'{0}\' is not a valid timeout, must be an integer'
.format(timeout)
)
cmd.extend(['--timeout', timeout])
if pkgs:
if isinstance(pkgs, six.string_types):
pkgs = [p.strip() for p in pkgs.split(',')]
if requirements:
for requirement in requirements:
with salt.utils.files.fopen(requirement) as rq_:
for req in rq_:
req = salt.utils.stringutils.to_unicode(req)
try:
req_pkg, _ = req.split('==')
if req_pkg in pkgs:
pkgs.remove(req_pkg)
except ValueError:
pass
cmd.extend(pkgs)
cmd_kwargs = dict(python_shell=False, runas=user,
cwd=cwd, saltenv=saltenv, use_vt=use_vt)
if bin_env and os.path.isdir(bin_env):
cmd_kwargs['env'] = {'VIRTUAL_ENV': bin_env}
try:
return __salt__['cmd.run_all'](cmd, **cmd_kwargs)
finally:
_clear_context(bin_env)
for requirement in cleanup_requirements:
if requirement:
try:
os.remove(requirement)
except OSError:
pass
def freeze(bin_env=None,
user=None,
cwd=None,
use_vt=False,
env_vars=None,
**kwargs):
'''
Return a list of installed packages either globally or in the specified
virtualenv
bin_env
Path to pip (or to a virtualenv). This can be used to specify the path
to the pip to use when more than one Python release is installed (e.g.
``/usr/bin/pip-2.7`` or ``/usr/bin/pip-2.6``. If a directory path is
specified, it is assumed to be a virtualenv.
user
The user under which to run pip
cwd
Directory from which to run pip
.. note::
If the version of pip available is older than 8.0.3, the list will not
include the packages ``pip``, ``wheel``, ``setuptools``, or
``distribute`` even if they are installed.
CLI Example:
.. code-block:: bash
salt '*' pip.freeze bin_env=/home/code/path/to/virtualenv
'''
cmd = _get_pip_bin(bin_env)
cmd.append('freeze')
# Include pip, setuptools, distribute, wheel
min_version = '8.0.3'
cur_version = version(bin_env)
if salt.utils.versions.compare(ver1=cur_version, oper='<', ver2=min_version):
logger.warning(
'The version of pip installed is %s, which is older than %s. '
'The packages pip, wheel, setuptools, and distribute will not be '
'included in the output of pip.freeze', cur_version, min_version
)
else:
cmd.append('--all')
cmd_kwargs = dict(runas=user, cwd=cwd, use_vt=use_vt, python_shell=False)
if kwargs:
cmd_kwargs.update(**kwargs)
if bin_env and os.path.isdir(bin_env):
cmd_kwargs['env'] = {'VIRTUAL_ENV': bin_env}
if env_vars:
cmd_kwargs.setdefault('env', {}).update(_format_env_vars(env_vars))
result = __salt__['cmd.run_all'](cmd, **cmd_kwargs)
if result['retcode']:
raise CommandExecutionError(result['stderr'], info=result)
return result['stdout'].splitlines()
def list_(prefix=None,
bin_env=None,
user=None,
cwd=None,
env_vars=None,
**kwargs):
'''
Filter list of installed apps from ``freeze`` and check to see if
``prefix`` exists in the list of packages installed.
.. note::
If the version of pip available is older than 8.0.3, the packages
``wheel``, ``setuptools``, and ``distribute`` will not be reported by
this function even if they are installed. Unlike :py:func:`pip.freeze
<salt.modules.pip.freeze>`, this function always reports the version of
pip which is installed.
CLI Example:
.. code-block:: bash
salt '*' pip.list salt
'''
packages = {}
if prefix is None or 'pip'.startswith(prefix):
packages['pip'] = version(bin_env)
for line in freeze(bin_env=bin_env,
user=user,
cwd=cwd,
env_vars=env_vars,
**kwargs):
if line.startswith('-f') or line.startswith('#'):
# ignore -f line as it contains --find-links directory
# ignore comment lines
continue
elif line.startswith('-e hg+not trust'):
# ignore hg + not trust problem
continue
elif line.startswith('-e'):
line = line.split('-e ')[1]
if '#egg=' in line:
version_, name = line.split('#egg=')
else:
if len(line.split('===')) >= 2:
name = line.split('===')[0]
version_ = line.split('===')[1]
elif len(line.split('==')) >= 2:
name = line.split('==')[0]
version_ = line.split('==')[1]
elif len(line.split('===')) >= 2:
name = line.split('===')[0]
version_ = line.split('===')[1]
elif len(line.split('==')) >= 2:
name = line.split('==')[0]
version_ = line.split('==')[1]
else:
logger.error('Can\'t parse line \'%s\'', line)
continue
if prefix:
if name.lower().startswith(prefix.lower()):
packages[name] = version_
else:
packages[name] = version_
return packages
def version(bin_env=None):
'''
.. versionadded:: 0.17.0
Returns the version of pip. Use ``bin_env`` to specify the path to a
virtualenv and get the version of pip in that virtualenv.
If unable to detect the pip version, returns ``None``.
CLI Example:
.. code-block:: bash
salt '*' pip.version
'''
contextkey = 'pip.version'
if bin_env is not None:
contextkey = '{0}.{1}'.format(contextkey, bin_env)
if contextkey in __context__:
return __context__[contextkey]
cmd = _get_pip_bin(bin_env)[:]
cmd.append('--version')
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
if ret['retcode']:
raise CommandNotFoundError('Could not find a `pip` binary')
try:
pip_version = re.match(r'^pip (\S+)', ret['stdout']).group(1)
except AttributeError:
pip_version = None
__context__[contextkey] = pip_version
return pip_version
def list_upgrades(bin_env=None,
user=None,
cwd=None):
'''
Check whether or not an upgrade is available for all packages
CLI Example:
.. code-block:: bash
salt '*' pip.list_upgrades
'''
cmd = _get_pip_bin(bin_env)
cmd.extend(['list', '--outdated'])
pip_version = version(bin_env)
# Pip started supporting the ability to output json starting with 9.0.0
min_version = '9.0'
if salt.utils.versions.compare(ver1=pip_version,
oper='>=',
ver2=min_version):
cmd.append('--format=json')
cmd_kwargs = dict(cwd=cwd, runas=user)
if bin_env and os.path.isdir(bin_env):
cmd_kwargs['env'] = {'VIRTUAL_ENV': bin_env}
result = __salt__['cmd.run_all'](cmd, **cmd_kwargs)
if result['retcode']:
raise CommandExecutionError(result['stderr'], info=result)
packages = {}
# Pip started supporting the ability to output json starting with 9.0.0
# Older versions will have to parse stdout
if salt.utils.versions.compare(ver1=pip_version, oper='<', ver2='9.0.0'):
# Pip versions < 8.0.0 had a different output format
# Sample data:
# pip (Current: 7.1.2 Latest: 10.0.1 [wheel])
# psutil (Current: 5.2.2 Latest: 5.4.5 [wheel])
# pyasn1 (Current: 0.2.3 Latest: 0.4.2 [wheel])
# pycparser (Current: 2.17 Latest: 2.18 [sdist])
if salt.utils.versions.compare(ver1=pip_version, oper='<', ver2='8.0.0'):
logger.debug('pip module: Old output format')
pat = re.compile(r'(\S*)\s+\(.*Latest:\s+(.*)\)')
# New output format for version 8.0.0+
# Sample data:
# pip (8.0.0) - Latest: 10.0.1 [wheel]
# psutil (5.2.2) - Latest: 5.4.5 [wheel]
# pyasn1 (0.2.3) - Latest: 0.4.2 [wheel]
# pycparser (2.17) - Latest: 2.18 [sdist]
else:
logger.debug('pip module: New output format')
pat = re.compile(r'(\S*)\s+\(.*\)\s+-\s+Latest:\s+(.*)')
for line in result['stdout'].splitlines():
match = pat.search(line)
if match:
name, version_ = match.groups()
else:
logger.error('Can\'t parse line \'%s\'', line)
continue
packages[name] = version_
else:
logger.debug('pip module: JSON output format')
try:
pkgs = salt.utils.json.loads(result['stdout'], strict=False)
except ValueError:
raise CommandExecutionError('Invalid JSON', info=result)
for pkg in pkgs:
packages[pkg['name']] = '{0} [{1}]'.format(pkg['latest_version'],
pkg['latest_filetype'])
return packages
def is_installed(pkgname=None,
bin_env=None,
user=None,
cwd=None):
'''
.. versionadded:: 2018.3.0
Filter list of installed apps from ``freeze`` and return True or False if
``pkgname`` exists in the list of packages installed.
.. note::
If the version of pip available is older than 8.0.3, the packages
wheel, setuptools, and distribute will not be reported by this function
even if they are installed. Unlike :py:func:`pip.freeze
<salt.modules.pip.freeze>`, this function always reports the version of
pip which is installed.
CLI Example:
.. code-block:: bash
salt '*' pip.is_installed salt
'''
for line in freeze(bin_env=bin_env, user=user, cwd=cwd):
if line.startswith('-f') or line.startswith('#'):
# ignore -f line as it contains --find-links directory
# ignore comment lines
continue
elif line.startswith('-e hg+not trust'):
# ignore hg + not trust problem
continue
elif line.startswith('-e'):
line = line.split('-e ')[1]
version_, name = line.split('#egg=')
elif len(line.split('===')) >= 2:
name = line.split('===')[0]
version_ = line.split('===')[1]
elif len(line.split('==')) >= 2:
name = line.split('==')[0]
version_ = line.split('==')[1]
else:
logger.error('Can\'t parse line \'%s\'', line)
continue
if pkgname:
if pkgname == name.lower():
return True
return False
def upgrade_available(pkg,
bin_env=None,
user=None,
cwd=None):
'''
.. versionadded:: 2015.5.0
Check whether or not an upgrade is available for a given package
CLI Example:
.. code-block:: bash
salt '*' pip.upgrade_available <package name>
'''
return pkg in list_upgrades(bin_env=bin_env, user=user, cwd=cwd)
def upgrade(bin_env=None,
user=None,
cwd=None,
use_vt=False):
'''
.. versionadded:: 2015.5.0
Upgrades outdated pip packages.
.. note::
On Windows you can't update salt from pip using salt, so salt will be
skipped
Returns a dict containing the changes.
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
CLI Example:
.. code-block:: bash
salt '*' pip.upgrade
'''
ret = {'changes': {},
'result': True,
'comment': '',
}
cmd = _get_pip_bin(bin_env)
cmd.extend(['install', '-U'])
old = list_(bin_env=bin_env, user=user, cwd=cwd)
cmd_kwargs = dict(cwd=cwd, use_vt=use_vt)
if bin_env and os.path.isdir(bin_env):
cmd_kwargs['env'] = {'VIRTUAL_ENV': bin_env}
errors = False
for pkg in list_upgrades(bin_env=bin_env, user=user, cwd=cwd):
if pkg == 'salt':
if salt.utils.platform.is_windows():
continue
result = __salt__['cmd.run_all'](cmd + [pkg], **cmd_kwargs)
if result['retcode'] != 0:
errors = True
if 'stderr' in result:
ret['comment'] += result['stderr']
if errors:
ret['result'] = False
_clear_context(bin_env)
new = list_(bin_env=bin_env, user=user, cwd=cwd)
ret['changes'] = salt.utils.data.compare_dicts(old, new)
return ret
|
saltstack/salt
|
salt/netapi/rest_cherrypy/__init__.py
|
verify_certs
|
python
|
def verify_certs(*args):
'''
Sanity checking for the specified SSL certificates
'''
msg = ("Could not find a certificate: {0}\n"
"If you want to quickly generate a self-signed certificate, "
"use the tls.create_self_signed_cert function in Salt")
for arg in args:
if not os.path.exists(arg):
raise Exception(msg.format(arg))
|
Sanity checking for the specified SSL certificates
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_cherrypy/__init__.py#L62-L72
| null |
# encoding: utf-8
'''
A script to start the CherryPy WSGI server
This is run by ``salt-api`` and started in a multiprocess.
'''
from __future__ import absolute_import, print_function, unicode_literals
# pylint: disable=C0103
# Import Python libs
import logging
import os
# Import CherryPy without traceback so we can provide an intelligent log
# message in the __virtual__ function
try:
import cherrypy
cpy_error = None
except ImportError as exc:
cpy_error = exc
__virtualname__ = os.path.abspath(__file__).rsplit(os.sep)[-2] or 'rest_cherrypy'
logger = logging.getLogger(__virtualname__)
cpy_min = '3.2.2'
def __virtual__():
short_name = __name__.rsplit('.')[-1]
mod_opts = __opts__.get(short_name, {})
if mod_opts:
# User has a rest_cherrypy section in config; assume the user wants to
# run the module and increase logging severity to be helpful
# Everything looks good; return the module name
if not cpy_error and 'port' in mod_opts:
return __virtualname__
# CherryPy wasn't imported; explain why
if cpy_error:
from salt.utils.versions import LooseVersion as V
if 'cherrypy' in globals() and V(cherrypy.__version__) < V(cpy_min):
error_msg = ("Required version of CherryPy is {0} or "
"greater.".format(cpy_min))
else:
error_msg = cpy_error
logger.error("Not loading '%s'. Error loading CherryPy: %s",
__name__, error_msg)
# Missing port config
if 'port' not in mod_opts:
logger.error("Not loading '%s'. 'port' not specified in config",
__name__)
return False
def start():
'''
Start the server loop
'''
from . import app
root, apiopts, conf = app.get_app(__opts__)
if not apiopts.get('disable_ssl', False):
if 'ssl_crt' not in apiopts or 'ssl_key' not in apiopts:
logger.error("Not starting '%s'. Options 'ssl_crt' and "
"'ssl_key' are required if SSL is not disabled.",
__name__)
return None
verify_certs(apiopts['ssl_crt'], apiopts['ssl_key'])
cherrypy.server.ssl_module = 'builtin'
cherrypy.server.ssl_certificate = apiopts['ssl_crt']
cherrypy.server.ssl_private_key = apiopts['ssl_key']
if 'ssl_chain' in apiopts.keys():
cherrypy.server.ssl_certificate_chain = apiopts['ssl_chain']
cherrypy.quickstart(root, apiopts.get('root_prefix', '/'), conf)
|
saltstack/salt
|
salt/netapi/rest_cherrypy/__init__.py
|
start
|
python
|
def start():
'''
Start the server loop
'''
from . import app
root, apiopts, conf = app.get_app(__opts__)
if not apiopts.get('disable_ssl', False):
if 'ssl_crt' not in apiopts or 'ssl_key' not in apiopts:
logger.error("Not starting '%s'. Options 'ssl_crt' and "
"'ssl_key' are required if SSL is not disabled.",
__name__)
return None
verify_certs(apiopts['ssl_crt'], apiopts['ssl_key'])
cherrypy.server.ssl_module = 'builtin'
cherrypy.server.ssl_certificate = apiopts['ssl_crt']
cherrypy.server.ssl_private_key = apiopts['ssl_key']
if 'ssl_chain' in apiopts.keys():
cherrypy.server.ssl_certificate_chain = apiopts['ssl_chain']
cherrypy.quickstart(root, apiopts.get('root_prefix', '/'), conf)
|
Start the server loop
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_cherrypy/__init__.py#L75-L98
| null |
# encoding: utf-8
'''
A script to start the CherryPy WSGI server
This is run by ``salt-api`` and started in a multiprocess.
'''
from __future__ import absolute_import, print_function, unicode_literals
# pylint: disable=C0103
# Import Python libs
import logging
import os
# Import CherryPy without traceback so we can provide an intelligent log
# message in the __virtual__ function
try:
import cherrypy
cpy_error = None
except ImportError as exc:
cpy_error = exc
__virtualname__ = os.path.abspath(__file__).rsplit(os.sep)[-2] or 'rest_cherrypy'
logger = logging.getLogger(__virtualname__)
cpy_min = '3.2.2'
def __virtual__():
short_name = __name__.rsplit('.')[-1]
mod_opts = __opts__.get(short_name, {})
if mod_opts:
# User has a rest_cherrypy section in config; assume the user wants to
# run the module and increase logging severity to be helpful
# Everything looks good; return the module name
if not cpy_error and 'port' in mod_opts:
return __virtualname__
# CherryPy wasn't imported; explain why
if cpy_error:
from salt.utils.versions import LooseVersion as V
if 'cherrypy' in globals() and V(cherrypy.__version__) < V(cpy_min):
error_msg = ("Required version of CherryPy is {0} or "
"greater.".format(cpy_min))
else:
error_msg = cpy_error
logger.error("Not loading '%s'. Error loading CherryPy: %s",
__name__, error_msg)
# Missing port config
if 'port' not in mod_opts:
logger.error("Not loading '%s'. 'port' not specified in config",
__name__)
return False
def verify_certs(*args):
'''
Sanity checking for the specified SSL certificates
'''
msg = ("Could not find a certificate: {0}\n"
"If you want to quickly generate a self-signed certificate, "
"use the tls.create_self_signed_cert function in Salt")
for arg in args:
if not os.path.exists(arg):
raise Exception(msg.format(arg))
|
saltstack/salt
|
salt/utils/pkg/rpm.py
|
get_osarch
|
python
|
def get_osarch():
'''
Get the os architecture using rpm --eval
'''
if salt.utils.path.which('rpm'):
ret = subprocess.Popen(
'rpm --eval "%{_host_cpu}"',
shell=True,
close_fds=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE).communicate()[0]
else:
ret = ''.join([x for x in platform.uname()[-2:] if x][-1:])
return salt.utils.stringutils.to_str(ret).strip() or 'unknown'
|
Get the os architecture using rpm --eval
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/pkg/rpm.py#L46-L60
|
[
"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 -*-
'''
Common functions for working with RPM packages
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import collections
import datetime
import logging
import subprocess
import platform
import salt.utils.stringutils
import salt.utils.path
# Import 3rd-party libs
from salt.ext import six
log = logging.getLogger(__name__)
# These arches compiled from the rpmUtils.arch python module source
ARCHES_64 = ('x86_64', 'athlon', 'amd64', 'ia32e', 'ia64', 'geode')
ARCHES_32 = ('i386', 'i486', 'i586', 'i686')
ARCHES_PPC = ('ppc', 'ppc64', 'ppc64iseries', 'ppc64pseries')
ARCHES_S390 = ('s390', 's390x')
ARCHES_SPARC = (
'sparc', 'sparcv8', 'sparcv9', 'sparcv9v', 'sparc64', 'sparc64v'
)
ARCHES_ALPHA = (
'alpha', 'alphaev4', 'alphaev45', 'alphaev5', 'alphaev56',
'alphapca56', 'alphaev6', 'alphaev67', 'alphaev68', 'alphaev7'
)
ARCHES_ARM = ('armv5tel', 'armv5tejl', 'armv6l', 'armv7l')
ARCHES_SH = ('sh3', 'sh4', 'sh4a')
ARCHES = ARCHES_64 + ARCHES_32 + ARCHES_PPC + ARCHES_S390 + \
ARCHES_ALPHA + ARCHES_ARM + ARCHES_SH
# EPOCHNUM can't be used until RHEL5 is EOL as it is not present
QUERYFORMAT = '%{NAME}_|-%{EPOCH}_|-%{VERSION}_|-%{RELEASE}_|-%{ARCH}_|-%{REPOID}_|-%{INSTALLTIME}'
# on some archs, the rpm _host_cpu macro doesn't match the pkg name arch
ARCHMAP = {'powerpc64le': 'ppc64le'}
def check_32(arch, osarch=None):
'''
Returns True if both the OS arch and the passed arch are 32-bit
'''
if osarch is None:
osarch = get_osarch()
return all(x in ARCHES_32 for x in (osarch, arch))
def pkginfo(name, version, arch, repoid, install_date=None, install_date_time_t=None):
'''
Build and return a pkginfo namedtuple
'''
pkginfo_tuple = collections.namedtuple(
'PkgInfo',
('name', 'version', 'arch', 'repoid', 'install_date',
'install_date_time_t')
)
return pkginfo_tuple(name, version, arch, repoid, install_date,
install_date_time_t)
def resolve_name(name, arch, osarch=None):
'''
Resolve the package name and arch into a unique name referred to by salt.
For example, on a 64-bit OS, a 32-bit package will be pkgname.i386.
'''
if osarch is None:
osarch = get_osarch()
if not check_32(arch, osarch) and arch not in (ARCHMAP.get(osarch, osarch), 'noarch'):
name += '.{0}'.format(arch)
return name
def parse_pkginfo(line, osarch=None):
'''
A small helper to parse an rpm/repoquery command's output. Returns a
pkginfo namedtuple.
'''
try:
name, epoch, version, release, arch, repoid, install_time = line.split('_|-')
# Handle unpack errors (should never happen with the queryformat we are
# using, but can't hurt to be careful).
except ValueError:
return None
name = resolve_name(name, arch, osarch)
if release:
version += '-{0}'.format(release)
if epoch not in ('(none)', '0'):
version = ':'.join((epoch, version))
if install_time not in ('(none)', '0'):
install_date = datetime.datetime.utcfromtimestamp(int(install_time)).isoformat() + "Z"
install_date_time_t = int(install_time)
else:
install_date = None
install_date_time_t = None
return pkginfo(name, version, arch, repoid, install_date, install_date_time_t)
def combine_comments(comments):
'''
Given a list of comments, strings, a single comment or a single string,
return a single string of text containing all of the comments, prepending
the '#' and joining with newlines as necessary.
'''
if not isinstance(comments, list):
comments = [comments]
ret = []
for comment in comments:
if not isinstance(comment, six.string_types):
comment = str(comment)
# Normalize for any spaces (or lack thereof) after the #
ret.append('# {0}\n'.format(comment.lstrip('#').lstrip()))
return ''.join(ret)
def version_to_evr(verstring):
'''
Split the package version string into epoch, version and release.
Return this as tuple.
The epoch is always not empty. The version and the release can be an empty
string if such a component could not be found in the version string.
"2:1.0-1.2" => ('2', '1.0', '1.2)
"1.0" => ('0', '1.0', '')
"" => ('0', '', '')
'''
if verstring in [None, '']:
return '0', '', ''
idx_e = verstring.find(':')
if idx_e != -1:
try:
epoch = six.text_type(int(verstring[:idx_e]))
except ValueError:
# look, garbage in the epoch field, how fun, kill it
epoch = '0' # this is our fallback, deal
else:
epoch = '0'
idx_r = verstring.find('-')
if idx_r != -1:
version = verstring[idx_e + 1:idx_r]
release = verstring[idx_r + 1:]
else:
version = verstring[idx_e + 1:]
release = ''
return epoch, version, release
|
saltstack/salt
|
salt/utils/pkg/rpm.py
|
check_32
|
python
|
def check_32(arch, osarch=None):
'''
Returns True if both the OS arch and the passed arch are 32-bit
'''
if osarch is None:
osarch = get_osarch()
return all(x in ARCHES_32 for x in (osarch, arch))
|
Returns True if both the OS arch and the passed arch are 32-bit
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/pkg/rpm.py#L63-L69
|
[
"def get_osarch():\n '''\n Get the os architecture using rpm --eval\n '''\n if salt.utils.path.which('rpm'):\n ret = subprocess.Popen(\n 'rpm --eval \"%{_host_cpu}\"',\n shell=True,\n close_fds=True,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE).communicate()[0]\n else:\n ret = ''.join([x for x in platform.uname()[-2:] if x][-1:])\n\n return salt.utils.stringutils.to_str(ret).strip() or 'unknown'\n"
] |
# -*- coding: utf-8 -*-
'''
Common functions for working with RPM packages
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import collections
import datetime
import logging
import subprocess
import platform
import salt.utils.stringutils
import salt.utils.path
# Import 3rd-party libs
from salt.ext import six
log = logging.getLogger(__name__)
# These arches compiled from the rpmUtils.arch python module source
ARCHES_64 = ('x86_64', 'athlon', 'amd64', 'ia32e', 'ia64', 'geode')
ARCHES_32 = ('i386', 'i486', 'i586', 'i686')
ARCHES_PPC = ('ppc', 'ppc64', 'ppc64iseries', 'ppc64pseries')
ARCHES_S390 = ('s390', 's390x')
ARCHES_SPARC = (
'sparc', 'sparcv8', 'sparcv9', 'sparcv9v', 'sparc64', 'sparc64v'
)
ARCHES_ALPHA = (
'alpha', 'alphaev4', 'alphaev45', 'alphaev5', 'alphaev56',
'alphapca56', 'alphaev6', 'alphaev67', 'alphaev68', 'alphaev7'
)
ARCHES_ARM = ('armv5tel', 'armv5tejl', 'armv6l', 'armv7l')
ARCHES_SH = ('sh3', 'sh4', 'sh4a')
ARCHES = ARCHES_64 + ARCHES_32 + ARCHES_PPC + ARCHES_S390 + \
ARCHES_ALPHA + ARCHES_ARM + ARCHES_SH
# EPOCHNUM can't be used until RHEL5 is EOL as it is not present
QUERYFORMAT = '%{NAME}_|-%{EPOCH}_|-%{VERSION}_|-%{RELEASE}_|-%{ARCH}_|-%{REPOID}_|-%{INSTALLTIME}'
# on some archs, the rpm _host_cpu macro doesn't match the pkg name arch
ARCHMAP = {'powerpc64le': 'ppc64le'}
def get_osarch():
'''
Get the os architecture using rpm --eval
'''
if salt.utils.path.which('rpm'):
ret = subprocess.Popen(
'rpm --eval "%{_host_cpu}"',
shell=True,
close_fds=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE).communicate()[0]
else:
ret = ''.join([x for x in platform.uname()[-2:] if x][-1:])
return salt.utils.stringutils.to_str(ret).strip() or 'unknown'
def pkginfo(name, version, arch, repoid, install_date=None, install_date_time_t=None):
'''
Build and return a pkginfo namedtuple
'''
pkginfo_tuple = collections.namedtuple(
'PkgInfo',
('name', 'version', 'arch', 'repoid', 'install_date',
'install_date_time_t')
)
return pkginfo_tuple(name, version, arch, repoid, install_date,
install_date_time_t)
def resolve_name(name, arch, osarch=None):
'''
Resolve the package name and arch into a unique name referred to by salt.
For example, on a 64-bit OS, a 32-bit package will be pkgname.i386.
'''
if osarch is None:
osarch = get_osarch()
if not check_32(arch, osarch) and arch not in (ARCHMAP.get(osarch, osarch), 'noarch'):
name += '.{0}'.format(arch)
return name
def parse_pkginfo(line, osarch=None):
'''
A small helper to parse an rpm/repoquery command's output. Returns a
pkginfo namedtuple.
'''
try:
name, epoch, version, release, arch, repoid, install_time = line.split('_|-')
# Handle unpack errors (should never happen with the queryformat we are
# using, but can't hurt to be careful).
except ValueError:
return None
name = resolve_name(name, arch, osarch)
if release:
version += '-{0}'.format(release)
if epoch not in ('(none)', '0'):
version = ':'.join((epoch, version))
if install_time not in ('(none)', '0'):
install_date = datetime.datetime.utcfromtimestamp(int(install_time)).isoformat() + "Z"
install_date_time_t = int(install_time)
else:
install_date = None
install_date_time_t = None
return pkginfo(name, version, arch, repoid, install_date, install_date_time_t)
def combine_comments(comments):
'''
Given a list of comments, strings, a single comment or a single string,
return a single string of text containing all of the comments, prepending
the '#' and joining with newlines as necessary.
'''
if not isinstance(comments, list):
comments = [comments]
ret = []
for comment in comments:
if not isinstance(comment, six.string_types):
comment = str(comment)
# Normalize for any spaces (or lack thereof) after the #
ret.append('# {0}\n'.format(comment.lstrip('#').lstrip()))
return ''.join(ret)
def version_to_evr(verstring):
'''
Split the package version string into epoch, version and release.
Return this as tuple.
The epoch is always not empty. The version and the release can be an empty
string if such a component could not be found in the version string.
"2:1.0-1.2" => ('2', '1.0', '1.2)
"1.0" => ('0', '1.0', '')
"" => ('0', '', '')
'''
if verstring in [None, '']:
return '0', '', ''
idx_e = verstring.find(':')
if idx_e != -1:
try:
epoch = six.text_type(int(verstring[:idx_e]))
except ValueError:
# look, garbage in the epoch field, how fun, kill it
epoch = '0' # this is our fallback, deal
else:
epoch = '0'
idx_r = verstring.find('-')
if idx_r != -1:
version = verstring[idx_e + 1:idx_r]
release = verstring[idx_r + 1:]
else:
version = verstring[idx_e + 1:]
release = ''
return epoch, version, release
|
saltstack/salt
|
salt/utils/pkg/rpm.py
|
pkginfo
|
python
|
def pkginfo(name, version, arch, repoid, install_date=None, install_date_time_t=None):
'''
Build and return a pkginfo namedtuple
'''
pkginfo_tuple = collections.namedtuple(
'PkgInfo',
('name', 'version', 'arch', 'repoid', 'install_date',
'install_date_time_t')
)
return pkginfo_tuple(name, version, arch, repoid, install_date,
install_date_time_t)
|
Build and return a pkginfo namedtuple
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/pkg/rpm.py#L72-L82
| null |
# -*- coding: utf-8 -*-
'''
Common functions for working with RPM packages
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import collections
import datetime
import logging
import subprocess
import platform
import salt.utils.stringutils
import salt.utils.path
# Import 3rd-party libs
from salt.ext import six
log = logging.getLogger(__name__)
# These arches compiled from the rpmUtils.arch python module source
ARCHES_64 = ('x86_64', 'athlon', 'amd64', 'ia32e', 'ia64', 'geode')
ARCHES_32 = ('i386', 'i486', 'i586', 'i686')
ARCHES_PPC = ('ppc', 'ppc64', 'ppc64iseries', 'ppc64pseries')
ARCHES_S390 = ('s390', 's390x')
ARCHES_SPARC = (
'sparc', 'sparcv8', 'sparcv9', 'sparcv9v', 'sparc64', 'sparc64v'
)
ARCHES_ALPHA = (
'alpha', 'alphaev4', 'alphaev45', 'alphaev5', 'alphaev56',
'alphapca56', 'alphaev6', 'alphaev67', 'alphaev68', 'alphaev7'
)
ARCHES_ARM = ('armv5tel', 'armv5tejl', 'armv6l', 'armv7l')
ARCHES_SH = ('sh3', 'sh4', 'sh4a')
ARCHES = ARCHES_64 + ARCHES_32 + ARCHES_PPC + ARCHES_S390 + \
ARCHES_ALPHA + ARCHES_ARM + ARCHES_SH
# EPOCHNUM can't be used until RHEL5 is EOL as it is not present
QUERYFORMAT = '%{NAME}_|-%{EPOCH}_|-%{VERSION}_|-%{RELEASE}_|-%{ARCH}_|-%{REPOID}_|-%{INSTALLTIME}'
# on some archs, the rpm _host_cpu macro doesn't match the pkg name arch
ARCHMAP = {'powerpc64le': 'ppc64le'}
def get_osarch():
'''
Get the os architecture using rpm --eval
'''
if salt.utils.path.which('rpm'):
ret = subprocess.Popen(
'rpm --eval "%{_host_cpu}"',
shell=True,
close_fds=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE).communicate()[0]
else:
ret = ''.join([x for x in platform.uname()[-2:] if x][-1:])
return salt.utils.stringutils.to_str(ret).strip() or 'unknown'
def check_32(arch, osarch=None):
'''
Returns True if both the OS arch and the passed arch are 32-bit
'''
if osarch is None:
osarch = get_osarch()
return all(x in ARCHES_32 for x in (osarch, arch))
def resolve_name(name, arch, osarch=None):
'''
Resolve the package name and arch into a unique name referred to by salt.
For example, on a 64-bit OS, a 32-bit package will be pkgname.i386.
'''
if osarch is None:
osarch = get_osarch()
if not check_32(arch, osarch) and arch not in (ARCHMAP.get(osarch, osarch), 'noarch'):
name += '.{0}'.format(arch)
return name
def parse_pkginfo(line, osarch=None):
'''
A small helper to parse an rpm/repoquery command's output. Returns a
pkginfo namedtuple.
'''
try:
name, epoch, version, release, arch, repoid, install_time = line.split('_|-')
# Handle unpack errors (should never happen with the queryformat we are
# using, but can't hurt to be careful).
except ValueError:
return None
name = resolve_name(name, arch, osarch)
if release:
version += '-{0}'.format(release)
if epoch not in ('(none)', '0'):
version = ':'.join((epoch, version))
if install_time not in ('(none)', '0'):
install_date = datetime.datetime.utcfromtimestamp(int(install_time)).isoformat() + "Z"
install_date_time_t = int(install_time)
else:
install_date = None
install_date_time_t = None
return pkginfo(name, version, arch, repoid, install_date, install_date_time_t)
def combine_comments(comments):
'''
Given a list of comments, strings, a single comment or a single string,
return a single string of text containing all of the comments, prepending
the '#' and joining with newlines as necessary.
'''
if not isinstance(comments, list):
comments = [comments]
ret = []
for comment in comments:
if not isinstance(comment, six.string_types):
comment = str(comment)
# Normalize for any spaces (or lack thereof) after the #
ret.append('# {0}\n'.format(comment.lstrip('#').lstrip()))
return ''.join(ret)
def version_to_evr(verstring):
'''
Split the package version string into epoch, version and release.
Return this as tuple.
The epoch is always not empty. The version and the release can be an empty
string if such a component could not be found in the version string.
"2:1.0-1.2" => ('2', '1.0', '1.2)
"1.0" => ('0', '1.0', '')
"" => ('0', '', '')
'''
if verstring in [None, '']:
return '0', '', ''
idx_e = verstring.find(':')
if idx_e != -1:
try:
epoch = six.text_type(int(verstring[:idx_e]))
except ValueError:
# look, garbage in the epoch field, how fun, kill it
epoch = '0' # this is our fallback, deal
else:
epoch = '0'
idx_r = verstring.find('-')
if idx_r != -1:
version = verstring[idx_e + 1:idx_r]
release = verstring[idx_r + 1:]
else:
version = verstring[idx_e + 1:]
release = ''
return epoch, version, release
|
saltstack/salt
|
salt/utils/pkg/rpm.py
|
resolve_name
|
python
|
def resolve_name(name, arch, osarch=None):
'''
Resolve the package name and arch into a unique name referred to by salt.
For example, on a 64-bit OS, a 32-bit package will be pkgname.i386.
'''
if osarch is None:
osarch = get_osarch()
if not check_32(arch, osarch) and arch not in (ARCHMAP.get(osarch, osarch), 'noarch'):
name += '.{0}'.format(arch)
return name
|
Resolve the package name and arch into a unique name referred to by salt.
For example, on a 64-bit OS, a 32-bit package will be pkgname.i386.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/pkg/rpm.py#L85-L95
|
[
"def get_osarch():\n '''\n Get the os architecture using rpm --eval\n '''\n if salt.utils.path.which('rpm'):\n ret = subprocess.Popen(\n 'rpm --eval \"%{_host_cpu}\"',\n shell=True,\n close_fds=True,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE).communicate()[0]\n else:\n ret = ''.join([x for x in platform.uname()[-2:] if x][-1:])\n\n return salt.utils.stringutils.to_str(ret).strip() or 'unknown'\n",
"def check_32(arch, osarch=None):\n '''\n Returns True if both the OS arch and the passed arch are 32-bit\n '''\n if osarch is None:\n osarch = get_osarch()\n return all(x in ARCHES_32 for x in (osarch, arch))\n"
] |
# -*- coding: utf-8 -*-
'''
Common functions for working with RPM packages
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import collections
import datetime
import logging
import subprocess
import platform
import salt.utils.stringutils
import salt.utils.path
# Import 3rd-party libs
from salt.ext import six
log = logging.getLogger(__name__)
# These arches compiled from the rpmUtils.arch python module source
ARCHES_64 = ('x86_64', 'athlon', 'amd64', 'ia32e', 'ia64', 'geode')
ARCHES_32 = ('i386', 'i486', 'i586', 'i686')
ARCHES_PPC = ('ppc', 'ppc64', 'ppc64iseries', 'ppc64pseries')
ARCHES_S390 = ('s390', 's390x')
ARCHES_SPARC = (
'sparc', 'sparcv8', 'sparcv9', 'sparcv9v', 'sparc64', 'sparc64v'
)
ARCHES_ALPHA = (
'alpha', 'alphaev4', 'alphaev45', 'alphaev5', 'alphaev56',
'alphapca56', 'alphaev6', 'alphaev67', 'alphaev68', 'alphaev7'
)
ARCHES_ARM = ('armv5tel', 'armv5tejl', 'armv6l', 'armv7l')
ARCHES_SH = ('sh3', 'sh4', 'sh4a')
ARCHES = ARCHES_64 + ARCHES_32 + ARCHES_PPC + ARCHES_S390 + \
ARCHES_ALPHA + ARCHES_ARM + ARCHES_SH
# EPOCHNUM can't be used until RHEL5 is EOL as it is not present
QUERYFORMAT = '%{NAME}_|-%{EPOCH}_|-%{VERSION}_|-%{RELEASE}_|-%{ARCH}_|-%{REPOID}_|-%{INSTALLTIME}'
# on some archs, the rpm _host_cpu macro doesn't match the pkg name arch
ARCHMAP = {'powerpc64le': 'ppc64le'}
def get_osarch():
'''
Get the os architecture using rpm --eval
'''
if salt.utils.path.which('rpm'):
ret = subprocess.Popen(
'rpm --eval "%{_host_cpu}"',
shell=True,
close_fds=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE).communicate()[0]
else:
ret = ''.join([x for x in platform.uname()[-2:] if x][-1:])
return salt.utils.stringutils.to_str(ret).strip() or 'unknown'
def check_32(arch, osarch=None):
'''
Returns True if both the OS arch and the passed arch are 32-bit
'''
if osarch is None:
osarch = get_osarch()
return all(x in ARCHES_32 for x in (osarch, arch))
def pkginfo(name, version, arch, repoid, install_date=None, install_date_time_t=None):
'''
Build and return a pkginfo namedtuple
'''
pkginfo_tuple = collections.namedtuple(
'PkgInfo',
('name', 'version', 'arch', 'repoid', 'install_date',
'install_date_time_t')
)
return pkginfo_tuple(name, version, arch, repoid, install_date,
install_date_time_t)
def parse_pkginfo(line, osarch=None):
'''
A small helper to parse an rpm/repoquery command's output. Returns a
pkginfo namedtuple.
'''
try:
name, epoch, version, release, arch, repoid, install_time = line.split('_|-')
# Handle unpack errors (should never happen with the queryformat we are
# using, but can't hurt to be careful).
except ValueError:
return None
name = resolve_name(name, arch, osarch)
if release:
version += '-{0}'.format(release)
if epoch not in ('(none)', '0'):
version = ':'.join((epoch, version))
if install_time not in ('(none)', '0'):
install_date = datetime.datetime.utcfromtimestamp(int(install_time)).isoformat() + "Z"
install_date_time_t = int(install_time)
else:
install_date = None
install_date_time_t = None
return pkginfo(name, version, arch, repoid, install_date, install_date_time_t)
def combine_comments(comments):
'''
Given a list of comments, strings, a single comment or a single string,
return a single string of text containing all of the comments, prepending
the '#' and joining with newlines as necessary.
'''
if not isinstance(comments, list):
comments = [comments]
ret = []
for comment in comments:
if not isinstance(comment, six.string_types):
comment = str(comment)
# Normalize for any spaces (or lack thereof) after the #
ret.append('# {0}\n'.format(comment.lstrip('#').lstrip()))
return ''.join(ret)
def version_to_evr(verstring):
'''
Split the package version string into epoch, version and release.
Return this as tuple.
The epoch is always not empty. The version and the release can be an empty
string if such a component could not be found in the version string.
"2:1.0-1.2" => ('2', '1.0', '1.2)
"1.0" => ('0', '1.0', '')
"" => ('0', '', '')
'''
if verstring in [None, '']:
return '0', '', ''
idx_e = verstring.find(':')
if idx_e != -1:
try:
epoch = six.text_type(int(verstring[:idx_e]))
except ValueError:
# look, garbage in the epoch field, how fun, kill it
epoch = '0' # this is our fallback, deal
else:
epoch = '0'
idx_r = verstring.find('-')
if idx_r != -1:
version = verstring[idx_e + 1:idx_r]
release = verstring[idx_r + 1:]
else:
version = verstring[idx_e + 1:]
release = ''
return epoch, version, release
|
saltstack/salt
|
salt/utils/pkg/rpm.py
|
parse_pkginfo
|
python
|
def parse_pkginfo(line, osarch=None):
'''
A small helper to parse an rpm/repoquery command's output. Returns a
pkginfo namedtuple.
'''
try:
name, epoch, version, release, arch, repoid, install_time = line.split('_|-')
# Handle unpack errors (should never happen with the queryformat we are
# using, but can't hurt to be careful).
except ValueError:
return None
name = resolve_name(name, arch, osarch)
if release:
version += '-{0}'.format(release)
if epoch not in ('(none)', '0'):
version = ':'.join((epoch, version))
if install_time not in ('(none)', '0'):
install_date = datetime.datetime.utcfromtimestamp(int(install_time)).isoformat() + "Z"
install_date_time_t = int(install_time)
else:
install_date = None
install_date_time_t = None
return pkginfo(name, version, arch, repoid, install_date, install_date_time_t)
|
A small helper to parse an rpm/repoquery command's output. Returns a
pkginfo namedtuple.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/pkg/rpm.py#L98-L123
|
[
"def pkginfo(name, version, arch, repoid, install_date=None, install_date_time_t=None):\n '''\n Build and return a pkginfo namedtuple\n '''\n pkginfo_tuple = collections.namedtuple(\n 'PkgInfo',\n ('name', 'version', 'arch', 'repoid', 'install_date',\n 'install_date_time_t')\n )\n return pkginfo_tuple(name, version, arch, repoid, install_date,\n install_date_time_t)\n",
"def resolve_name(name, arch, osarch=None):\n '''\n Resolve the package name and arch into a unique name referred to by salt.\n For example, on a 64-bit OS, a 32-bit package will be pkgname.i386.\n '''\n if osarch is None:\n osarch = get_osarch()\n\n if not check_32(arch, osarch) and arch not in (ARCHMAP.get(osarch, osarch), 'noarch'):\n name += '.{0}'.format(arch)\n return name\n"
] |
# -*- coding: utf-8 -*-
'''
Common functions for working with RPM packages
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import collections
import datetime
import logging
import subprocess
import platform
import salt.utils.stringutils
import salt.utils.path
# Import 3rd-party libs
from salt.ext import six
log = logging.getLogger(__name__)
# These arches compiled from the rpmUtils.arch python module source
ARCHES_64 = ('x86_64', 'athlon', 'amd64', 'ia32e', 'ia64', 'geode')
ARCHES_32 = ('i386', 'i486', 'i586', 'i686')
ARCHES_PPC = ('ppc', 'ppc64', 'ppc64iseries', 'ppc64pseries')
ARCHES_S390 = ('s390', 's390x')
ARCHES_SPARC = (
'sparc', 'sparcv8', 'sparcv9', 'sparcv9v', 'sparc64', 'sparc64v'
)
ARCHES_ALPHA = (
'alpha', 'alphaev4', 'alphaev45', 'alphaev5', 'alphaev56',
'alphapca56', 'alphaev6', 'alphaev67', 'alphaev68', 'alphaev7'
)
ARCHES_ARM = ('armv5tel', 'armv5tejl', 'armv6l', 'armv7l')
ARCHES_SH = ('sh3', 'sh4', 'sh4a')
ARCHES = ARCHES_64 + ARCHES_32 + ARCHES_PPC + ARCHES_S390 + \
ARCHES_ALPHA + ARCHES_ARM + ARCHES_SH
# EPOCHNUM can't be used until RHEL5 is EOL as it is not present
QUERYFORMAT = '%{NAME}_|-%{EPOCH}_|-%{VERSION}_|-%{RELEASE}_|-%{ARCH}_|-%{REPOID}_|-%{INSTALLTIME}'
# on some archs, the rpm _host_cpu macro doesn't match the pkg name arch
ARCHMAP = {'powerpc64le': 'ppc64le'}
def get_osarch():
'''
Get the os architecture using rpm --eval
'''
if salt.utils.path.which('rpm'):
ret = subprocess.Popen(
'rpm --eval "%{_host_cpu}"',
shell=True,
close_fds=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE).communicate()[0]
else:
ret = ''.join([x for x in platform.uname()[-2:] if x][-1:])
return salt.utils.stringutils.to_str(ret).strip() or 'unknown'
def check_32(arch, osarch=None):
'''
Returns True if both the OS arch and the passed arch are 32-bit
'''
if osarch is None:
osarch = get_osarch()
return all(x in ARCHES_32 for x in (osarch, arch))
def pkginfo(name, version, arch, repoid, install_date=None, install_date_time_t=None):
'''
Build and return a pkginfo namedtuple
'''
pkginfo_tuple = collections.namedtuple(
'PkgInfo',
('name', 'version', 'arch', 'repoid', 'install_date',
'install_date_time_t')
)
return pkginfo_tuple(name, version, arch, repoid, install_date,
install_date_time_t)
def resolve_name(name, arch, osarch=None):
'''
Resolve the package name and arch into a unique name referred to by salt.
For example, on a 64-bit OS, a 32-bit package will be pkgname.i386.
'''
if osarch is None:
osarch = get_osarch()
if not check_32(arch, osarch) and arch not in (ARCHMAP.get(osarch, osarch), 'noarch'):
name += '.{0}'.format(arch)
return name
def combine_comments(comments):
'''
Given a list of comments, strings, a single comment or a single string,
return a single string of text containing all of the comments, prepending
the '#' and joining with newlines as necessary.
'''
if not isinstance(comments, list):
comments = [comments]
ret = []
for comment in comments:
if not isinstance(comment, six.string_types):
comment = str(comment)
# Normalize for any spaces (or lack thereof) after the #
ret.append('# {0}\n'.format(comment.lstrip('#').lstrip()))
return ''.join(ret)
def version_to_evr(verstring):
'''
Split the package version string into epoch, version and release.
Return this as tuple.
The epoch is always not empty. The version and the release can be an empty
string if such a component could not be found in the version string.
"2:1.0-1.2" => ('2', '1.0', '1.2)
"1.0" => ('0', '1.0', '')
"" => ('0', '', '')
'''
if verstring in [None, '']:
return '0', '', ''
idx_e = verstring.find(':')
if idx_e != -1:
try:
epoch = six.text_type(int(verstring[:idx_e]))
except ValueError:
# look, garbage in the epoch field, how fun, kill it
epoch = '0' # this is our fallback, deal
else:
epoch = '0'
idx_r = verstring.find('-')
if idx_r != -1:
version = verstring[idx_e + 1:idx_r]
release = verstring[idx_r + 1:]
else:
version = verstring[idx_e + 1:]
release = ''
return epoch, version, release
|
saltstack/salt
|
salt/utils/pkg/rpm.py
|
combine_comments
|
python
|
def combine_comments(comments):
'''
Given a list of comments, strings, a single comment or a single string,
return a single string of text containing all of the comments, prepending
the '#' and joining with newlines as necessary.
'''
if not isinstance(comments, list):
comments = [comments]
ret = []
for comment in comments:
if not isinstance(comment, six.string_types):
comment = str(comment)
# Normalize for any spaces (or lack thereof) after the #
ret.append('# {0}\n'.format(comment.lstrip('#').lstrip()))
return ''.join(ret)
|
Given a list of comments, strings, a single comment or a single string,
return a single string of text containing all of the comments, prepending
the '#' and joining with newlines as necessary.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/pkg/rpm.py#L126-L140
| null |
# -*- coding: utf-8 -*-
'''
Common functions for working with RPM packages
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import collections
import datetime
import logging
import subprocess
import platform
import salt.utils.stringutils
import salt.utils.path
# Import 3rd-party libs
from salt.ext import six
log = logging.getLogger(__name__)
# These arches compiled from the rpmUtils.arch python module source
ARCHES_64 = ('x86_64', 'athlon', 'amd64', 'ia32e', 'ia64', 'geode')
ARCHES_32 = ('i386', 'i486', 'i586', 'i686')
ARCHES_PPC = ('ppc', 'ppc64', 'ppc64iseries', 'ppc64pseries')
ARCHES_S390 = ('s390', 's390x')
ARCHES_SPARC = (
'sparc', 'sparcv8', 'sparcv9', 'sparcv9v', 'sparc64', 'sparc64v'
)
ARCHES_ALPHA = (
'alpha', 'alphaev4', 'alphaev45', 'alphaev5', 'alphaev56',
'alphapca56', 'alphaev6', 'alphaev67', 'alphaev68', 'alphaev7'
)
ARCHES_ARM = ('armv5tel', 'armv5tejl', 'armv6l', 'armv7l')
ARCHES_SH = ('sh3', 'sh4', 'sh4a')
ARCHES = ARCHES_64 + ARCHES_32 + ARCHES_PPC + ARCHES_S390 + \
ARCHES_ALPHA + ARCHES_ARM + ARCHES_SH
# EPOCHNUM can't be used until RHEL5 is EOL as it is not present
QUERYFORMAT = '%{NAME}_|-%{EPOCH}_|-%{VERSION}_|-%{RELEASE}_|-%{ARCH}_|-%{REPOID}_|-%{INSTALLTIME}'
# on some archs, the rpm _host_cpu macro doesn't match the pkg name arch
ARCHMAP = {'powerpc64le': 'ppc64le'}
def get_osarch():
'''
Get the os architecture using rpm --eval
'''
if salt.utils.path.which('rpm'):
ret = subprocess.Popen(
'rpm --eval "%{_host_cpu}"',
shell=True,
close_fds=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE).communicate()[0]
else:
ret = ''.join([x for x in platform.uname()[-2:] if x][-1:])
return salt.utils.stringutils.to_str(ret).strip() or 'unknown'
def check_32(arch, osarch=None):
'''
Returns True if both the OS arch and the passed arch are 32-bit
'''
if osarch is None:
osarch = get_osarch()
return all(x in ARCHES_32 for x in (osarch, arch))
def pkginfo(name, version, arch, repoid, install_date=None, install_date_time_t=None):
'''
Build and return a pkginfo namedtuple
'''
pkginfo_tuple = collections.namedtuple(
'PkgInfo',
('name', 'version', 'arch', 'repoid', 'install_date',
'install_date_time_t')
)
return pkginfo_tuple(name, version, arch, repoid, install_date,
install_date_time_t)
def resolve_name(name, arch, osarch=None):
'''
Resolve the package name and arch into a unique name referred to by salt.
For example, on a 64-bit OS, a 32-bit package will be pkgname.i386.
'''
if osarch is None:
osarch = get_osarch()
if not check_32(arch, osarch) and arch not in (ARCHMAP.get(osarch, osarch), 'noarch'):
name += '.{0}'.format(arch)
return name
def parse_pkginfo(line, osarch=None):
'''
A small helper to parse an rpm/repoquery command's output. Returns a
pkginfo namedtuple.
'''
try:
name, epoch, version, release, arch, repoid, install_time = line.split('_|-')
# Handle unpack errors (should never happen with the queryformat we are
# using, but can't hurt to be careful).
except ValueError:
return None
name = resolve_name(name, arch, osarch)
if release:
version += '-{0}'.format(release)
if epoch not in ('(none)', '0'):
version = ':'.join((epoch, version))
if install_time not in ('(none)', '0'):
install_date = datetime.datetime.utcfromtimestamp(int(install_time)).isoformat() + "Z"
install_date_time_t = int(install_time)
else:
install_date = None
install_date_time_t = None
return pkginfo(name, version, arch, repoid, install_date, install_date_time_t)
def version_to_evr(verstring):
'''
Split the package version string into epoch, version and release.
Return this as tuple.
The epoch is always not empty. The version and the release can be an empty
string if such a component could not be found in the version string.
"2:1.0-1.2" => ('2', '1.0', '1.2)
"1.0" => ('0', '1.0', '')
"" => ('0', '', '')
'''
if verstring in [None, '']:
return '0', '', ''
idx_e = verstring.find(':')
if idx_e != -1:
try:
epoch = six.text_type(int(verstring[:idx_e]))
except ValueError:
# look, garbage in the epoch field, how fun, kill it
epoch = '0' # this is our fallback, deal
else:
epoch = '0'
idx_r = verstring.find('-')
if idx_r != -1:
version = verstring[idx_e + 1:idx_r]
release = verstring[idx_r + 1:]
else:
version = verstring[idx_e + 1:]
release = ''
return epoch, version, release
|
saltstack/salt
|
salt/utils/pkg/rpm.py
|
version_to_evr
|
python
|
def version_to_evr(verstring):
'''
Split the package version string into epoch, version and release.
Return this as tuple.
The epoch is always not empty. The version and the release can be an empty
string if such a component could not be found in the version string.
"2:1.0-1.2" => ('2', '1.0', '1.2)
"1.0" => ('0', '1.0', '')
"" => ('0', '', '')
'''
if verstring in [None, '']:
return '0', '', ''
idx_e = verstring.find(':')
if idx_e != -1:
try:
epoch = six.text_type(int(verstring[:idx_e]))
except ValueError:
# look, garbage in the epoch field, how fun, kill it
epoch = '0' # this is our fallback, deal
else:
epoch = '0'
idx_r = verstring.find('-')
if idx_r != -1:
version = verstring[idx_e + 1:idx_r]
release = verstring[idx_r + 1:]
else:
version = verstring[idx_e + 1:]
release = ''
return epoch, version, release
|
Split the package version string into epoch, version and release.
Return this as tuple.
The epoch is always not empty. The version and the release can be an empty
string if such a component could not be found in the version string.
"2:1.0-1.2" => ('2', '1.0', '1.2)
"1.0" => ('0', '1.0', '')
"" => ('0', '', '')
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/pkg/rpm.py#L143-L175
| null |
# -*- coding: utf-8 -*-
'''
Common functions for working with RPM packages
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import collections
import datetime
import logging
import subprocess
import platform
import salt.utils.stringutils
import salt.utils.path
# Import 3rd-party libs
from salt.ext import six
log = logging.getLogger(__name__)
# These arches compiled from the rpmUtils.arch python module source
ARCHES_64 = ('x86_64', 'athlon', 'amd64', 'ia32e', 'ia64', 'geode')
ARCHES_32 = ('i386', 'i486', 'i586', 'i686')
ARCHES_PPC = ('ppc', 'ppc64', 'ppc64iseries', 'ppc64pseries')
ARCHES_S390 = ('s390', 's390x')
ARCHES_SPARC = (
'sparc', 'sparcv8', 'sparcv9', 'sparcv9v', 'sparc64', 'sparc64v'
)
ARCHES_ALPHA = (
'alpha', 'alphaev4', 'alphaev45', 'alphaev5', 'alphaev56',
'alphapca56', 'alphaev6', 'alphaev67', 'alphaev68', 'alphaev7'
)
ARCHES_ARM = ('armv5tel', 'armv5tejl', 'armv6l', 'armv7l')
ARCHES_SH = ('sh3', 'sh4', 'sh4a')
ARCHES = ARCHES_64 + ARCHES_32 + ARCHES_PPC + ARCHES_S390 + \
ARCHES_ALPHA + ARCHES_ARM + ARCHES_SH
# EPOCHNUM can't be used until RHEL5 is EOL as it is not present
QUERYFORMAT = '%{NAME}_|-%{EPOCH}_|-%{VERSION}_|-%{RELEASE}_|-%{ARCH}_|-%{REPOID}_|-%{INSTALLTIME}'
# on some archs, the rpm _host_cpu macro doesn't match the pkg name arch
ARCHMAP = {'powerpc64le': 'ppc64le'}
def get_osarch():
'''
Get the os architecture using rpm --eval
'''
if salt.utils.path.which('rpm'):
ret = subprocess.Popen(
'rpm --eval "%{_host_cpu}"',
shell=True,
close_fds=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE).communicate()[0]
else:
ret = ''.join([x for x in platform.uname()[-2:] if x][-1:])
return salt.utils.stringutils.to_str(ret).strip() or 'unknown'
def check_32(arch, osarch=None):
'''
Returns True if both the OS arch and the passed arch are 32-bit
'''
if osarch is None:
osarch = get_osarch()
return all(x in ARCHES_32 for x in (osarch, arch))
def pkginfo(name, version, arch, repoid, install_date=None, install_date_time_t=None):
'''
Build and return a pkginfo namedtuple
'''
pkginfo_tuple = collections.namedtuple(
'PkgInfo',
('name', 'version', 'arch', 'repoid', 'install_date',
'install_date_time_t')
)
return pkginfo_tuple(name, version, arch, repoid, install_date,
install_date_time_t)
def resolve_name(name, arch, osarch=None):
'''
Resolve the package name and arch into a unique name referred to by salt.
For example, on a 64-bit OS, a 32-bit package will be pkgname.i386.
'''
if osarch is None:
osarch = get_osarch()
if not check_32(arch, osarch) and arch not in (ARCHMAP.get(osarch, osarch), 'noarch'):
name += '.{0}'.format(arch)
return name
def parse_pkginfo(line, osarch=None):
'''
A small helper to parse an rpm/repoquery command's output. Returns a
pkginfo namedtuple.
'''
try:
name, epoch, version, release, arch, repoid, install_time = line.split('_|-')
# Handle unpack errors (should never happen with the queryformat we are
# using, but can't hurt to be careful).
except ValueError:
return None
name = resolve_name(name, arch, osarch)
if release:
version += '-{0}'.format(release)
if epoch not in ('(none)', '0'):
version = ':'.join((epoch, version))
if install_time not in ('(none)', '0'):
install_date = datetime.datetime.utcfromtimestamp(int(install_time)).isoformat() + "Z"
install_date_time_t = int(install_time)
else:
install_date = None
install_date_time_t = None
return pkginfo(name, version, arch, repoid, install_date, install_date_time_t)
def combine_comments(comments):
'''
Given a list of comments, strings, a single comment or a single string,
return a single string of text containing all of the comments, prepending
the '#' and joining with newlines as necessary.
'''
if not isinstance(comments, list):
comments = [comments]
ret = []
for comment in comments:
if not isinstance(comment, six.string_types):
comment = str(comment)
# Normalize for any spaces (or lack thereof) after the #
ret.append('# {0}\n'.format(comment.lstrip('#').lstrip()))
return ''.join(ret)
|
saltstack/salt
|
salt/states/boto_secgroup.py
|
present
|
python
|
def present(
name,
description,
vpc_id=None,
vpc_name=None,
rules=None,
rules_egress=None,
delete_ingress_rules=True,
delete_egress_rules=True,
region=None,
key=None,
keyid=None,
profile=None,
tags=None):
'''
Ensure the security group exists with the specified rules.
name
Name of the security group.
description
A description of this security group.
vpc_id
The ID of the VPC to create the security group in, if any. Exclusive with vpc_name.
vpc_name
The name of the VPC to create the security group in, if any. Exclusive with vpc_id.
.. versionadded:: 2016.3.0
.. versionadded:: 2015.8.2
rules
A list of ingress rule dicts. If not specified, ``rules=None``,
the ingress rules will be unmanaged. If set to an empty list, ``[]``,
then all ingress rules will be removed.
rules_egress
A list of egress rule dicts. If not specified, ``rules_egress=None``,
the egress rules will be unmanaged. If set to an empty list, ``[]``,
then all egress rules will be removed.
delete_ingress_rules
Some tools (EMR comes to mind) insist on adding rules on-the-fly, which
salt will happily remove on the next run. Set this param to False to
avoid deleting rules which were added outside of salt.
delete_egress_rules
Some tools (EMR comes to mind) insist on adding rules on-the-fly, which
salt will happily remove on the next run. Set this param to False to
avoid deleting rules which were added outside of salt.
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string)
that contains a dict with region, key, and keyid.
tags
List of key:value pairs of tags to set on the security group
.. versionadded:: 2016.3.0
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
_ret = _security_group_present(name, description, vpc_id=vpc_id,
vpc_name=vpc_name, region=region,
key=key, keyid=keyid, profile=profile)
ret['changes'] = _ret['changes']
ret['comment'] = ' '.join([ret['comment'], _ret['comment']])
if not _ret['result']:
ret['result'] = _ret['result']
if ret['result'] is False:
return ret
elif ret['result'] is None:
return ret
if rules is not None:
_ret = _rules_present(name, rules, delete_ingress_rules, vpc_id=vpc_id,
vpc_name=vpc_name, region=region, key=key,
keyid=keyid, profile=profile)
ret['changes'] = dictupdate.update(ret['changes'], _ret['changes'])
ret['comment'] = ' '.join([ret['comment'], _ret['comment']])
if not _ret['result']:
ret['result'] = _ret['result']
if rules_egress is not None:
_ret = _rules_egress_present(name, rules_egress, delete_egress_rules,
vpc_id=vpc_id, vpc_name=vpc_name,
region=region, key=key, keyid=keyid,
profile=profile)
ret['changes'] = dictupdate.update(ret['changes'], _ret['changes'])
ret['comment'] = ' '.join([ret['comment'], _ret['comment']])
if not _ret['result']:
ret['result'] = _ret['result']
_ret = _tags_present(
name=name, tags=tags, vpc_id=vpc_id, vpc_name=vpc_name,
region=region, key=key, keyid=keyid, profile=profile
)
ret['changes'] = dictupdate.update(ret['changes'], _ret['changes'])
ret['comment'] = ' '.join([ret['comment'], _ret['comment']])
if not _ret['result']:
ret['result'] = _ret['result']
return ret
|
Ensure the security group exists with the specified rules.
name
Name of the security group.
description
A description of this security group.
vpc_id
The ID of the VPC to create the security group in, if any. Exclusive with vpc_name.
vpc_name
The name of the VPC to create the security group in, if any. Exclusive with vpc_id.
.. versionadded:: 2016.3.0
.. versionadded:: 2015.8.2
rules
A list of ingress rule dicts. If not specified, ``rules=None``,
the ingress rules will be unmanaged. If set to an empty list, ``[]``,
then all ingress rules will be removed.
rules_egress
A list of egress rule dicts. If not specified, ``rules_egress=None``,
the egress rules will be unmanaged. If set to an empty list, ``[]``,
then all egress rules will be removed.
delete_ingress_rules
Some tools (EMR comes to mind) insist on adding rules on-the-fly, which
salt will happily remove on the next run. Set this param to False to
avoid deleting rules which were added outside of salt.
delete_egress_rules
Some tools (EMR comes to mind) insist on adding rules on-the-fly, which
salt will happily remove on the next run. Set this param to False to
avoid deleting rules which were added outside of salt.
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string)
that contains a dict with region, key, and keyid.
tags
List of key:value pairs of tags to set on the security group
.. versionadded:: 2016.3.0
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_secgroup.py#L127-L235
|
[
"def update(dest, upd, recursive_update=True, merge_lists=False):\n '''\n Recursive version of the default dict.update\n\n Merges upd recursively into dest\n\n If recursive_update=False, will use the classic dict.update, or fall back\n on a manual merge (helpful for non-dict types like FunctionWrapper)\n\n If merge_lists=True, will aggregate list object types instead of replace.\n The list in ``upd`` is added to the list in ``dest``, so the resulting list\n is ``dest[key] + upd[key]``. This behavior is only activated when\n recursive_update=True. By default merge_lists=False.\n\n .. versionchanged: 2016.11.6\n When merging lists, duplicate values are removed. Values already\n present in the ``dest`` list are not added from the ``upd`` list.\n '''\n if (not isinstance(dest, Mapping)) \\\n or (not isinstance(upd, Mapping)):\n raise TypeError('Cannot update using non-dict types in dictupdate.update()')\n updkeys = list(upd.keys())\n if not set(list(dest.keys())) & set(updkeys):\n recursive_update = False\n if recursive_update:\n for key in updkeys:\n val = upd[key]\n try:\n dest_subkey = dest.get(key, None)\n except AttributeError:\n dest_subkey = None\n if isinstance(dest_subkey, Mapping) \\\n and isinstance(val, Mapping):\n ret = update(dest_subkey, val, merge_lists=merge_lists)\n dest[key] = ret\n elif isinstance(dest_subkey, list) and isinstance(val, list):\n if merge_lists:\n merged = copy.deepcopy(dest_subkey)\n merged.extend([x for x in val if x not in merged])\n dest[key] = merged\n else:\n dest[key] = upd[key]\n else:\n dest[key] = upd[key]\n return dest\n try:\n for k in upd:\n dest[k] = upd[k]\n except AttributeError:\n # this mapping is not a dict\n for k in upd:\n dest[k] = upd[k]\n return dest\n",
"def _tags_present(name, tags, vpc_id=None, vpc_name=None, region=None,\n key=None, keyid=None, profile=None):\n '''\n helper function to validate tags are correct\n '''\n ret = {'result': True, 'comment': '', 'changes': {}}\n if tags:\n sg = __salt__['boto_secgroup.get_config'](name=name, group_id=None, region=region, key=key,\n keyid=keyid, profile=profile, vpc_id=vpc_id,\n vpc_name=vpc_name)\n if not sg:\n ret['comment'] = '{0} security group configuration could not be retrieved.'.format(name)\n ret['result'] = False\n return ret\n tags_to_add = tags\n tags_to_update = {}\n tags_to_remove = []\n if sg.get('tags'):\n for existing_tag in sg['tags']:\n if existing_tag not in tags:\n if existing_tag not in tags_to_remove:\n tags_to_remove.append(existing_tag)\n else:\n if tags[existing_tag] != sg['tags'][existing_tag]:\n tags_to_update[existing_tag] = tags[existing_tag]\n tags_to_add.pop(existing_tag)\n if tags_to_remove:\n if __opts__['test']:\n msg = 'The following tag{0} set to be removed: {1}.'.format(\n ('s are' if len(tags_to_remove) > 1 else ' is'), ', '.join(tags_to_remove))\n ret['comment'] = ' '.join([ret['comment'], msg])\n ret['result'] = None\n else:\n temp_ret = __salt__['boto_secgroup.delete_tags'](tags_to_remove,\n name=name,\n group_id=None,\n vpc_name=vpc_name,\n vpc_id=vpc_id,\n region=region,\n key=key,\n keyid=keyid,\n profile=profile)\n if not temp_ret:\n ret['result'] = False\n ret['comment'] = ' '.join([\n ret['comment'],\n 'Error attempting to delete tags {0}.'.format(tags_to_remove)\n ])\n return ret\n if 'old' not in ret['changes']:\n ret['changes'] = dictupdate.update(ret['changes'], {'old': {'tags': {}}})\n for rem_tag in tags_to_remove:\n ret['changes']['old']['tags'][rem_tag] = sg['tags'][rem_tag]\n if tags_to_add or tags_to_update:\n if __opts__['test']:\n if tags_to_add:\n msg = 'The following tag{0} set to be added: {1}.'.format(\n ('s are' if len(tags_to_add.keys()) > 1 else ' is'),\n ', '.join(tags_to_add.keys()))\n ret['comment'] = ' '.join([ret['comment'], msg])\n ret['result'] = None\n if tags_to_update:\n msg = 'The following tag {0} set to be updated: {1}.'.format(\n ('values are' if len(tags_to_update.keys()) > 1 else 'value is'),\n ', '.join(tags_to_update.keys()))\n ret['comment'] = ' '.join([ret['comment'], msg])\n ret['result'] = None\n else:\n all_tag_changes = dictupdate.update(tags_to_add, tags_to_update)\n temp_ret = __salt__['boto_secgroup.set_tags'](all_tag_changes,\n name=name,\n group_id=None,\n vpc_name=vpc_name,\n vpc_id=vpc_id,\n region=region,\n key=key,\n keyid=keyid,\n profile=profile)\n if not temp_ret:\n ret['result'] = False\n msg = 'Error attempting to set tags.'\n ret['comment'] = ' '.join([ret['comment'], msg])\n return ret\n if 'old' not in ret['changes']:\n ret['changes'] = dictupdate.update(ret['changes'], {'old': {'tags': {}}})\n if 'new' not in ret['changes']:\n ret['changes'] = dictupdate.update(ret['changes'], {'new': {'tags': {}}})\n for tag in all_tag_changes:\n ret['changes']['new']['tags'][tag] = tags[tag]\n if 'tags' in sg:\n if sg['tags']:\n if tag in sg['tags']:\n ret['changes']['old']['tags'][tag] = sg['tags'][tag]\n if not tags_to_update and not tags_to_remove and not tags_to_add:\n ret['comment'] = ' '.join([ret['comment'], 'Tags are already set.'])\n return ret\n",
"def _security_group_present(name, description, vpc_id=None, vpc_name=None,\n region=None, key=None, keyid=None, profile=None):\n '''\n given a group name or a group name and vpc id (or vpc name):\n 1. determine if the group exists\n 2. if the group does not exist, creates the group\n 3. return the group's configuration and any changes made\n '''\n ret = {'result': True, 'comment': '', 'changes': {}}\n exists = __salt__['boto_secgroup.exists'](name, region, key, keyid,\n profile, vpc_id, vpc_name)\n if not exists:\n if __opts__['test']:\n ret['comment'] = 'Security group {0} is set to be created.'.format(name)\n ret['result'] = None\n return ret\n created = __salt__['boto_secgroup.create'](name=name, description=description,\n vpc_id=vpc_id, vpc_name=vpc_name,\n region=region, key=key, keyid=keyid,\n profile=profile)\n if created:\n ret['changes']['old'] = {'secgroup': None}\n sg = __salt__['boto_secgroup.get_config'](name=name, group_id=None, region=region, key=key,\n keyid=keyid, profile=profile, vpc_id=vpc_id,\n vpc_name=vpc_name)\n ret['changes']['new'] = {'secgroup': sg}\n ret['comment'] = 'Security group {0} created.'.format(name)\n else:\n ret['result'] = False\n ret['comment'] = 'Failed to create {0} security group.'.format(name)\n else:\n ret['comment'] = 'Security group {0} present.'.format(name)\n return ret\n",
"def _rules_present(name, rules, delete_ingress_rules=True, vpc_id=None,\n vpc_name=None, region=None, key=None, keyid=None, profile=None):\n '''\n given a group name or group name and vpc_id (or vpc name):\n 1. get lists of desired rule changes (using _get_rule_changes)\n 2. authorize/create rules missing rules\n 3. if delete_ingress_rules is True, delete/revoke non-requested rules\n 4. return 'old' and 'new' group rules\n '''\n ret = {'result': True, 'comment': '', 'changes': {}}\n sg = __salt__['boto_secgroup.get_config'](name=name, group_id=None, region=region, key=key,\n keyid=keyid, profile=profile, vpc_id=vpc_id,\n vpc_name=vpc_name)\n if not sg:\n ret['comment'] = '{0} security group configuration could not be retrieved.'.format(name)\n ret['result'] = False\n return ret\n rules = _split_rules(rules)\n if vpc_id or vpc_name:\n for rule in rules:\n _source_group_name = rule.get('source_group_name', None)\n if _source_group_name:\n _group_vpc_name = vpc_name\n _group_vpc_id = vpc_id\n _source_group_name_vpc = rule.get('source_group_name_vpc', None)\n if _source_group_name_vpc:\n _group_vpc_name = _source_group_name_vpc\n _group_vpc_id = None\n _group_id = __salt__['boto_secgroup.get_group_id'](\n name=_source_group_name, vpc_id=_group_vpc_id, vpc_name=_group_vpc_name,\n region=region, key=key, keyid=keyid, profile=profile\n )\n if not _group_id:\n raise SaltInvocationError(\n 'source_group_name {0} does not map to a valid '\n 'source group id.'.format(_source_group_name)\n )\n rule['source_group_name'] = None\n if _source_group_name_vpc:\n rule.pop('source_group_name_vpc')\n rule['source_group_group_id'] = _group_id\n # rules = rules that exist in salt state\n # sg['rules'] = that exist in present group\n to_delete, to_create = _get_rule_changes(rules, sg['rules'])\n to_delete = to_delete if delete_ingress_rules else []\n if to_create or to_delete:\n if __opts__['test']:\n msg = \"\"\"Security group {0} set to have rules modified.\n To be created: {1}\n To be deleted: {2}\"\"\".format(name, pprint.pformat(to_create),\n pprint.pformat(to_delete))\n ret['comment'] = msg\n ret['result'] = None\n return ret\n if to_delete:\n deleted = True\n for rule in to_delete:\n _deleted = __salt__['boto_secgroup.revoke'](\n name, vpc_id=vpc_id, vpc_name=vpc_name, region=region,\n key=key, keyid=keyid, profile=profile, **rule)\n if not _deleted:\n deleted = False\n if deleted:\n ret['comment'] = 'Removed rules on {0} security group.'.format(name)\n else:\n ret['comment'] = 'Failed to remove rules on {0} security group.'.format(name)\n ret['result'] = False\n if to_create:\n created = True\n for rule in to_create:\n _created = __salt__['boto_secgroup.authorize'](\n name, vpc_id=vpc_id, vpc_name=vpc_name, region=region,\n key=key, keyid=keyid, profile=profile, **rule)\n if not _created:\n created = False\n if created:\n ret['comment'] = ' '.join([\n ret['comment'],\n 'Created rules on {0} security group.'.format(name)\n ])\n else:\n ret['comment'] = ' '.join([\n ret['comment'],\n 'Failed to create rules on {0} security group.'.format(name)\n ])\n ret['result'] = False\n ret['changes']['old'] = {'rules': sg['rules']}\n sg = __salt__['boto_secgroup.get_config'](name=name, group_id=None, region=region, key=key,\n keyid=keyid, profile=profile, vpc_id=vpc_id,\n vpc_name=vpc_name)\n ret['changes']['new'] = {'rules': sg['rules']}\n return ret\n",
"def _rules_egress_present(name, rules_egress, delete_egress_rules=True, vpc_id=None,\n vpc_name=None, region=None, key=None, keyid=None, profile=None):\n '''\n given a group name or group name and vpc_id (or vpc name):\n 1. get lists of desired rule changes (using _get_rule_changes)\n 2. authorize/create missing rules\n 3. if delete_egress_rules is True, delete/revoke non-requested rules\n 4. return 'old' and 'new' group rules\n '''\n ret = {'result': True, 'comment': '', 'changes': {}}\n sg = __salt__['boto_secgroup.get_config'](name=name, group_id=None, region=region, key=key,\n keyid=keyid, profile=profile, vpc_id=vpc_id,\n vpc_name=vpc_name)\n if not sg:\n ret['comment'] = '{0} security group configuration could not be retrieved.'.format(name)\n ret['result'] = False\n return ret\n rules_egress = _split_rules(rules_egress)\n if vpc_id or vpc_name:\n for rule in rules_egress:\n _source_group_name = rule.get('source_group_name', None)\n if _source_group_name:\n _group_vpc_name = vpc_name\n _group_vpc_id = vpc_id\n _source_group_name_vpc = rule.get('source_group_name_vpc', None)\n if _source_group_name_vpc:\n _group_vpc_name = _source_group_name_vpc\n _group_vpc_id = None\n _group_id = __salt__['boto_secgroup.get_group_id'](\n name=_source_group_name, vpc_id=_group_vpc_id, vpc_name=_group_vpc_name,\n region=region, key=key, keyid=keyid, profile=profile\n )\n if not _group_id:\n raise SaltInvocationError(\n 'source_group_name {0} does not map to a valid '\n 'source group id.'.format(_source_group_name)\n )\n rule['source_group_name'] = None\n if _source_group_name_vpc:\n rule.pop('source_group_name_vpc')\n rule['source_group_group_id'] = _group_id\n # rules_egress = rules that exist in salt state\n # sg['rules_egress'] = that exist in present group\n to_delete, to_create = _get_rule_changes(rules_egress, sg['rules_egress'])\n to_delete = to_delete if delete_egress_rules else []\n if to_create or to_delete:\n if __opts__['test']:\n msg = \"\"\"Security group {0} set to have rules modified.\n To be created: {1}\n To be deleted: {2}\"\"\".format(name, pprint.pformat(to_create),\n pprint.pformat(to_delete))\n ret['comment'] = msg\n ret['result'] = None\n return ret\n if to_delete:\n deleted = True\n for rule in to_delete:\n _deleted = __salt__['boto_secgroup.revoke'](\n name, vpc_id=vpc_id, vpc_name=vpc_name, region=region,\n key=key, keyid=keyid, profile=profile, egress=True, **rule)\n if not _deleted:\n deleted = False\n if deleted:\n ret['comment'] = ' '.join([\n ret['comment'],\n 'Removed egress rule on {0} security group.'.format(name)\n ])\n else:\n ret['comment'] = ' '.join([\n ret['comment'],\n 'Failed to remove egress rule on {0} security group.'.format(name)\n ])\n ret['result'] = False\n if to_create:\n created = True\n for rule in to_create:\n _created = __salt__['boto_secgroup.authorize'](\n name, vpc_id=vpc_id, vpc_name=vpc_name, region=region,\n key=key, keyid=keyid, profile=profile, egress=True, **rule)\n if not _created:\n created = False\n if created:\n ret['comment'] = ' '.join([\n ret['comment'],\n 'Created egress rules on {0} security group.'.format(name)\n ])\n else:\n ret['comment'] = ' '.join([\n ret['comment'],\n 'Failed to create egress rules on {0} security group.'.format(name)\n ])\n ret['result'] = False\n\n ret['changes']['old'] = {'rules_egress': sg['rules_egress']}\n sg = __salt__['boto_secgroup.get_config'](name=name, group_id=None, region=region, key=key,\n keyid=keyid, profile=profile, vpc_id=vpc_id,\n vpc_name=vpc_name)\n ret['changes']['new'] = {'rules_egress': sg['rules_egress']}\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Manage Security Groups
======================
.. versionadded:: 2014.7.0
Create and destroy Security Groups. Be aware that this interacts with Amazon's
services, and so may incur charges.
This module uses ``boto``, which can be installed via package, or pip.
This module accepts explicit EC2 credentials but can also utilize
IAM roles assigned to the instance through Instance Profiles. Dynamic
credentials are then automatically obtained from AWS API and no further
configuration is necessary. More information available `here
<http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html>`_.
If IAM roles are not used you need to specify them either in a pillar file or
in the minion's config file:
.. code-block:: yaml
secgroup.keyid: GKTADJGHEIQSXMKKRBJ08H
secgroup.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
It's also possible to specify ``key``, ``keyid`` and ``region`` via a profile, either
passed in as a dict, or as a string to pull from pillars or minion config:
.. code-block:: yaml
myprofile:
keyid: GKTADJGHEIQSXMKKRBJ08H
key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
region: us-east-1
.. code-block:: yaml
Ensure mysecgroup exists:
boto_secgroup.present:
- name: mysecgroup
- description: My security group
- vpc_name: myvpc
- rules:
- ip_protocol: tcp
from_port: 80
to_port: 80
cidr_ip:
- 10.0.0.0/8
- 192.168.0.0/16
- ip_protocol: tcp
from_port: 8080
to_port: 8090
cidr_ip:
- 10.0.0.0/8
- 192.168.0.0/16
- ip_protocol: icmp
from_port: -1
to_port: -1
source_group_name: mysecgroup
- ip_protocol: tcp
from_port: 8080
to_port: 8080
source_group_name: MyOtherSecGroup
source_group_name_vpc: MyPeeredVPC
- rules_egress:
- ip_protocol: all
from_port: -1
to_port: -1
cidr_ip:
- 10.0.0.0/8
- 192.168.0.0/16
- tags:
SomeTag: 'My Tag Value'
SomeOtherTag: 'Other Tag Value'
- region: us-east-1
- keyid: GKTADJGHEIQSXMKKRBJ08H
- key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
# Using a profile from pillars
Ensure mysecgroup exists:
boto_secgroup.present:
- name: mysecgroup
- description: My security group
- profile: myprofile
# Passing in a profile
Ensure mysecgroup exists:
boto_secgroup.present:
- name: mysecgroup
- description: My security group
- profile:
keyid: GKTADJGHEIQSXMKKRBJ08H
key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
region: us-east-1
.. note::
When using the ``profile`` parameter and ``region`` is set outside of
the profile group, region is ignored and a default region will be used.
If ``region`` is missing from the ``profile`` data set, ``us-east-1``
will be used as the default region.
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import Python libs
import logging
import pprint
# Import salt libs
import salt.utils.dictupdate as dictupdate
from salt.exceptions import SaltInvocationError
from salt.ext import six
log = logging.getLogger(__name__)
def __virtual__():
'''
Only load if boto is available.
'''
return 'boto_secgroup' if 'boto_secgroup.exists' in __salt__ else False
def _security_group_present(name, description, vpc_id=None, vpc_name=None,
region=None, key=None, keyid=None, profile=None):
'''
given a group name or a group name and vpc id (or vpc name):
1. determine if the group exists
2. if the group does not exist, creates the group
3. return the group's configuration and any changes made
'''
ret = {'result': True, 'comment': '', 'changes': {}}
exists = __salt__['boto_secgroup.exists'](name, region, key, keyid,
profile, vpc_id, vpc_name)
if not exists:
if __opts__['test']:
ret['comment'] = 'Security group {0} is set to be created.'.format(name)
ret['result'] = None
return ret
created = __salt__['boto_secgroup.create'](name=name, description=description,
vpc_id=vpc_id, vpc_name=vpc_name,
region=region, key=key, keyid=keyid,
profile=profile)
if created:
ret['changes']['old'] = {'secgroup': None}
sg = __salt__['boto_secgroup.get_config'](name=name, group_id=None, region=region, key=key,
keyid=keyid, profile=profile, vpc_id=vpc_id,
vpc_name=vpc_name)
ret['changes']['new'] = {'secgroup': sg}
ret['comment'] = 'Security group {0} created.'.format(name)
else:
ret['result'] = False
ret['comment'] = 'Failed to create {0} security group.'.format(name)
else:
ret['comment'] = 'Security group {0} present.'.format(name)
return ret
def _split_rules(rules):
'''
Split rules with lists into individual rules.
We accept some attributes as lists or strings. The data we get back from
the execution module lists rules as individual rules. We need to split the
provided rules into individual rules to compare them.
'''
split = []
for rule in rules:
cidr_ip = rule.get('cidr_ip')
group_name = rule.get('source_group_name')
group_id = rule.get('source_group_group_id')
if cidr_ip and not isinstance(cidr_ip, six.string_types):
for ip in cidr_ip:
_rule = rule.copy()
_rule['cidr_ip'] = ip
split.append(_rule)
elif group_name and not isinstance(group_name, six.string_types):
for name in group_name:
_rule = rule.copy()
_rule['source_group_name'] = name
split.append(_rule)
elif group_id and not isinstance(group_id, six.string_types):
for _id in group_id:
_rule = rule.copy()
_rule['source_group_group_id'] = _id
split.append(_rule)
else:
split.append(rule)
return split
def _check_rule(rule, _rule):
'''
Check to see if two rules are the same. Needed to compare rules fetched
from boto, since they may not completely match rules defined in sls files
but may be functionally equivalent.
'''
# We need to alter what Boto returns if no ports are specified
# so that we can compare rules fairly.
#
# Boto returns None for from_port and to_port where we're required
# to pass in "-1" instead.
if _rule.get('from_port') is None:
_rule['from_port'] = -1
if _rule.get('to_port') is None:
_rule['to_port'] = -1
if (rule['ip_protocol'] == _rule['ip_protocol'] and
six.text_type(rule['from_port']) == six.text_type(_rule['from_port']) and
six.text_type(rule['to_port']) == six.text_type(_rule['to_port'])):
_cidr_ip = _rule.get('cidr_ip')
if _cidr_ip and _cidr_ip == rule.get('cidr_ip'):
return True
_owner_id = _rule.get('source_group_owner_id')
if _owner_id and _owner_id == rule.get('source_group_owner_id'):
return True
_group_id = _rule.get('source_group_group_id')
if _group_id and _group_id == rule.get('source_group_group_id'):
return True
_group_name = _rule.get('source_group_name')
if _group_name and _group_id == rule.get('source_group_name'):
return True
return False
def _get_rule_changes(rules, _rules):
'''
given a list of desired rules (rules) and existing rules (_rules) return
a list of rules to delete (to_delete) and to create (to_create)
'''
to_delete = []
to_create = []
# for each rule in state file
# 1. validate rule
# 2. determine if rule exists in existing security group rules
for rule in rules:
try:
ip_protocol = six.text_type(rule.get('ip_protocol'))
except KeyError:
raise SaltInvocationError('ip_protocol, to_port, and from_port are'
' required arguments for security group'
' rules.')
supported_protocols = ['tcp', '6', 6, 'udp', '17', 17, 'icmp', '1', 1,
'all', '-1', -1]
if ip_protocol not in supported_protocols and (not
'{0}'.format(ip_protocol).isdigit() or int(ip_protocol) > 255):
raise SaltInvocationError(
'Invalid ip_protocol {0} specified in security group rule.'.format(ip_protocol))
# For the 'all' case, we need to change the protocol name to '-1'.
if ip_protocol == 'all':
rule['ip_protocol'] = '-1'
cidr_ip = rule.get('cidr_ip', None)
group_name = rule.get('source_group_name', None)
group_id = rule.get('source_group_group_id', None)
if cidr_ip and (group_id or group_name):
raise SaltInvocationError('cidr_ip and source groups can not both'
' be specified in security group rules.')
if group_id and group_name:
raise SaltInvocationError('Either source_group_group_id or'
' source_group_name can be specified in'
' security group rules, but not both.')
if not (cidr_ip or group_id or group_name):
raise SaltInvocationError('cidr_ip, source_group_group_id, or'
' source_group_name must be provided for'
' security group rules.')
rule_found = False
# for each rule in existing security group ruleset determine if
# new rule exists
for _rule in _rules:
if _check_rule(rule, _rule):
rule_found = True
break
if not rule_found:
to_create.append(rule)
# for each rule in existing security group configuration
# 1. determine if rules needed to be deleted
for _rule in _rules:
rule_found = False
for rule in rules:
if _check_rule(rule, _rule):
rule_found = True
break
if not rule_found:
# Can only supply name or id, not both. Since we're deleting
# entries, it doesn't matter which we pick.
_rule.pop('source_group_name', None)
to_delete.append(_rule)
log.debug('Rules to be deleted: %s', to_delete)
log.debug('Rules to be created: %s', to_create)
return (to_delete, to_create)
def _rules_present(name, rules, delete_ingress_rules=True, vpc_id=None,
vpc_name=None, region=None, key=None, keyid=None, profile=None):
'''
given a group name or group name and vpc_id (or vpc name):
1. get lists of desired rule changes (using _get_rule_changes)
2. authorize/create rules missing rules
3. if delete_ingress_rules is True, delete/revoke non-requested rules
4. return 'old' and 'new' group rules
'''
ret = {'result': True, 'comment': '', 'changes': {}}
sg = __salt__['boto_secgroup.get_config'](name=name, group_id=None, region=region, key=key,
keyid=keyid, profile=profile, vpc_id=vpc_id,
vpc_name=vpc_name)
if not sg:
ret['comment'] = '{0} security group configuration could not be retrieved.'.format(name)
ret['result'] = False
return ret
rules = _split_rules(rules)
if vpc_id or vpc_name:
for rule in rules:
_source_group_name = rule.get('source_group_name', None)
if _source_group_name:
_group_vpc_name = vpc_name
_group_vpc_id = vpc_id
_source_group_name_vpc = rule.get('source_group_name_vpc', None)
if _source_group_name_vpc:
_group_vpc_name = _source_group_name_vpc
_group_vpc_id = None
_group_id = __salt__['boto_secgroup.get_group_id'](
name=_source_group_name, vpc_id=_group_vpc_id, vpc_name=_group_vpc_name,
region=region, key=key, keyid=keyid, profile=profile
)
if not _group_id:
raise SaltInvocationError(
'source_group_name {0} does not map to a valid '
'source group id.'.format(_source_group_name)
)
rule['source_group_name'] = None
if _source_group_name_vpc:
rule.pop('source_group_name_vpc')
rule['source_group_group_id'] = _group_id
# rules = rules that exist in salt state
# sg['rules'] = that exist in present group
to_delete, to_create = _get_rule_changes(rules, sg['rules'])
to_delete = to_delete if delete_ingress_rules else []
if to_create or to_delete:
if __opts__['test']:
msg = """Security group {0} set to have rules modified.
To be created: {1}
To be deleted: {2}""".format(name, pprint.pformat(to_create),
pprint.pformat(to_delete))
ret['comment'] = msg
ret['result'] = None
return ret
if to_delete:
deleted = True
for rule in to_delete:
_deleted = __salt__['boto_secgroup.revoke'](
name, vpc_id=vpc_id, vpc_name=vpc_name, region=region,
key=key, keyid=keyid, profile=profile, **rule)
if not _deleted:
deleted = False
if deleted:
ret['comment'] = 'Removed rules on {0} security group.'.format(name)
else:
ret['comment'] = 'Failed to remove rules on {0} security group.'.format(name)
ret['result'] = False
if to_create:
created = True
for rule in to_create:
_created = __salt__['boto_secgroup.authorize'](
name, vpc_id=vpc_id, vpc_name=vpc_name, region=region,
key=key, keyid=keyid, profile=profile, **rule)
if not _created:
created = False
if created:
ret['comment'] = ' '.join([
ret['comment'],
'Created rules on {0} security group.'.format(name)
])
else:
ret['comment'] = ' '.join([
ret['comment'],
'Failed to create rules on {0} security group.'.format(name)
])
ret['result'] = False
ret['changes']['old'] = {'rules': sg['rules']}
sg = __salt__['boto_secgroup.get_config'](name=name, group_id=None, region=region, key=key,
keyid=keyid, profile=profile, vpc_id=vpc_id,
vpc_name=vpc_name)
ret['changes']['new'] = {'rules': sg['rules']}
return ret
def _rules_egress_present(name, rules_egress, delete_egress_rules=True, vpc_id=None,
vpc_name=None, region=None, key=None, keyid=None, profile=None):
'''
given a group name or group name and vpc_id (or vpc name):
1. get lists of desired rule changes (using _get_rule_changes)
2. authorize/create missing rules
3. if delete_egress_rules is True, delete/revoke non-requested rules
4. return 'old' and 'new' group rules
'''
ret = {'result': True, 'comment': '', 'changes': {}}
sg = __salt__['boto_secgroup.get_config'](name=name, group_id=None, region=region, key=key,
keyid=keyid, profile=profile, vpc_id=vpc_id,
vpc_name=vpc_name)
if not sg:
ret['comment'] = '{0} security group configuration could not be retrieved.'.format(name)
ret['result'] = False
return ret
rules_egress = _split_rules(rules_egress)
if vpc_id or vpc_name:
for rule in rules_egress:
_source_group_name = rule.get('source_group_name', None)
if _source_group_name:
_group_vpc_name = vpc_name
_group_vpc_id = vpc_id
_source_group_name_vpc = rule.get('source_group_name_vpc', None)
if _source_group_name_vpc:
_group_vpc_name = _source_group_name_vpc
_group_vpc_id = None
_group_id = __salt__['boto_secgroup.get_group_id'](
name=_source_group_name, vpc_id=_group_vpc_id, vpc_name=_group_vpc_name,
region=region, key=key, keyid=keyid, profile=profile
)
if not _group_id:
raise SaltInvocationError(
'source_group_name {0} does not map to a valid '
'source group id.'.format(_source_group_name)
)
rule['source_group_name'] = None
if _source_group_name_vpc:
rule.pop('source_group_name_vpc')
rule['source_group_group_id'] = _group_id
# rules_egress = rules that exist in salt state
# sg['rules_egress'] = that exist in present group
to_delete, to_create = _get_rule_changes(rules_egress, sg['rules_egress'])
to_delete = to_delete if delete_egress_rules else []
if to_create or to_delete:
if __opts__['test']:
msg = """Security group {0} set to have rules modified.
To be created: {1}
To be deleted: {2}""".format(name, pprint.pformat(to_create),
pprint.pformat(to_delete))
ret['comment'] = msg
ret['result'] = None
return ret
if to_delete:
deleted = True
for rule in to_delete:
_deleted = __salt__['boto_secgroup.revoke'](
name, vpc_id=vpc_id, vpc_name=vpc_name, region=region,
key=key, keyid=keyid, profile=profile, egress=True, **rule)
if not _deleted:
deleted = False
if deleted:
ret['comment'] = ' '.join([
ret['comment'],
'Removed egress rule on {0} security group.'.format(name)
])
else:
ret['comment'] = ' '.join([
ret['comment'],
'Failed to remove egress rule on {0} security group.'.format(name)
])
ret['result'] = False
if to_create:
created = True
for rule in to_create:
_created = __salt__['boto_secgroup.authorize'](
name, vpc_id=vpc_id, vpc_name=vpc_name, region=region,
key=key, keyid=keyid, profile=profile, egress=True, **rule)
if not _created:
created = False
if created:
ret['comment'] = ' '.join([
ret['comment'],
'Created egress rules on {0} security group.'.format(name)
])
else:
ret['comment'] = ' '.join([
ret['comment'],
'Failed to create egress rules on {0} security group.'.format(name)
])
ret['result'] = False
ret['changes']['old'] = {'rules_egress': sg['rules_egress']}
sg = __salt__['boto_secgroup.get_config'](name=name, group_id=None, region=region, key=key,
keyid=keyid, profile=profile, vpc_id=vpc_id,
vpc_name=vpc_name)
ret['changes']['new'] = {'rules_egress': sg['rules_egress']}
return ret
def absent(
name,
vpc_id=None,
vpc_name=None,
region=None,
key=None,
keyid=None,
profile=None):
'''
Ensure a security group with the specified name does not exist.
name
Name of the security group.
vpc_id
The ID of the VPC to remove the security group from, if any. Exclusive with vpc_name.
vpc_name
The name of the VPC to remove the security group from, if any. Exclusive with vpc_name.
.. versionadded:: 2016.3.0
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string)
that contains a dict with region, key and keyid.
.. versionadded:: 2016.3.0
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
sg = __salt__['boto_secgroup.get_config'](name=name, group_id=None, region=region, key=key,
keyid=keyid, profile=profile, vpc_id=vpc_id,
vpc_name=vpc_name)
if sg:
if __opts__['test']:
ret['comment'] = 'Security group {0} is set to be removed.'.format(name)
ret['result'] = None
return ret
deleted = __salt__['boto_secgroup.delete'](name=name, group_id=None, region=region, key=key,
keyid=keyid, profile=profile, vpc_id=vpc_id,
vpc_name=vpc_name)
if deleted:
ret['changes']['old'] = {'secgroup': sg}
ret['changes']['new'] = {'secgroup': None}
ret['comment'] = 'Security group {0} deleted.'.format(name)
else:
ret['result'] = False
ret['comment'] = 'Failed to delete {0} security group.'.format(name)
else:
ret['comment'] = '{0} security group does not exist.'.format(name)
return ret
def _tags_present(name, tags, vpc_id=None, vpc_name=None, region=None,
key=None, keyid=None, profile=None):
'''
helper function to validate tags are correct
'''
ret = {'result': True, 'comment': '', 'changes': {}}
if tags:
sg = __salt__['boto_secgroup.get_config'](name=name, group_id=None, region=region, key=key,
keyid=keyid, profile=profile, vpc_id=vpc_id,
vpc_name=vpc_name)
if not sg:
ret['comment'] = '{0} security group configuration could not be retrieved.'.format(name)
ret['result'] = False
return ret
tags_to_add = tags
tags_to_update = {}
tags_to_remove = []
if sg.get('tags'):
for existing_tag in sg['tags']:
if existing_tag not in tags:
if existing_tag not in tags_to_remove:
tags_to_remove.append(existing_tag)
else:
if tags[existing_tag] != sg['tags'][existing_tag]:
tags_to_update[existing_tag] = tags[existing_tag]
tags_to_add.pop(existing_tag)
if tags_to_remove:
if __opts__['test']:
msg = 'The following tag{0} set to be removed: {1}.'.format(
('s are' if len(tags_to_remove) > 1 else ' is'), ', '.join(tags_to_remove))
ret['comment'] = ' '.join([ret['comment'], msg])
ret['result'] = None
else:
temp_ret = __salt__['boto_secgroup.delete_tags'](tags_to_remove,
name=name,
group_id=None,
vpc_name=vpc_name,
vpc_id=vpc_id,
region=region,
key=key,
keyid=keyid,
profile=profile)
if not temp_ret:
ret['result'] = False
ret['comment'] = ' '.join([
ret['comment'],
'Error attempting to delete tags {0}.'.format(tags_to_remove)
])
return ret
if 'old' not in ret['changes']:
ret['changes'] = dictupdate.update(ret['changes'], {'old': {'tags': {}}})
for rem_tag in tags_to_remove:
ret['changes']['old']['tags'][rem_tag] = sg['tags'][rem_tag]
if tags_to_add or tags_to_update:
if __opts__['test']:
if tags_to_add:
msg = 'The following tag{0} set to be added: {1}.'.format(
('s are' if len(tags_to_add.keys()) > 1 else ' is'),
', '.join(tags_to_add.keys()))
ret['comment'] = ' '.join([ret['comment'], msg])
ret['result'] = None
if tags_to_update:
msg = 'The following tag {0} set to be updated: {1}.'.format(
('values are' if len(tags_to_update.keys()) > 1 else 'value is'),
', '.join(tags_to_update.keys()))
ret['comment'] = ' '.join([ret['comment'], msg])
ret['result'] = None
else:
all_tag_changes = dictupdate.update(tags_to_add, tags_to_update)
temp_ret = __salt__['boto_secgroup.set_tags'](all_tag_changes,
name=name,
group_id=None,
vpc_name=vpc_name,
vpc_id=vpc_id,
region=region,
key=key,
keyid=keyid,
profile=profile)
if not temp_ret:
ret['result'] = False
msg = 'Error attempting to set tags.'
ret['comment'] = ' '.join([ret['comment'], msg])
return ret
if 'old' not in ret['changes']:
ret['changes'] = dictupdate.update(ret['changes'], {'old': {'tags': {}}})
if 'new' not in ret['changes']:
ret['changes'] = dictupdate.update(ret['changes'], {'new': {'tags': {}}})
for tag in all_tag_changes:
ret['changes']['new']['tags'][tag] = tags[tag]
if 'tags' in sg:
if sg['tags']:
if tag in sg['tags']:
ret['changes']['old']['tags'][tag] = sg['tags'][tag]
if not tags_to_update and not tags_to_remove and not tags_to_add:
ret['comment'] = ' '.join([ret['comment'], 'Tags are already set.'])
return ret
|
saltstack/salt
|
salt/states/boto_secgroup.py
|
_security_group_present
|
python
|
def _security_group_present(name, description, vpc_id=None, vpc_name=None,
region=None, key=None, keyid=None, profile=None):
'''
given a group name or a group name and vpc id (or vpc name):
1. determine if the group exists
2. if the group does not exist, creates the group
3. return the group's configuration and any changes made
'''
ret = {'result': True, 'comment': '', 'changes': {}}
exists = __salt__['boto_secgroup.exists'](name, region, key, keyid,
profile, vpc_id, vpc_name)
if not exists:
if __opts__['test']:
ret['comment'] = 'Security group {0} is set to be created.'.format(name)
ret['result'] = None
return ret
created = __salt__['boto_secgroup.create'](name=name, description=description,
vpc_id=vpc_id, vpc_name=vpc_name,
region=region, key=key, keyid=keyid,
profile=profile)
if created:
ret['changes']['old'] = {'secgroup': None}
sg = __salt__['boto_secgroup.get_config'](name=name, group_id=None, region=region, key=key,
keyid=keyid, profile=profile, vpc_id=vpc_id,
vpc_name=vpc_name)
ret['changes']['new'] = {'secgroup': sg}
ret['comment'] = 'Security group {0} created.'.format(name)
else:
ret['result'] = False
ret['comment'] = 'Failed to create {0} security group.'.format(name)
else:
ret['comment'] = 'Security group {0} present.'.format(name)
return ret
|
given a group name or a group name and vpc id (or vpc name):
1. determine if the group exists
2. if the group does not exist, creates the group
3. return the group's configuration and any changes made
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_secgroup.py#L238-L270
| null |
# -*- coding: utf-8 -*-
'''
Manage Security Groups
======================
.. versionadded:: 2014.7.0
Create and destroy Security Groups. Be aware that this interacts with Amazon's
services, and so may incur charges.
This module uses ``boto``, which can be installed via package, or pip.
This module accepts explicit EC2 credentials but can also utilize
IAM roles assigned to the instance through Instance Profiles. Dynamic
credentials are then automatically obtained from AWS API and no further
configuration is necessary. More information available `here
<http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html>`_.
If IAM roles are not used you need to specify them either in a pillar file or
in the minion's config file:
.. code-block:: yaml
secgroup.keyid: GKTADJGHEIQSXMKKRBJ08H
secgroup.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
It's also possible to specify ``key``, ``keyid`` and ``region`` via a profile, either
passed in as a dict, or as a string to pull from pillars or minion config:
.. code-block:: yaml
myprofile:
keyid: GKTADJGHEIQSXMKKRBJ08H
key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
region: us-east-1
.. code-block:: yaml
Ensure mysecgroup exists:
boto_secgroup.present:
- name: mysecgroup
- description: My security group
- vpc_name: myvpc
- rules:
- ip_protocol: tcp
from_port: 80
to_port: 80
cidr_ip:
- 10.0.0.0/8
- 192.168.0.0/16
- ip_protocol: tcp
from_port: 8080
to_port: 8090
cidr_ip:
- 10.0.0.0/8
- 192.168.0.0/16
- ip_protocol: icmp
from_port: -1
to_port: -1
source_group_name: mysecgroup
- ip_protocol: tcp
from_port: 8080
to_port: 8080
source_group_name: MyOtherSecGroup
source_group_name_vpc: MyPeeredVPC
- rules_egress:
- ip_protocol: all
from_port: -1
to_port: -1
cidr_ip:
- 10.0.0.0/8
- 192.168.0.0/16
- tags:
SomeTag: 'My Tag Value'
SomeOtherTag: 'Other Tag Value'
- region: us-east-1
- keyid: GKTADJGHEIQSXMKKRBJ08H
- key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
# Using a profile from pillars
Ensure mysecgroup exists:
boto_secgroup.present:
- name: mysecgroup
- description: My security group
- profile: myprofile
# Passing in a profile
Ensure mysecgroup exists:
boto_secgroup.present:
- name: mysecgroup
- description: My security group
- profile:
keyid: GKTADJGHEIQSXMKKRBJ08H
key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
region: us-east-1
.. note::
When using the ``profile`` parameter and ``region`` is set outside of
the profile group, region is ignored and a default region will be used.
If ``region`` is missing from the ``profile`` data set, ``us-east-1``
will be used as the default region.
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import Python libs
import logging
import pprint
# Import salt libs
import salt.utils.dictupdate as dictupdate
from salt.exceptions import SaltInvocationError
from salt.ext import six
log = logging.getLogger(__name__)
def __virtual__():
'''
Only load if boto is available.
'''
return 'boto_secgroup' if 'boto_secgroup.exists' in __salt__ else False
def present(
name,
description,
vpc_id=None,
vpc_name=None,
rules=None,
rules_egress=None,
delete_ingress_rules=True,
delete_egress_rules=True,
region=None,
key=None,
keyid=None,
profile=None,
tags=None):
'''
Ensure the security group exists with the specified rules.
name
Name of the security group.
description
A description of this security group.
vpc_id
The ID of the VPC to create the security group in, if any. Exclusive with vpc_name.
vpc_name
The name of the VPC to create the security group in, if any. Exclusive with vpc_id.
.. versionadded:: 2016.3.0
.. versionadded:: 2015.8.2
rules
A list of ingress rule dicts. If not specified, ``rules=None``,
the ingress rules will be unmanaged. If set to an empty list, ``[]``,
then all ingress rules will be removed.
rules_egress
A list of egress rule dicts. If not specified, ``rules_egress=None``,
the egress rules will be unmanaged. If set to an empty list, ``[]``,
then all egress rules will be removed.
delete_ingress_rules
Some tools (EMR comes to mind) insist on adding rules on-the-fly, which
salt will happily remove on the next run. Set this param to False to
avoid deleting rules which were added outside of salt.
delete_egress_rules
Some tools (EMR comes to mind) insist on adding rules on-the-fly, which
salt will happily remove on the next run. Set this param to False to
avoid deleting rules which were added outside of salt.
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string)
that contains a dict with region, key, and keyid.
tags
List of key:value pairs of tags to set on the security group
.. versionadded:: 2016.3.0
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
_ret = _security_group_present(name, description, vpc_id=vpc_id,
vpc_name=vpc_name, region=region,
key=key, keyid=keyid, profile=profile)
ret['changes'] = _ret['changes']
ret['comment'] = ' '.join([ret['comment'], _ret['comment']])
if not _ret['result']:
ret['result'] = _ret['result']
if ret['result'] is False:
return ret
elif ret['result'] is None:
return ret
if rules is not None:
_ret = _rules_present(name, rules, delete_ingress_rules, vpc_id=vpc_id,
vpc_name=vpc_name, region=region, key=key,
keyid=keyid, profile=profile)
ret['changes'] = dictupdate.update(ret['changes'], _ret['changes'])
ret['comment'] = ' '.join([ret['comment'], _ret['comment']])
if not _ret['result']:
ret['result'] = _ret['result']
if rules_egress is not None:
_ret = _rules_egress_present(name, rules_egress, delete_egress_rules,
vpc_id=vpc_id, vpc_name=vpc_name,
region=region, key=key, keyid=keyid,
profile=profile)
ret['changes'] = dictupdate.update(ret['changes'], _ret['changes'])
ret['comment'] = ' '.join([ret['comment'], _ret['comment']])
if not _ret['result']:
ret['result'] = _ret['result']
_ret = _tags_present(
name=name, tags=tags, vpc_id=vpc_id, vpc_name=vpc_name,
region=region, key=key, keyid=keyid, profile=profile
)
ret['changes'] = dictupdate.update(ret['changes'], _ret['changes'])
ret['comment'] = ' '.join([ret['comment'], _ret['comment']])
if not _ret['result']:
ret['result'] = _ret['result']
return ret
def _split_rules(rules):
'''
Split rules with lists into individual rules.
We accept some attributes as lists or strings. The data we get back from
the execution module lists rules as individual rules. We need to split the
provided rules into individual rules to compare them.
'''
split = []
for rule in rules:
cidr_ip = rule.get('cidr_ip')
group_name = rule.get('source_group_name')
group_id = rule.get('source_group_group_id')
if cidr_ip and not isinstance(cidr_ip, six.string_types):
for ip in cidr_ip:
_rule = rule.copy()
_rule['cidr_ip'] = ip
split.append(_rule)
elif group_name and not isinstance(group_name, six.string_types):
for name in group_name:
_rule = rule.copy()
_rule['source_group_name'] = name
split.append(_rule)
elif group_id and not isinstance(group_id, six.string_types):
for _id in group_id:
_rule = rule.copy()
_rule['source_group_group_id'] = _id
split.append(_rule)
else:
split.append(rule)
return split
def _check_rule(rule, _rule):
'''
Check to see if two rules are the same. Needed to compare rules fetched
from boto, since they may not completely match rules defined in sls files
but may be functionally equivalent.
'''
# We need to alter what Boto returns if no ports are specified
# so that we can compare rules fairly.
#
# Boto returns None for from_port and to_port where we're required
# to pass in "-1" instead.
if _rule.get('from_port') is None:
_rule['from_port'] = -1
if _rule.get('to_port') is None:
_rule['to_port'] = -1
if (rule['ip_protocol'] == _rule['ip_protocol'] and
six.text_type(rule['from_port']) == six.text_type(_rule['from_port']) and
six.text_type(rule['to_port']) == six.text_type(_rule['to_port'])):
_cidr_ip = _rule.get('cidr_ip')
if _cidr_ip and _cidr_ip == rule.get('cidr_ip'):
return True
_owner_id = _rule.get('source_group_owner_id')
if _owner_id and _owner_id == rule.get('source_group_owner_id'):
return True
_group_id = _rule.get('source_group_group_id')
if _group_id and _group_id == rule.get('source_group_group_id'):
return True
_group_name = _rule.get('source_group_name')
if _group_name and _group_id == rule.get('source_group_name'):
return True
return False
def _get_rule_changes(rules, _rules):
'''
given a list of desired rules (rules) and existing rules (_rules) return
a list of rules to delete (to_delete) and to create (to_create)
'''
to_delete = []
to_create = []
# for each rule in state file
# 1. validate rule
# 2. determine if rule exists in existing security group rules
for rule in rules:
try:
ip_protocol = six.text_type(rule.get('ip_protocol'))
except KeyError:
raise SaltInvocationError('ip_protocol, to_port, and from_port are'
' required arguments for security group'
' rules.')
supported_protocols = ['tcp', '6', 6, 'udp', '17', 17, 'icmp', '1', 1,
'all', '-1', -1]
if ip_protocol not in supported_protocols and (not
'{0}'.format(ip_protocol).isdigit() or int(ip_protocol) > 255):
raise SaltInvocationError(
'Invalid ip_protocol {0} specified in security group rule.'.format(ip_protocol))
# For the 'all' case, we need to change the protocol name to '-1'.
if ip_protocol == 'all':
rule['ip_protocol'] = '-1'
cidr_ip = rule.get('cidr_ip', None)
group_name = rule.get('source_group_name', None)
group_id = rule.get('source_group_group_id', None)
if cidr_ip and (group_id or group_name):
raise SaltInvocationError('cidr_ip and source groups can not both'
' be specified in security group rules.')
if group_id and group_name:
raise SaltInvocationError('Either source_group_group_id or'
' source_group_name can be specified in'
' security group rules, but not both.')
if not (cidr_ip or group_id or group_name):
raise SaltInvocationError('cidr_ip, source_group_group_id, or'
' source_group_name must be provided for'
' security group rules.')
rule_found = False
# for each rule in existing security group ruleset determine if
# new rule exists
for _rule in _rules:
if _check_rule(rule, _rule):
rule_found = True
break
if not rule_found:
to_create.append(rule)
# for each rule in existing security group configuration
# 1. determine if rules needed to be deleted
for _rule in _rules:
rule_found = False
for rule in rules:
if _check_rule(rule, _rule):
rule_found = True
break
if not rule_found:
# Can only supply name or id, not both. Since we're deleting
# entries, it doesn't matter which we pick.
_rule.pop('source_group_name', None)
to_delete.append(_rule)
log.debug('Rules to be deleted: %s', to_delete)
log.debug('Rules to be created: %s', to_create)
return (to_delete, to_create)
def _rules_present(name, rules, delete_ingress_rules=True, vpc_id=None,
vpc_name=None, region=None, key=None, keyid=None, profile=None):
'''
given a group name or group name and vpc_id (or vpc name):
1. get lists of desired rule changes (using _get_rule_changes)
2. authorize/create rules missing rules
3. if delete_ingress_rules is True, delete/revoke non-requested rules
4. return 'old' and 'new' group rules
'''
ret = {'result': True, 'comment': '', 'changes': {}}
sg = __salt__['boto_secgroup.get_config'](name=name, group_id=None, region=region, key=key,
keyid=keyid, profile=profile, vpc_id=vpc_id,
vpc_name=vpc_name)
if not sg:
ret['comment'] = '{0} security group configuration could not be retrieved.'.format(name)
ret['result'] = False
return ret
rules = _split_rules(rules)
if vpc_id or vpc_name:
for rule in rules:
_source_group_name = rule.get('source_group_name', None)
if _source_group_name:
_group_vpc_name = vpc_name
_group_vpc_id = vpc_id
_source_group_name_vpc = rule.get('source_group_name_vpc', None)
if _source_group_name_vpc:
_group_vpc_name = _source_group_name_vpc
_group_vpc_id = None
_group_id = __salt__['boto_secgroup.get_group_id'](
name=_source_group_name, vpc_id=_group_vpc_id, vpc_name=_group_vpc_name,
region=region, key=key, keyid=keyid, profile=profile
)
if not _group_id:
raise SaltInvocationError(
'source_group_name {0} does not map to a valid '
'source group id.'.format(_source_group_name)
)
rule['source_group_name'] = None
if _source_group_name_vpc:
rule.pop('source_group_name_vpc')
rule['source_group_group_id'] = _group_id
# rules = rules that exist in salt state
# sg['rules'] = that exist in present group
to_delete, to_create = _get_rule_changes(rules, sg['rules'])
to_delete = to_delete if delete_ingress_rules else []
if to_create or to_delete:
if __opts__['test']:
msg = """Security group {0} set to have rules modified.
To be created: {1}
To be deleted: {2}""".format(name, pprint.pformat(to_create),
pprint.pformat(to_delete))
ret['comment'] = msg
ret['result'] = None
return ret
if to_delete:
deleted = True
for rule in to_delete:
_deleted = __salt__['boto_secgroup.revoke'](
name, vpc_id=vpc_id, vpc_name=vpc_name, region=region,
key=key, keyid=keyid, profile=profile, **rule)
if not _deleted:
deleted = False
if deleted:
ret['comment'] = 'Removed rules on {0} security group.'.format(name)
else:
ret['comment'] = 'Failed to remove rules on {0} security group.'.format(name)
ret['result'] = False
if to_create:
created = True
for rule in to_create:
_created = __salt__['boto_secgroup.authorize'](
name, vpc_id=vpc_id, vpc_name=vpc_name, region=region,
key=key, keyid=keyid, profile=profile, **rule)
if not _created:
created = False
if created:
ret['comment'] = ' '.join([
ret['comment'],
'Created rules on {0} security group.'.format(name)
])
else:
ret['comment'] = ' '.join([
ret['comment'],
'Failed to create rules on {0} security group.'.format(name)
])
ret['result'] = False
ret['changes']['old'] = {'rules': sg['rules']}
sg = __salt__['boto_secgroup.get_config'](name=name, group_id=None, region=region, key=key,
keyid=keyid, profile=profile, vpc_id=vpc_id,
vpc_name=vpc_name)
ret['changes']['new'] = {'rules': sg['rules']}
return ret
def _rules_egress_present(name, rules_egress, delete_egress_rules=True, vpc_id=None,
vpc_name=None, region=None, key=None, keyid=None, profile=None):
'''
given a group name or group name and vpc_id (or vpc name):
1. get lists of desired rule changes (using _get_rule_changes)
2. authorize/create missing rules
3. if delete_egress_rules is True, delete/revoke non-requested rules
4. return 'old' and 'new' group rules
'''
ret = {'result': True, 'comment': '', 'changes': {}}
sg = __salt__['boto_secgroup.get_config'](name=name, group_id=None, region=region, key=key,
keyid=keyid, profile=profile, vpc_id=vpc_id,
vpc_name=vpc_name)
if not sg:
ret['comment'] = '{0} security group configuration could not be retrieved.'.format(name)
ret['result'] = False
return ret
rules_egress = _split_rules(rules_egress)
if vpc_id or vpc_name:
for rule in rules_egress:
_source_group_name = rule.get('source_group_name', None)
if _source_group_name:
_group_vpc_name = vpc_name
_group_vpc_id = vpc_id
_source_group_name_vpc = rule.get('source_group_name_vpc', None)
if _source_group_name_vpc:
_group_vpc_name = _source_group_name_vpc
_group_vpc_id = None
_group_id = __salt__['boto_secgroup.get_group_id'](
name=_source_group_name, vpc_id=_group_vpc_id, vpc_name=_group_vpc_name,
region=region, key=key, keyid=keyid, profile=profile
)
if not _group_id:
raise SaltInvocationError(
'source_group_name {0} does not map to a valid '
'source group id.'.format(_source_group_name)
)
rule['source_group_name'] = None
if _source_group_name_vpc:
rule.pop('source_group_name_vpc')
rule['source_group_group_id'] = _group_id
# rules_egress = rules that exist in salt state
# sg['rules_egress'] = that exist in present group
to_delete, to_create = _get_rule_changes(rules_egress, sg['rules_egress'])
to_delete = to_delete if delete_egress_rules else []
if to_create or to_delete:
if __opts__['test']:
msg = """Security group {0} set to have rules modified.
To be created: {1}
To be deleted: {2}""".format(name, pprint.pformat(to_create),
pprint.pformat(to_delete))
ret['comment'] = msg
ret['result'] = None
return ret
if to_delete:
deleted = True
for rule in to_delete:
_deleted = __salt__['boto_secgroup.revoke'](
name, vpc_id=vpc_id, vpc_name=vpc_name, region=region,
key=key, keyid=keyid, profile=profile, egress=True, **rule)
if not _deleted:
deleted = False
if deleted:
ret['comment'] = ' '.join([
ret['comment'],
'Removed egress rule on {0} security group.'.format(name)
])
else:
ret['comment'] = ' '.join([
ret['comment'],
'Failed to remove egress rule on {0} security group.'.format(name)
])
ret['result'] = False
if to_create:
created = True
for rule in to_create:
_created = __salt__['boto_secgroup.authorize'](
name, vpc_id=vpc_id, vpc_name=vpc_name, region=region,
key=key, keyid=keyid, profile=profile, egress=True, **rule)
if not _created:
created = False
if created:
ret['comment'] = ' '.join([
ret['comment'],
'Created egress rules on {0} security group.'.format(name)
])
else:
ret['comment'] = ' '.join([
ret['comment'],
'Failed to create egress rules on {0} security group.'.format(name)
])
ret['result'] = False
ret['changes']['old'] = {'rules_egress': sg['rules_egress']}
sg = __salt__['boto_secgroup.get_config'](name=name, group_id=None, region=region, key=key,
keyid=keyid, profile=profile, vpc_id=vpc_id,
vpc_name=vpc_name)
ret['changes']['new'] = {'rules_egress': sg['rules_egress']}
return ret
def absent(
name,
vpc_id=None,
vpc_name=None,
region=None,
key=None,
keyid=None,
profile=None):
'''
Ensure a security group with the specified name does not exist.
name
Name of the security group.
vpc_id
The ID of the VPC to remove the security group from, if any. Exclusive with vpc_name.
vpc_name
The name of the VPC to remove the security group from, if any. Exclusive with vpc_name.
.. versionadded:: 2016.3.0
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string)
that contains a dict with region, key and keyid.
.. versionadded:: 2016.3.0
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
sg = __salt__['boto_secgroup.get_config'](name=name, group_id=None, region=region, key=key,
keyid=keyid, profile=profile, vpc_id=vpc_id,
vpc_name=vpc_name)
if sg:
if __opts__['test']:
ret['comment'] = 'Security group {0} is set to be removed.'.format(name)
ret['result'] = None
return ret
deleted = __salt__['boto_secgroup.delete'](name=name, group_id=None, region=region, key=key,
keyid=keyid, profile=profile, vpc_id=vpc_id,
vpc_name=vpc_name)
if deleted:
ret['changes']['old'] = {'secgroup': sg}
ret['changes']['new'] = {'secgroup': None}
ret['comment'] = 'Security group {0} deleted.'.format(name)
else:
ret['result'] = False
ret['comment'] = 'Failed to delete {0} security group.'.format(name)
else:
ret['comment'] = '{0} security group does not exist.'.format(name)
return ret
def _tags_present(name, tags, vpc_id=None, vpc_name=None, region=None,
key=None, keyid=None, profile=None):
'''
helper function to validate tags are correct
'''
ret = {'result': True, 'comment': '', 'changes': {}}
if tags:
sg = __salt__['boto_secgroup.get_config'](name=name, group_id=None, region=region, key=key,
keyid=keyid, profile=profile, vpc_id=vpc_id,
vpc_name=vpc_name)
if not sg:
ret['comment'] = '{0} security group configuration could not be retrieved.'.format(name)
ret['result'] = False
return ret
tags_to_add = tags
tags_to_update = {}
tags_to_remove = []
if sg.get('tags'):
for existing_tag in sg['tags']:
if existing_tag not in tags:
if existing_tag not in tags_to_remove:
tags_to_remove.append(existing_tag)
else:
if tags[existing_tag] != sg['tags'][existing_tag]:
tags_to_update[existing_tag] = tags[existing_tag]
tags_to_add.pop(existing_tag)
if tags_to_remove:
if __opts__['test']:
msg = 'The following tag{0} set to be removed: {1}.'.format(
('s are' if len(tags_to_remove) > 1 else ' is'), ', '.join(tags_to_remove))
ret['comment'] = ' '.join([ret['comment'], msg])
ret['result'] = None
else:
temp_ret = __salt__['boto_secgroup.delete_tags'](tags_to_remove,
name=name,
group_id=None,
vpc_name=vpc_name,
vpc_id=vpc_id,
region=region,
key=key,
keyid=keyid,
profile=profile)
if not temp_ret:
ret['result'] = False
ret['comment'] = ' '.join([
ret['comment'],
'Error attempting to delete tags {0}.'.format(tags_to_remove)
])
return ret
if 'old' not in ret['changes']:
ret['changes'] = dictupdate.update(ret['changes'], {'old': {'tags': {}}})
for rem_tag in tags_to_remove:
ret['changes']['old']['tags'][rem_tag] = sg['tags'][rem_tag]
if tags_to_add or tags_to_update:
if __opts__['test']:
if tags_to_add:
msg = 'The following tag{0} set to be added: {1}.'.format(
('s are' if len(tags_to_add.keys()) > 1 else ' is'),
', '.join(tags_to_add.keys()))
ret['comment'] = ' '.join([ret['comment'], msg])
ret['result'] = None
if tags_to_update:
msg = 'The following tag {0} set to be updated: {1}.'.format(
('values are' if len(tags_to_update.keys()) > 1 else 'value is'),
', '.join(tags_to_update.keys()))
ret['comment'] = ' '.join([ret['comment'], msg])
ret['result'] = None
else:
all_tag_changes = dictupdate.update(tags_to_add, tags_to_update)
temp_ret = __salt__['boto_secgroup.set_tags'](all_tag_changes,
name=name,
group_id=None,
vpc_name=vpc_name,
vpc_id=vpc_id,
region=region,
key=key,
keyid=keyid,
profile=profile)
if not temp_ret:
ret['result'] = False
msg = 'Error attempting to set tags.'
ret['comment'] = ' '.join([ret['comment'], msg])
return ret
if 'old' not in ret['changes']:
ret['changes'] = dictupdate.update(ret['changes'], {'old': {'tags': {}}})
if 'new' not in ret['changes']:
ret['changes'] = dictupdate.update(ret['changes'], {'new': {'tags': {}}})
for tag in all_tag_changes:
ret['changes']['new']['tags'][tag] = tags[tag]
if 'tags' in sg:
if sg['tags']:
if tag in sg['tags']:
ret['changes']['old']['tags'][tag] = sg['tags'][tag]
if not tags_to_update and not tags_to_remove and not tags_to_add:
ret['comment'] = ' '.join([ret['comment'], 'Tags are already set.'])
return ret
|
saltstack/salt
|
salt/states/boto_secgroup.py
|
_split_rules
|
python
|
def _split_rules(rules):
'''
Split rules with lists into individual rules.
We accept some attributes as lists or strings. The data we get back from
the execution module lists rules as individual rules. We need to split the
provided rules into individual rules to compare them.
'''
split = []
for rule in rules:
cidr_ip = rule.get('cidr_ip')
group_name = rule.get('source_group_name')
group_id = rule.get('source_group_group_id')
if cidr_ip and not isinstance(cidr_ip, six.string_types):
for ip in cidr_ip:
_rule = rule.copy()
_rule['cidr_ip'] = ip
split.append(_rule)
elif group_name and not isinstance(group_name, six.string_types):
for name in group_name:
_rule = rule.copy()
_rule['source_group_name'] = name
split.append(_rule)
elif group_id and not isinstance(group_id, six.string_types):
for _id in group_id:
_rule = rule.copy()
_rule['source_group_group_id'] = _id
split.append(_rule)
else:
split.append(rule)
return split
|
Split rules with lists into individual rules.
We accept some attributes as lists or strings. The data we get back from
the execution module lists rules as individual rules. We need to split the
provided rules into individual rules to compare them.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_secgroup.py#L273-L303
| null |
# -*- coding: utf-8 -*-
'''
Manage Security Groups
======================
.. versionadded:: 2014.7.0
Create and destroy Security Groups. Be aware that this interacts with Amazon's
services, and so may incur charges.
This module uses ``boto``, which can be installed via package, or pip.
This module accepts explicit EC2 credentials but can also utilize
IAM roles assigned to the instance through Instance Profiles. Dynamic
credentials are then automatically obtained from AWS API and no further
configuration is necessary. More information available `here
<http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html>`_.
If IAM roles are not used you need to specify them either in a pillar file or
in the minion's config file:
.. code-block:: yaml
secgroup.keyid: GKTADJGHEIQSXMKKRBJ08H
secgroup.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
It's also possible to specify ``key``, ``keyid`` and ``region`` via a profile, either
passed in as a dict, or as a string to pull from pillars or minion config:
.. code-block:: yaml
myprofile:
keyid: GKTADJGHEIQSXMKKRBJ08H
key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
region: us-east-1
.. code-block:: yaml
Ensure mysecgroup exists:
boto_secgroup.present:
- name: mysecgroup
- description: My security group
- vpc_name: myvpc
- rules:
- ip_protocol: tcp
from_port: 80
to_port: 80
cidr_ip:
- 10.0.0.0/8
- 192.168.0.0/16
- ip_protocol: tcp
from_port: 8080
to_port: 8090
cidr_ip:
- 10.0.0.0/8
- 192.168.0.0/16
- ip_protocol: icmp
from_port: -1
to_port: -1
source_group_name: mysecgroup
- ip_protocol: tcp
from_port: 8080
to_port: 8080
source_group_name: MyOtherSecGroup
source_group_name_vpc: MyPeeredVPC
- rules_egress:
- ip_protocol: all
from_port: -1
to_port: -1
cidr_ip:
- 10.0.0.0/8
- 192.168.0.0/16
- tags:
SomeTag: 'My Tag Value'
SomeOtherTag: 'Other Tag Value'
- region: us-east-1
- keyid: GKTADJGHEIQSXMKKRBJ08H
- key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
# Using a profile from pillars
Ensure mysecgroup exists:
boto_secgroup.present:
- name: mysecgroup
- description: My security group
- profile: myprofile
# Passing in a profile
Ensure mysecgroup exists:
boto_secgroup.present:
- name: mysecgroup
- description: My security group
- profile:
keyid: GKTADJGHEIQSXMKKRBJ08H
key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
region: us-east-1
.. note::
When using the ``profile`` parameter and ``region`` is set outside of
the profile group, region is ignored and a default region will be used.
If ``region`` is missing from the ``profile`` data set, ``us-east-1``
will be used as the default region.
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import Python libs
import logging
import pprint
# Import salt libs
import salt.utils.dictupdate as dictupdate
from salt.exceptions import SaltInvocationError
from salt.ext import six
log = logging.getLogger(__name__)
def __virtual__():
'''
Only load if boto is available.
'''
return 'boto_secgroup' if 'boto_secgroup.exists' in __salt__ else False
def present(
name,
description,
vpc_id=None,
vpc_name=None,
rules=None,
rules_egress=None,
delete_ingress_rules=True,
delete_egress_rules=True,
region=None,
key=None,
keyid=None,
profile=None,
tags=None):
'''
Ensure the security group exists with the specified rules.
name
Name of the security group.
description
A description of this security group.
vpc_id
The ID of the VPC to create the security group in, if any. Exclusive with vpc_name.
vpc_name
The name of the VPC to create the security group in, if any. Exclusive with vpc_id.
.. versionadded:: 2016.3.0
.. versionadded:: 2015.8.2
rules
A list of ingress rule dicts. If not specified, ``rules=None``,
the ingress rules will be unmanaged. If set to an empty list, ``[]``,
then all ingress rules will be removed.
rules_egress
A list of egress rule dicts. If not specified, ``rules_egress=None``,
the egress rules will be unmanaged. If set to an empty list, ``[]``,
then all egress rules will be removed.
delete_ingress_rules
Some tools (EMR comes to mind) insist on adding rules on-the-fly, which
salt will happily remove on the next run. Set this param to False to
avoid deleting rules which were added outside of salt.
delete_egress_rules
Some tools (EMR comes to mind) insist on adding rules on-the-fly, which
salt will happily remove on the next run. Set this param to False to
avoid deleting rules which were added outside of salt.
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string)
that contains a dict with region, key, and keyid.
tags
List of key:value pairs of tags to set on the security group
.. versionadded:: 2016.3.0
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
_ret = _security_group_present(name, description, vpc_id=vpc_id,
vpc_name=vpc_name, region=region,
key=key, keyid=keyid, profile=profile)
ret['changes'] = _ret['changes']
ret['comment'] = ' '.join([ret['comment'], _ret['comment']])
if not _ret['result']:
ret['result'] = _ret['result']
if ret['result'] is False:
return ret
elif ret['result'] is None:
return ret
if rules is not None:
_ret = _rules_present(name, rules, delete_ingress_rules, vpc_id=vpc_id,
vpc_name=vpc_name, region=region, key=key,
keyid=keyid, profile=profile)
ret['changes'] = dictupdate.update(ret['changes'], _ret['changes'])
ret['comment'] = ' '.join([ret['comment'], _ret['comment']])
if not _ret['result']:
ret['result'] = _ret['result']
if rules_egress is not None:
_ret = _rules_egress_present(name, rules_egress, delete_egress_rules,
vpc_id=vpc_id, vpc_name=vpc_name,
region=region, key=key, keyid=keyid,
profile=profile)
ret['changes'] = dictupdate.update(ret['changes'], _ret['changes'])
ret['comment'] = ' '.join([ret['comment'], _ret['comment']])
if not _ret['result']:
ret['result'] = _ret['result']
_ret = _tags_present(
name=name, tags=tags, vpc_id=vpc_id, vpc_name=vpc_name,
region=region, key=key, keyid=keyid, profile=profile
)
ret['changes'] = dictupdate.update(ret['changes'], _ret['changes'])
ret['comment'] = ' '.join([ret['comment'], _ret['comment']])
if not _ret['result']:
ret['result'] = _ret['result']
return ret
def _security_group_present(name, description, vpc_id=None, vpc_name=None,
region=None, key=None, keyid=None, profile=None):
'''
given a group name or a group name and vpc id (or vpc name):
1. determine if the group exists
2. if the group does not exist, creates the group
3. return the group's configuration and any changes made
'''
ret = {'result': True, 'comment': '', 'changes': {}}
exists = __salt__['boto_secgroup.exists'](name, region, key, keyid,
profile, vpc_id, vpc_name)
if not exists:
if __opts__['test']:
ret['comment'] = 'Security group {0} is set to be created.'.format(name)
ret['result'] = None
return ret
created = __salt__['boto_secgroup.create'](name=name, description=description,
vpc_id=vpc_id, vpc_name=vpc_name,
region=region, key=key, keyid=keyid,
profile=profile)
if created:
ret['changes']['old'] = {'secgroup': None}
sg = __salt__['boto_secgroup.get_config'](name=name, group_id=None, region=region, key=key,
keyid=keyid, profile=profile, vpc_id=vpc_id,
vpc_name=vpc_name)
ret['changes']['new'] = {'secgroup': sg}
ret['comment'] = 'Security group {0} created.'.format(name)
else:
ret['result'] = False
ret['comment'] = 'Failed to create {0} security group.'.format(name)
else:
ret['comment'] = 'Security group {0} present.'.format(name)
return ret
def _check_rule(rule, _rule):
'''
Check to see if two rules are the same. Needed to compare rules fetched
from boto, since they may not completely match rules defined in sls files
but may be functionally equivalent.
'''
# We need to alter what Boto returns if no ports are specified
# so that we can compare rules fairly.
#
# Boto returns None for from_port and to_port where we're required
# to pass in "-1" instead.
if _rule.get('from_port') is None:
_rule['from_port'] = -1
if _rule.get('to_port') is None:
_rule['to_port'] = -1
if (rule['ip_protocol'] == _rule['ip_protocol'] and
six.text_type(rule['from_port']) == six.text_type(_rule['from_port']) and
six.text_type(rule['to_port']) == six.text_type(_rule['to_port'])):
_cidr_ip = _rule.get('cidr_ip')
if _cidr_ip and _cidr_ip == rule.get('cidr_ip'):
return True
_owner_id = _rule.get('source_group_owner_id')
if _owner_id and _owner_id == rule.get('source_group_owner_id'):
return True
_group_id = _rule.get('source_group_group_id')
if _group_id and _group_id == rule.get('source_group_group_id'):
return True
_group_name = _rule.get('source_group_name')
if _group_name and _group_id == rule.get('source_group_name'):
return True
return False
def _get_rule_changes(rules, _rules):
'''
given a list of desired rules (rules) and existing rules (_rules) return
a list of rules to delete (to_delete) and to create (to_create)
'''
to_delete = []
to_create = []
# for each rule in state file
# 1. validate rule
# 2. determine if rule exists in existing security group rules
for rule in rules:
try:
ip_protocol = six.text_type(rule.get('ip_protocol'))
except KeyError:
raise SaltInvocationError('ip_protocol, to_port, and from_port are'
' required arguments for security group'
' rules.')
supported_protocols = ['tcp', '6', 6, 'udp', '17', 17, 'icmp', '1', 1,
'all', '-1', -1]
if ip_protocol not in supported_protocols and (not
'{0}'.format(ip_protocol).isdigit() or int(ip_protocol) > 255):
raise SaltInvocationError(
'Invalid ip_protocol {0} specified in security group rule.'.format(ip_protocol))
# For the 'all' case, we need to change the protocol name to '-1'.
if ip_protocol == 'all':
rule['ip_protocol'] = '-1'
cidr_ip = rule.get('cidr_ip', None)
group_name = rule.get('source_group_name', None)
group_id = rule.get('source_group_group_id', None)
if cidr_ip and (group_id or group_name):
raise SaltInvocationError('cidr_ip and source groups can not both'
' be specified in security group rules.')
if group_id and group_name:
raise SaltInvocationError('Either source_group_group_id or'
' source_group_name can be specified in'
' security group rules, but not both.')
if not (cidr_ip or group_id or group_name):
raise SaltInvocationError('cidr_ip, source_group_group_id, or'
' source_group_name must be provided for'
' security group rules.')
rule_found = False
# for each rule in existing security group ruleset determine if
# new rule exists
for _rule in _rules:
if _check_rule(rule, _rule):
rule_found = True
break
if not rule_found:
to_create.append(rule)
# for each rule in existing security group configuration
# 1. determine if rules needed to be deleted
for _rule in _rules:
rule_found = False
for rule in rules:
if _check_rule(rule, _rule):
rule_found = True
break
if not rule_found:
# Can only supply name or id, not both. Since we're deleting
# entries, it doesn't matter which we pick.
_rule.pop('source_group_name', None)
to_delete.append(_rule)
log.debug('Rules to be deleted: %s', to_delete)
log.debug('Rules to be created: %s', to_create)
return (to_delete, to_create)
def _rules_present(name, rules, delete_ingress_rules=True, vpc_id=None,
vpc_name=None, region=None, key=None, keyid=None, profile=None):
'''
given a group name or group name and vpc_id (or vpc name):
1. get lists of desired rule changes (using _get_rule_changes)
2. authorize/create rules missing rules
3. if delete_ingress_rules is True, delete/revoke non-requested rules
4. return 'old' and 'new' group rules
'''
ret = {'result': True, 'comment': '', 'changes': {}}
sg = __salt__['boto_secgroup.get_config'](name=name, group_id=None, region=region, key=key,
keyid=keyid, profile=profile, vpc_id=vpc_id,
vpc_name=vpc_name)
if not sg:
ret['comment'] = '{0} security group configuration could not be retrieved.'.format(name)
ret['result'] = False
return ret
rules = _split_rules(rules)
if vpc_id or vpc_name:
for rule in rules:
_source_group_name = rule.get('source_group_name', None)
if _source_group_name:
_group_vpc_name = vpc_name
_group_vpc_id = vpc_id
_source_group_name_vpc = rule.get('source_group_name_vpc', None)
if _source_group_name_vpc:
_group_vpc_name = _source_group_name_vpc
_group_vpc_id = None
_group_id = __salt__['boto_secgroup.get_group_id'](
name=_source_group_name, vpc_id=_group_vpc_id, vpc_name=_group_vpc_name,
region=region, key=key, keyid=keyid, profile=profile
)
if not _group_id:
raise SaltInvocationError(
'source_group_name {0} does not map to a valid '
'source group id.'.format(_source_group_name)
)
rule['source_group_name'] = None
if _source_group_name_vpc:
rule.pop('source_group_name_vpc')
rule['source_group_group_id'] = _group_id
# rules = rules that exist in salt state
# sg['rules'] = that exist in present group
to_delete, to_create = _get_rule_changes(rules, sg['rules'])
to_delete = to_delete if delete_ingress_rules else []
if to_create or to_delete:
if __opts__['test']:
msg = """Security group {0} set to have rules modified.
To be created: {1}
To be deleted: {2}""".format(name, pprint.pformat(to_create),
pprint.pformat(to_delete))
ret['comment'] = msg
ret['result'] = None
return ret
if to_delete:
deleted = True
for rule in to_delete:
_deleted = __salt__['boto_secgroup.revoke'](
name, vpc_id=vpc_id, vpc_name=vpc_name, region=region,
key=key, keyid=keyid, profile=profile, **rule)
if not _deleted:
deleted = False
if deleted:
ret['comment'] = 'Removed rules on {0} security group.'.format(name)
else:
ret['comment'] = 'Failed to remove rules on {0} security group.'.format(name)
ret['result'] = False
if to_create:
created = True
for rule in to_create:
_created = __salt__['boto_secgroup.authorize'](
name, vpc_id=vpc_id, vpc_name=vpc_name, region=region,
key=key, keyid=keyid, profile=profile, **rule)
if not _created:
created = False
if created:
ret['comment'] = ' '.join([
ret['comment'],
'Created rules on {0} security group.'.format(name)
])
else:
ret['comment'] = ' '.join([
ret['comment'],
'Failed to create rules on {0} security group.'.format(name)
])
ret['result'] = False
ret['changes']['old'] = {'rules': sg['rules']}
sg = __salt__['boto_secgroup.get_config'](name=name, group_id=None, region=region, key=key,
keyid=keyid, profile=profile, vpc_id=vpc_id,
vpc_name=vpc_name)
ret['changes']['new'] = {'rules': sg['rules']}
return ret
def _rules_egress_present(name, rules_egress, delete_egress_rules=True, vpc_id=None,
vpc_name=None, region=None, key=None, keyid=None, profile=None):
'''
given a group name or group name and vpc_id (or vpc name):
1. get lists of desired rule changes (using _get_rule_changes)
2. authorize/create missing rules
3. if delete_egress_rules is True, delete/revoke non-requested rules
4. return 'old' and 'new' group rules
'''
ret = {'result': True, 'comment': '', 'changes': {}}
sg = __salt__['boto_secgroup.get_config'](name=name, group_id=None, region=region, key=key,
keyid=keyid, profile=profile, vpc_id=vpc_id,
vpc_name=vpc_name)
if not sg:
ret['comment'] = '{0} security group configuration could not be retrieved.'.format(name)
ret['result'] = False
return ret
rules_egress = _split_rules(rules_egress)
if vpc_id or vpc_name:
for rule in rules_egress:
_source_group_name = rule.get('source_group_name', None)
if _source_group_name:
_group_vpc_name = vpc_name
_group_vpc_id = vpc_id
_source_group_name_vpc = rule.get('source_group_name_vpc', None)
if _source_group_name_vpc:
_group_vpc_name = _source_group_name_vpc
_group_vpc_id = None
_group_id = __salt__['boto_secgroup.get_group_id'](
name=_source_group_name, vpc_id=_group_vpc_id, vpc_name=_group_vpc_name,
region=region, key=key, keyid=keyid, profile=profile
)
if not _group_id:
raise SaltInvocationError(
'source_group_name {0} does not map to a valid '
'source group id.'.format(_source_group_name)
)
rule['source_group_name'] = None
if _source_group_name_vpc:
rule.pop('source_group_name_vpc')
rule['source_group_group_id'] = _group_id
# rules_egress = rules that exist in salt state
# sg['rules_egress'] = that exist in present group
to_delete, to_create = _get_rule_changes(rules_egress, sg['rules_egress'])
to_delete = to_delete if delete_egress_rules else []
if to_create or to_delete:
if __opts__['test']:
msg = """Security group {0} set to have rules modified.
To be created: {1}
To be deleted: {2}""".format(name, pprint.pformat(to_create),
pprint.pformat(to_delete))
ret['comment'] = msg
ret['result'] = None
return ret
if to_delete:
deleted = True
for rule in to_delete:
_deleted = __salt__['boto_secgroup.revoke'](
name, vpc_id=vpc_id, vpc_name=vpc_name, region=region,
key=key, keyid=keyid, profile=profile, egress=True, **rule)
if not _deleted:
deleted = False
if deleted:
ret['comment'] = ' '.join([
ret['comment'],
'Removed egress rule on {0} security group.'.format(name)
])
else:
ret['comment'] = ' '.join([
ret['comment'],
'Failed to remove egress rule on {0} security group.'.format(name)
])
ret['result'] = False
if to_create:
created = True
for rule in to_create:
_created = __salt__['boto_secgroup.authorize'](
name, vpc_id=vpc_id, vpc_name=vpc_name, region=region,
key=key, keyid=keyid, profile=profile, egress=True, **rule)
if not _created:
created = False
if created:
ret['comment'] = ' '.join([
ret['comment'],
'Created egress rules on {0} security group.'.format(name)
])
else:
ret['comment'] = ' '.join([
ret['comment'],
'Failed to create egress rules on {0} security group.'.format(name)
])
ret['result'] = False
ret['changes']['old'] = {'rules_egress': sg['rules_egress']}
sg = __salt__['boto_secgroup.get_config'](name=name, group_id=None, region=region, key=key,
keyid=keyid, profile=profile, vpc_id=vpc_id,
vpc_name=vpc_name)
ret['changes']['new'] = {'rules_egress': sg['rules_egress']}
return ret
def absent(
name,
vpc_id=None,
vpc_name=None,
region=None,
key=None,
keyid=None,
profile=None):
'''
Ensure a security group with the specified name does not exist.
name
Name of the security group.
vpc_id
The ID of the VPC to remove the security group from, if any. Exclusive with vpc_name.
vpc_name
The name of the VPC to remove the security group from, if any. Exclusive with vpc_name.
.. versionadded:: 2016.3.0
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string)
that contains a dict with region, key and keyid.
.. versionadded:: 2016.3.0
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
sg = __salt__['boto_secgroup.get_config'](name=name, group_id=None, region=region, key=key,
keyid=keyid, profile=profile, vpc_id=vpc_id,
vpc_name=vpc_name)
if sg:
if __opts__['test']:
ret['comment'] = 'Security group {0} is set to be removed.'.format(name)
ret['result'] = None
return ret
deleted = __salt__['boto_secgroup.delete'](name=name, group_id=None, region=region, key=key,
keyid=keyid, profile=profile, vpc_id=vpc_id,
vpc_name=vpc_name)
if deleted:
ret['changes']['old'] = {'secgroup': sg}
ret['changes']['new'] = {'secgroup': None}
ret['comment'] = 'Security group {0} deleted.'.format(name)
else:
ret['result'] = False
ret['comment'] = 'Failed to delete {0} security group.'.format(name)
else:
ret['comment'] = '{0} security group does not exist.'.format(name)
return ret
def _tags_present(name, tags, vpc_id=None, vpc_name=None, region=None,
key=None, keyid=None, profile=None):
'''
helper function to validate tags are correct
'''
ret = {'result': True, 'comment': '', 'changes': {}}
if tags:
sg = __salt__['boto_secgroup.get_config'](name=name, group_id=None, region=region, key=key,
keyid=keyid, profile=profile, vpc_id=vpc_id,
vpc_name=vpc_name)
if not sg:
ret['comment'] = '{0} security group configuration could not be retrieved.'.format(name)
ret['result'] = False
return ret
tags_to_add = tags
tags_to_update = {}
tags_to_remove = []
if sg.get('tags'):
for existing_tag in sg['tags']:
if existing_tag not in tags:
if existing_tag not in tags_to_remove:
tags_to_remove.append(existing_tag)
else:
if tags[existing_tag] != sg['tags'][existing_tag]:
tags_to_update[existing_tag] = tags[existing_tag]
tags_to_add.pop(existing_tag)
if tags_to_remove:
if __opts__['test']:
msg = 'The following tag{0} set to be removed: {1}.'.format(
('s are' if len(tags_to_remove) > 1 else ' is'), ', '.join(tags_to_remove))
ret['comment'] = ' '.join([ret['comment'], msg])
ret['result'] = None
else:
temp_ret = __salt__['boto_secgroup.delete_tags'](tags_to_remove,
name=name,
group_id=None,
vpc_name=vpc_name,
vpc_id=vpc_id,
region=region,
key=key,
keyid=keyid,
profile=profile)
if not temp_ret:
ret['result'] = False
ret['comment'] = ' '.join([
ret['comment'],
'Error attempting to delete tags {0}.'.format(tags_to_remove)
])
return ret
if 'old' not in ret['changes']:
ret['changes'] = dictupdate.update(ret['changes'], {'old': {'tags': {}}})
for rem_tag in tags_to_remove:
ret['changes']['old']['tags'][rem_tag] = sg['tags'][rem_tag]
if tags_to_add or tags_to_update:
if __opts__['test']:
if tags_to_add:
msg = 'The following tag{0} set to be added: {1}.'.format(
('s are' if len(tags_to_add.keys()) > 1 else ' is'),
', '.join(tags_to_add.keys()))
ret['comment'] = ' '.join([ret['comment'], msg])
ret['result'] = None
if tags_to_update:
msg = 'The following tag {0} set to be updated: {1}.'.format(
('values are' if len(tags_to_update.keys()) > 1 else 'value is'),
', '.join(tags_to_update.keys()))
ret['comment'] = ' '.join([ret['comment'], msg])
ret['result'] = None
else:
all_tag_changes = dictupdate.update(tags_to_add, tags_to_update)
temp_ret = __salt__['boto_secgroup.set_tags'](all_tag_changes,
name=name,
group_id=None,
vpc_name=vpc_name,
vpc_id=vpc_id,
region=region,
key=key,
keyid=keyid,
profile=profile)
if not temp_ret:
ret['result'] = False
msg = 'Error attempting to set tags.'
ret['comment'] = ' '.join([ret['comment'], msg])
return ret
if 'old' not in ret['changes']:
ret['changes'] = dictupdate.update(ret['changes'], {'old': {'tags': {}}})
if 'new' not in ret['changes']:
ret['changes'] = dictupdate.update(ret['changes'], {'new': {'tags': {}}})
for tag in all_tag_changes:
ret['changes']['new']['tags'][tag] = tags[tag]
if 'tags' in sg:
if sg['tags']:
if tag in sg['tags']:
ret['changes']['old']['tags'][tag] = sg['tags'][tag]
if not tags_to_update and not tags_to_remove and not tags_to_add:
ret['comment'] = ' '.join([ret['comment'], 'Tags are already set.'])
return ret
|
saltstack/salt
|
salt/states/boto_secgroup.py
|
_check_rule
|
python
|
def _check_rule(rule, _rule):
'''
Check to see if two rules are the same. Needed to compare rules fetched
from boto, since they may not completely match rules defined in sls files
but may be functionally equivalent.
'''
# We need to alter what Boto returns if no ports are specified
# so that we can compare rules fairly.
#
# Boto returns None for from_port and to_port where we're required
# to pass in "-1" instead.
if _rule.get('from_port') is None:
_rule['from_port'] = -1
if _rule.get('to_port') is None:
_rule['to_port'] = -1
if (rule['ip_protocol'] == _rule['ip_protocol'] and
six.text_type(rule['from_port']) == six.text_type(_rule['from_port']) and
six.text_type(rule['to_port']) == six.text_type(_rule['to_port'])):
_cidr_ip = _rule.get('cidr_ip')
if _cidr_ip and _cidr_ip == rule.get('cidr_ip'):
return True
_owner_id = _rule.get('source_group_owner_id')
if _owner_id and _owner_id == rule.get('source_group_owner_id'):
return True
_group_id = _rule.get('source_group_group_id')
if _group_id and _group_id == rule.get('source_group_group_id'):
return True
_group_name = _rule.get('source_group_name')
if _group_name and _group_id == rule.get('source_group_name'):
return True
return False
|
Check to see if two rules are the same. Needed to compare rules fetched
from boto, since they may not completely match rules defined in sls files
but may be functionally equivalent.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_secgroup.py#L306-L338
| null |
# -*- coding: utf-8 -*-
'''
Manage Security Groups
======================
.. versionadded:: 2014.7.0
Create and destroy Security Groups. Be aware that this interacts with Amazon's
services, and so may incur charges.
This module uses ``boto``, which can be installed via package, or pip.
This module accepts explicit EC2 credentials but can also utilize
IAM roles assigned to the instance through Instance Profiles. Dynamic
credentials are then automatically obtained from AWS API and no further
configuration is necessary. More information available `here
<http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html>`_.
If IAM roles are not used you need to specify them either in a pillar file or
in the minion's config file:
.. code-block:: yaml
secgroup.keyid: GKTADJGHEIQSXMKKRBJ08H
secgroup.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
It's also possible to specify ``key``, ``keyid`` and ``region`` via a profile, either
passed in as a dict, or as a string to pull from pillars or minion config:
.. code-block:: yaml
myprofile:
keyid: GKTADJGHEIQSXMKKRBJ08H
key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
region: us-east-1
.. code-block:: yaml
Ensure mysecgroup exists:
boto_secgroup.present:
- name: mysecgroup
- description: My security group
- vpc_name: myvpc
- rules:
- ip_protocol: tcp
from_port: 80
to_port: 80
cidr_ip:
- 10.0.0.0/8
- 192.168.0.0/16
- ip_protocol: tcp
from_port: 8080
to_port: 8090
cidr_ip:
- 10.0.0.0/8
- 192.168.0.0/16
- ip_protocol: icmp
from_port: -1
to_port: -1
source_group_name: mysecgroup
- ip_protocol: tcp
from_port: 8080
to_port: 8080
source_group_name: MyOtherSecGroup
source_group_name_vpc: MyPeeredVPC
- rules_egress:
- ip_protocol: all
from_port: -1
to_port: -1
cidr_ip:
- 10.0.0.0/8
- 192.168.0.0/16
- tags:
SomeTag: 'My Tag Value'
SomeOtherTag: 'Other Tag Value'
- region: us-east-1
- keyid: GKTADJGHEIQSXMKKRBJ08H
- key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
# Using a profile from pillars
Ensure mysecgroup exists:
boto_secgroup.present:
- name: mysecgroup
- description: My security group
- profile: myprofile
# Passing in a profile
Ensure mysecgroup exists:
boto_secgroup.present:
- name: mysecgroup
- description: My security group
- profile:
keyid: GKTADJGHEIQSXMKKRBJ08H
key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
region: us-east-1
.. note::
When using the ``profile`` parameter and ``region`` is set outside of
the profile group, region is ignored and a default region will be used.
If ``region`` is missing from the ``profile`` data set, ``us-east-1``
will be used as the default region.
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import Python libs
import logging
import pprint
# Import salt libs
import salt.utils.dictupdate as dictupdate
from salt.exceptions import SaltInvocationError
from salt.ext import six
log = logging.getLogger(__name__)
def __virtual__():
'''
Only load if boto is available.
'''
return 'boto_secgroup' if 'boto_secgroup.exists' in __salt__ else False
def present(
name,
description,
vpc_id=None,
vpc_name=None,
rules=None,
rules_egress=None,
delete_ingress_rules=True,
delete_egress_rules=True,
region=None,
key=None,
keyid=None,
profile=None,
tags=None):
'''
Ensure the security group exists with the specified rules.
name
Name of the security group.
description
A description of this security group.
vpc_id
The ID of the VPC to create the security group in, if any. Exclusive with vpc_name.
vpc_name
The name of the VPC to create the security group in, if any. Exclusive with vpc_id.
.. versionadded:: 2016.3.0
.. versionadded:: 2015.8.2
rules
A list of ingress rule dicts. If not specified, ``rules=None``,
the ingress rules will be unmanaged. If set to an empty list, ``[]``,
then all ingress rules will be removed.
rules_egress
A list of egress rule dicts. If not specified, ``rules_egress=None``,
the egress rules will be unmanaged. If set to an empty list, ``[]``,
then all egress rules will be removed.
delete_ingress_rules
Some tools (EMR comes to mind) insist on adding rules on-the-fly, which
salt will happily remove on the next run. Set this param to False to
avoid deleting rules which were added outside of salt.
delete_egress_rules
Some tools (EMR comes to mind) insist on adding rules on-the-fly, which
salt will happily remove on the next run. Set this param to False to
avoid deleting rules which were added outside of salt.
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string)
that contains a dict with region, key, and keyid.
tags
List of key:value pairs of tags to set on the security group
.. versionadded:: 2016.3.0
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
_ret = _security_group_present(name, description, vpc_id=vpc_id,
vpc_name=vpc_name, region=region,
key=key, keyid=keyid, profile=profile)
ret['changes'] = _ret['changes']
ret['comment'] = ' '.join([ret['comment'], _ret['comment']])
if not _ret['result']:
ret['result'] = _ret['result']
if ret['result'] is False:
return ret
elif ret['result'] is None:
return ret
if rules is not None:
_ret = _rules_present(name, rules, delete_ingress_rules, vpc_id=vpc_id,
vpc_name=vpc_name, region=region, key=key,
keyid=keyid, profile=profile)
ret['changes'] = dictupdate.update(ret['changes'], _ret['changes'])
ret['comment'] = ' '.join([ret['comment'], _ret['comment']])
if not _ret['result']:
ret['result'] = _ret['result']
if rules_egress is not None:
_ret = _rules_egress_present(name, rules_egress, delete_egress_rules,
vpc_id=vpc_id, vpc_name=vpc_name,
region=region, key=key, keyid=keyid,
profile=profile)
ret['changes'] = dictupdate.update(ret['changes'], _ret['changes'])
ret['comment'] = ' '.join([ret['comment'], _ret['comment']])
if not _ret['result']:
ret['result'] = _ret['result']
_ret = _tags_present(
name=name, tags=tags, vpc_id=vpc_id, vpc_name=vpc_name,
region=region, key=key, keyid=keyid, profile=profile
)
ret['changes'] = dictupdate.update(ret['changes'], _ret['changes'])
ret['comment'] = ' '.join([ret['comment'], _ret['comment']])
if not _ret['result']:
ret['result'] = _ret['result']
return ret
def _security_group_present(name, description, vpc_id=None, vpc_name=None,
region=None, key=None, keyid=None, profile=None):
'''
given a group name or a group name and vpc id (or vpc name):
1. determine if the group exists
2. if the group does not exist, creates the group
3. return the group's configuration and any changes made
'''
ret = {'result': True, 'comment': '', 'changes': {}}
exists = __salt__['boto_secgroup.exists'](name, region, key, keyid,
profile, vpc_id, vpc_name)
if not exists:
if __opts__['test']:
ret['comment'] = 'Security group {0} is set to be created.'.format(name)
ret['result'] = None
return ret
created = __salt__['boto_secgroup.create'](name=name, description=description,
vpc_id=vpc_id, vpc_name=vpc_name,
region=region, key=key, keyid=keyid,
profile=profile)
if created:
ret['changes']['old'] = {'secgroup': None}
sg = __salt__['boto_secgroup.get_config'](name=name, group_id=None, region=region, key=key,
keyid=keyid, profile=profile, vpc_id=vpc_id,
vpc_name=vpc_name)
ret['changes']['new'] = {'secgroup': sg}
ret['comment'] = 'Security group {0} created.'.format(name)
else:
ret['result'] = False
ret['comment'] = 'Failed to create {0} security group.'.format(name)
else:
ret['comment'] = 'Security group {0} present.'.format(name)
return ret
def _split_rules(rules):
'''
Split rules with lists into individual rules.
We accept some attributes as lists or strings. The data we get back from
the execution module lists rules as individual rules. We need to split the
provided rules into individual rules to compare them.
'''
split = []
for rule in rules:
cidr_ip = rule.get('cidr_ip')
group_name = rule.get('source_group_name')
group_id = rule.get('source_group_group_id')
if cidr_ip and not isinstance(cidr_ip, six.string_types):
for ip in cidr_ip:
_rule = rule.copy()
_rule['cidr_ip'] = ip
split.append(_rule)
elif group_name and not isinstance(group_name, six.string_types):
for name in group_name:
_rule = rule.copy()
_rule['source_group_name'] = name
split.append(_rule)
elif group_id and not isinstance(group_id, six.string_types):
for _id in group_id:
_rule = rule.copy()
_rule['source_group_group_id'] = _id
split.append(_rule)
else:
split.append(rule)
return split
def _get_rule_changes(rules, _rules):
'''
given a list of desired rules (rules) and existing rules (_rules) return
a list of rules to delete (to_delete) and to create (to_create)
'''
to_delete = []
to_create = []
# for each rule in state file
# 1. validate rule
# 2. determine if rule exists in existing security group rules
for rule in rules:
try:
ip_protocol = six.text_type(rule.get('ip_protocol'))
except KeyError:
raise SaltInvocationError('ip_protocol, to_port, and from_port are'
' required arguments for security group'
' rules.')
supported_protocols = ['tcp', '6', 6, 'udp', '17', 17, 'icmp', '1', 1,
'all', '-1', -1]
if ip_protocol not in supported_protocols and (not
'{0}'.format(ip_protocol).isdigit() or int(ip_protocol) > 255):
raise SaltInvocationError(
'Invalid ip_protocol {0} specified in security group rule.'.format(ip_protocol))
# For the 'all' case, we need to change the protocol name to '-1'.
if ip_protocol == 'all':
rule['ip_protocol'] = '-1'
cidr_ip = rule.get('cidr_ip', None)
group_name = rule.get('source_group_name', None)
group_id = rule.get('source_group_group_id', None)
if cidr_ip and (group_id or group_name):
raise SaltInvocationError('cidr_ip and source groups can not both'
' be specified in security group rules.')
if group_id and group_name:
raise SaltInvocationError('Either source_group_group_id or'
' source_group_name can be specified in'
' security group rules, but not both.')
if not (cidr_ip or group_id or group_name):
raise SaltInvocationError('cidr_ip, source_group_group_id, or'
' source_group_name must be provided for'
' security group rules.')
rule_found = False
# for each rule in existing security group ruleset determine if
# new rule exists
for _rule in _rules:
if _check_rule(rule, _rule):
rule_found = True
break
if not rule_found:
to_create.append(rule)
# for each rule in existing security group configuration
# 1. determine if rules needed to be deleted
for _rule in _rules:
rule_found = False
for rule in rules:
if _check_rule(rule, _rule):
rule_found = True
break
if not rule_found:
# Can only supply name or id, not both. Since we're deleting
# entries, it doesn't matter which we pick.
_rule.pop('source_group_name', None)
to_delete.append(_rule)
log.debug('Rules to be deleted: %s', to_delete)
log.debug('Rules to be created: %s', to_create)
return (to_delete, to_create)
def _rules_present(name, rules, delete_ingress_rules=True, vpc_id=None,
vpc_name=None, region=None, key=None, keyid=None, profile=None):
'''
given a group name or group name and vpc_id (or vpc name):
1. get lists of desired rule changes (using _get_rule_changes)
2. authorize/create rules missing rules
3. if delete_ingress_rules is True, delete/revoke non-requested rules
4. return 'old' and 'new' group rules
'''
ret = {'result': True, 'comment': '', 'changes': {}}
sg = __salt__['boto_secgroup.get_config'](name=name, group_id=None, region=region, key=key,
keyid=keyid, profile=profile, vpc_id=vpc_id,
vpc_name=vpc_name)
if not sg:
ret['comment'] = '{0} security group configuration could not be retrieved.'.format(name)
ret['result'] = False
return ret
rules = _split_rules(rules)
if vpc_id or vpc_name:
for rule in rules:
_source_group_name = rule.get('source_group_name', None)
if _source_group_name:
_group_vpc_name = vpc_name
_group_vpc_id = vpc_id
_source_group_name_vpc = rule.get('source_group_name_vpc', None)
if _source_group_name_vpc:
_group_vpc_name = _source_group_name_vpc
_group_vpc_id = None
_group_id = __salt__['boto_secgroup.get_group_id'](
name=_source_group_name, vpc_id=_group_vpc_id, vpc_name=_group_vpc_name,
region=region, key=key, keyid=keyid, profile=profile
)
if not _group_id:
raise SaltInvocationError(
'source_group_name {0} does not map to a valid '
'source group id.'.format(_source_group_name)
)
rule['source_group_name'] = None
if _source_group_name_vpc:
rule.pop('source_group_name_vpc')
rule['source_group_group_id'] = _group_id
# rules = rules that exist in salt state
# sg['rules'] = that exist in present group
to_delete, to_create = _get_rule_changes(rules, sg['rules'])
to_delete = to_delete if delete_ingress_rules else []
if to_create or to_delete:
if __opts__['test']:
msg = """Security group {0} set to have rules modified.
To be created: {1}
To be deleted: {2}""".format(name, pprint.pformat(to_create),
pprint.pformat(to_delete))
ret['comment'] = msg
ret['result'] = None
return ret
if to_delete:
deleted = True
for rule in to_delete:
_deleted = __salt__['boto_secgroup.revoke'](
name, vpc_id=vpc_id, vpc_name=vpc_name, region=region,
key=key, keyid=keyid, profile=profile, **rule)
if not _deleted:
deleted = False
if deleted:
ret['comment'] = 'Removed rules on {0} security group.'.format(name)
else:
ret['comment'] = 'Failed to remove rules on {0} security group.'.format(name)
ret['result'] = False
if to_create:
created = True
for rule in to_create:
_created = __salt__['boto_secgroup.authorize'](
name, vpc_id=vpc_id, vpc_name=vpc_name, region=region,
key=key, keyid=keyid, profile=profile, **rule)
if not _created:
created = False
if created:
ret['comment'] = ' '.join([
ret['comment'],
'Created rules on {0} security group.'.format(name)
])
else:
ret['comment'] = ' '.join([
ret['comment'],
'Failed to create rules on {0} security group.'.format(name)
])
ret['result'] = False
ret['changes']['old'] = {'rules': sg['rules']}
sg = __salt__['boto_secgroup.get_config'](name=name, group_id=None, region=region, key=key,
keyid=keyid, profile=profile, vpc_id=vpc_id,
vpc_name=vpc_name)
ret['changes']['new'] = {'rules': sg['rules']}
return ret
def _rules_egress_present(name, rules_egress, delete_egress_rules=True, vpc_id=None,
vpc_name=None, region=None, key=None, keyid=None, profile=None):
'''
given a group name or group name and vpc_id (or vpc name):
1. get lists of desired rule changes (using _get_rule_changes)
2. authorize/create missing rules
3. if delete_egress_rules is True, delete/revoke non-requested rules
4. return 'old' and 'new' group rules
'''
ret = {'result': True, 'comment': '', 'changes': {}}
sg = __salt__['boto_secgroup.get_config'](name=name, group_id=None, region=region, key=key,
keyid=keyid, profile=profile, vpc_id=vpc_id,
vpc_name=vpc_name)
if not sg:
ret['comment'] = '{0} security group configuration could not be retrieved.'.format(name)
ret['result'] = False
return ret
rules_egress = _split_rules(rules_egress)
if vpc_id or vpc_name:
for rule in rules_egress:
_source_group_name = rule.get('source_group_name', None)
if _source_group_name:
_group_vpc_name = vpc_name
_group_vpc_id = vpc_id
_source_group_name_vpc = rule.get('source_group_name_vpc', None)
if _source_group_name_vpc:
_group_vpc_name = _source_group_name_vpc
_group_vpc_id = None
_group_id = __salt__['boto_secgroup.get_group_id'](
name=_source_group_name, vpc_id=_group_vpc_id, vpc_name=_group_vpc_name,
region=region, key=key, keyid=keyid, profile=profile
)
if not _group_id:
raise SaltInvocationError(
'source_group_name {0} does not map to a valid '
'source group id.'.format(_source_group_name)
)
rule['source_group_name'] = None
if _source_group_name_vpc:
rule.pop('source_group_name_vpc')
rule['source_group_group_id'] = _group_id
# rules_egress = rules that exist in salt state
# sg['rules_egress'] = that exist in present group
to_delete, to_create = _get_rule_changes(rules_egress, sg['rules_egress'])
to_delete = to_delete if delete_egress_rules else []
if to_create or to_delete:
if __opts__['test']:
msg = """Security group {0} set to have rules modified.
To be created: {1}
To be deleted: {2}""".format(name, pprint.pformat(to_create),
pprint.pformat(to_delete))
ret['comment'] = msg
ret['result'] = None
return ret
if to_delete:
deleted = True
for rule in to_delete:
_deleted = __salt__['boto_secgroup.revoke'](
name, vpc_id=vpc_id, vpc_name=vpc_name, region=region,
key=key, keyid=keyid, profile=profile, egress=True, **rule)
if not _deleted:
deleted = False
if deleted:
ret['comment'] = ' '.join([
ret['comment'],
'Removed egress rule on {0} security group.'.format(name)
])
else:
ret['comment'] = ' '.join([
ret['comment'],
'Failed to remove egress rule on {0} security group.'.format(name)
])
ret['result'] = False
if to_create:
created = True
for rule in to_create:
_created = __salt__['boto_secgroup.authorize'](
name, vpc_id=vpc_id, vpc_name=vpc_name, region=region,
key=key, keyid=keyid, profile=profile, egress=True, **rule)
if not _created:
created = False
if created:
ret['comment'] = ' '.join([
ret['comment'],
'Created egress rules on {0} security group.'.format(name)
])
else:
ret['comment'] = ' '.join([
ret['comment'],
'Failed to create egress rules on {0} security group.'.format(name)
])
ret['result'] = False
ret['changes']['old'] = {'rules_egress': sg['rules_egress']}
sg = __salt__['boto_secgroup.get_config'](name=name, group_id=None, region=region, key=key,
keyid=keyid, profile=profile, vpc_id=vpc_id,
vpc_name=vpc_name)
ret['changes']['new'] = {'rules_egress': sg['rules_egress']}
return ret
def absent(
name,
vpc_id=None,
vpc_name=None,
region=None,
key=None,
keyid=None,
profile=None):
'''
Ensure a security group with the specified name does not exist.
name
Name of the security group.
vpc_id
The ID of the VPC to remove the security group from, if any. Exclusive with vpc_name.
vpc_name
The name of the VPC to remove the security group from, if any. Exclusive with vpc_name.
.. versionadded:: 2016.3.0
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string)
that contains a dict with region, key and keyid.
.. versionadded:: 2016.3.0
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
sg = __salt__['boto_secgroup.get_config'](name=name, group_id=None, region=region, key=key,
keyid=keyid, profile=profile, vpc_id=vpc_id,
vpc_name=vpc_name)
if sg:
if __opts__['test']:
ret['comment'] = 'Security group {0} is set to be removed.'.format(name)
ret['result'] = None
return ret
deleted = __salt__['boto_secgroup.delete'](name=name, group_id=None, region=region, key=key,
keyid=keyid, profile=profile, vpc_id=vpc_id,
vpc_name=vpc_name)
if deleted:
ret['changes']['old'] = {'secgroup': sg}
ret['changes']['new'] = {'secgroup': None}
ret['comment'] = 'Security group {0} deleted.'.format(name)
else:
ret['result'] = False
ret['comment'] = 'Failed to delete {0} security group.'.format(name)
else:
ret['comment'] = '{0} security group does not exist.'.format(name)
return ret
def _tags_present(name, tags, vpc_id=None, vpc_name=None, region=None,
key=None, keyid=None, profile=None):
'''
helper function to validate tags are correct
'''
ret = {'result': True, 'comment': '', 'changes': {}}
if tags:
sg = __salt__['boto_secgroup.get_config'](name=name, group_id=None, region=region, key=key,
keyid=keyid, profile=profile, vpc_id=vpc_id,
vpc_name=vpc_name)
if not sg:
ret['comment'] = '{0} security group configuration could not be retrieved.'.format(name)
ret['result'] = False
return ret
tags_to_add = tags
tags_to_update = {}
tags_to_remove = []
if sg.get('tags'):
for existing_tag in sg['tags']:
if existing_tag not in tags:
if existing_tag not in tags_to_remove:
tags_to_remove.append(existing_tag)
else:
if tags[existing_tag] != sg['tags'][existing_tag]:
tags_to_update[existing_tag] = tags[existing_tag]
tags_to_add.pop(existing_tag)
if tags_to_remove:
if __opts__['test']:
msg = 'The following tag{0} set to be removed: {1}.'.format(
('s are' if len(tags_to_remove) > 1 else ' is'), ', '.join(tags_to_remove))
ret['comment'] = ' '.join([ret['comment'], msg])
ret['result'] = None
else:
temp_ret = __salt__['boto_secgroup.delete_tags'](tags_to_remove,
name=name,
group_id=None,
vpc_name=vpc_name,
vpc_id=vpc_id,
region=region,
key=key,
keyid=keyid,
profile=profile)
if not temp_ret:
ret['result'] = False
ret['comment'] = ' '.join([
ret['comment'],
'Error attempting to delete tags {0}.'.format(tags_to_remove)
])
return ret
if 'old' not in ret['changes']:
ret['changes'] = dictupdate.update(ret['changes'], {'old': {'tags': {}}})
for rem_tag in tags_to_remove:
ret['changes']['old']['tags'][rem_tag] = sg['tags'][rem_tag]
if tags_to_add or tags_to_update:
if __opts__['test']:
if tags_to_add:
msg = 'The following tag{0} set to be added: {1}.'.format(
('s are' if len(tags_to_add.keys()) > 1 else ' is'),
', '.join(tags_to_add.keys()))
ret['comment'] = ' '.join([ret['comment'], msg])
ret['result'] = None
if tags_to_update:
msg = 'The following tag {0} set to be updated: {1}.'.format(
('values are' if len(tags_to_update.keys()) > 1 else 'value is'),
', '.join(tags_to_update.keys()))
ret['comment'] = ' '.join([ret['comment'], msg])
ret['result'] = None
else:
all_tag_changes = dictupdate.update(tags_to_add, tags_to_update)
temp_ret = __salt__['boto_secgroup.set_tags'](all_tag_changes,
name=name,
group_id=None,
vpc_name=vpc_name,
vpc_id=vpc_id,
region=region,
key=key,
keyid=keyid,
profile=profile)
if not temp_ret:
ret['result'] = False
msg = 'Error attempting to set tags.'
ret['comment'] = ' '.join([ret['comment'], msg])
return ret
if 'old' not in ret['changes']:
ret['changes'] = dictupdate.update(ret['changes'], {'old': {'tags': {}}})
if 'new' not in ret['changes']:
ret['changes'] = dictupdate.update(ret['changes'], {'new': {'tags': {}}})
for tag in all_tag_changes:
ret['changes']['new']['tags'][tag] = tags[tag]
if 'tags' in sg:
if sg['tags']:
if tag in sg['tags']:
ret['changes']['old']['tags'][tag] = sg['tags'][tag]
if not tags_to_update and not tags_to_remove and not tags_to_add:
ret['comment'] = ' '.join([ret['comment'], 'Tags are already set.'])
return ret
|
saltstack/salt
|
salt/states/boto_secgroup.py
|
_get_rule_changes
|
python
|
def _get_rule_changes(rules, _rules):
'''
given a list of desired rules (rules) and existing rules (_rules) return
a list of rules to delete (to_delete) and to create (to_create)
'''
to_delete = []
to_create = []
# for each rule in state file
# 1. validate rule
# 2. determine if rule exists in existing security group rules
for rule in rules:
try:
ip_protocol = six.text_type(rule.get('ip_protocol'))
except KeyError:
raise SaltInvocationError('ip_protocol, to_port, and from_port are'
' required arguments for security group'
' rules.')
supported_protocols = ['tcp', '6', 6, 'udp', '17', 17, 'icmp', '1', 1,
'all', '-1', -1]
if ip_protocol not in supported_protocols and (not
'{0}'.format(ip_protocol).isdigit() or int(ip_protocol) > 255):
raise SaltInvocationError(
'Invalid ip_protocol {0} specified in security group rule.'.format(ip_protocol))
# For the 'all' case, we need to change the protocol name to '-1'.
if ip_protocol == 'all':
rule['ip_protocol'] = '-1'
cidr_ip = rule.get('cidr_ip', None)
group_name = rule.get('source_group_name', None)
group_id = rule.get('source_group_group_id', None)
if cidr_ip and (group_id or group_name):
raise SaltInvocationError('cidr_ip and source groups can not both'
' be specified in security group rules.')
if group_id and group_name:
raise SaltInvocationError('Either source_group_group_id or'
' source_group_name can be specified in'
' security group rules, but not both.')
if not (cidr_ip or group_id or group_name):
raise SaltInvocationError('cidr_ip, source_group_group_id, or'
' source_group_name must be provided for'
' security group rules.')
rule_found = False
# for each rule in existing security group ruleset determine if
# new rule exists
for _rule in _rules:
if _check_rule(rule, _rule):
rule_found = True
break
if not rule_found:
to_create.append(rule)
# for each rule in existing security group configuration
# 1. determine if rules needed to be deleted
for _rule in _rules:
rule_found = False
for rule in rules:
if _check_rule(rule, _rule):
rule_found = True
break
if not rule_found:
# Can only supply name or id, not both. Since we're deleting
# entries, it doesn't matter which we pick.
_rule.pop('source_group_name', None)
to_delete.append(_rule)
log.debug('Rules to be deleted: %s', to_delete)
log.debug('Rules to be created: %s', to_create)
return (to_delete, to_create)
|
given a list of desired rules (rules) and existing rules (_rules) return
a list of rules to delete (to_delete) and to create (to_create)
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_secgroup.py#L341-L405
|
[
"def _check_rule(rule, _rule):\n '''\n Check to see if two rules are the same. Needed to compare rules fetched\n from boto, since they may not completely match rules defined in sls files\n but may be functionally equivalent.\n '''\n\n # We need to alter what Boto returns if no ports are specified\n # so that we can compare rules fairly.\n #\n # Boto returns None for from_port and to_port where we're required\n # to pass in \"-1\" instead.\n if _rule.get('from_port') is None:\n _rule['from_port'] = -1\n if _rule.get('to_port') is None:\n _rule['to_port'] = -1\n\n if (rule['ip_protocol'] == _rule['ip_protocol'] and\n six.text_type(rule['from_port']) == six.text_type(_rule['from_port']) and\n six.text_type(rule['to_port']) == six.text_type(_rule['to_port'])):\n _cidr_ip = _rule.get('cidr_ip')\n if _cidr_ip and _cidr_ip == rule.get('cidr_ip'):\n return True\n _owner_id = _rule.get('source_group_owner_id')\n if _owner_id and _owner_id == rule.get('source_group_owner_id'):\n return True\n _group_id = _rule.get('source_group_group_id')\n if _group_id and _group_id == rule.get('source_group_group_id'):\n return True\n _group_name = _rule.get('source_group_name')\n if _group_name and _group_id == rule.get('source_group_name'):\n return True\n return False\n"
] |
# -*- coding: utf-8 -*-
'''
Manage Security Groups
======================
.. versionadded:: 2014.7.0
Create and destroy Security Groups. Be aware that this interacts with Amazon's
services, and so may incur charges.
This module uses ``boto``, which can be installed via package, or pip.
This module accepts explicit EC2 credentials but can also utilize
IAM roles assigned to the instance through Instance Profiles. Dynamic
credentials are then automatically obtained from AWS API and no further
configuration is necessary. More information available `here
<http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html>`_.
If IAM roles are not used you need to specify them either in a pillar file or
in the minion's config file:
.. code-block:: yaml
secgroup.keyid: GKTADJGHEIQSXMKKRBJ08H
secgroup.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
It's also possible to specify ``key``, ``keyid`` and ``region`` via a profile, either
passed in as a dict, or as a string to pull from pillars or minion config:
.. code-block:: yaml
myprofile:
keyid: GKTADJGHEIQSXMKKRBJ08H
key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
region: us-east-1
.. code-block:: yaml
Ensure mysecgroup exists:
boto_secgroup.present:
- name: mysecgroup
- description: My security group
- vpc_name: myvpc
- rules:
- ip_protocol: tcp
from_port: 80
to_port: 80
cidr_ip:
- 10.0.0.0/8
- 192.168.0.0/16
- ip_protocol: tcp
from_port: 8080
to_port: 8090
cidr_ip:
- 10.0.0.0/8
- 192.168.0.0/16
- ip_protocol: icmp
from_port: -1
to_port: -1
source_group_name: mysecgroup
- ip_protocol: tcp
from_port: 8080
to_port: 8080
source_group_name: MyOtherSecGroup
source_group_name_vpc: MyPeeredVPC
- rules_egress:
- ip_protocol: all
from_port: -1
to_port: -1
cidr_ip:
- 10.0.0.0/8
- 192.168.0.0/16
- tags:
SomeTag: 'My Tag Value'
SomeOtherTag: 'Other Tag Value'
- region: us-east-1
- keyid: GKTADJGHEIQSXMKKRBJ08H
- key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
# Using a profile from pillars
Ensure mysecgroup exists:
boto_secgroup.present:
- name: mysecgroup
- description: My security group
- profile: myprofile
# Passing in a profile
Ensure mysecgroup exists:
boto_secgroup.present:
- name: mysecgroup
- description: My security group
- profile:
keyid: GKTADJGHEIQSXMKKRBJ08H
key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
region: us-east-1
.. note::
When using the ``profile`` parameter and ``region`` is set outside of
the profile group, region is ignored and a default region will be used.
If ``region`` is missing from the ``profile`` data set, ``us-east-1``
will be used as the default region.
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import Python libs
import logging
import pprint
# Import salt libs
import salt.utils.dictupdate as dictupdate
from salt.exceptions import SaltInvocationError
from salt.ext import six
log = logging.getLogger(__name__)
def __virtual__():
'''
Only load if boto is available.
'''
return 'boto_secgroup' if 'boto_secgroup.exists' in __salt__ else False
def present(
name,
description,
vpc_id=None,
vpc_name=None,
rules=None,
rules_egress=None,
delete_ingress_rules=True,
delete_egress_rules=True,
region=None,
key=None,
keyid=None,
profile=None,
tags=None):
'''
Ensure the security group exists with the specified rules.
name
Name of the security group.
description
A description of this security group.
vpc_id
The ID of the VPC to create the security group in, if any. Exclusive with vpc_name.
vpc_name
The name of the VPC to create the security group in, if any. Exclusive with vpc_id.
.. versionadded:: 2016.3.0
.. versionadded:: 2015.8.2
rules
A list of ingress rule dicts. If not specified, ``rules=None``,
the ingress rules will be unmanaged. If set to an empty list, ``[]``,
then all ingress rules will be removed.
rules_egress
A list of egress rule dicts. If not specified, ``rules_egress=None``,
the egress rules will be unmanaged. If set to an empty list, ``[]``,
then all egress rules will be removed.
delete_ingress_rules
Some tools (EMR comes to mind) insist on adding rules on-the-fly, which
salt will happily remove on the next run. Set this param to False to
avoid deleting rules which were added outside of salt.
delete_egress_rules
Some tools (EMR comes to mind) insist on adding rules on-the-fly, which
salt will happily remove on the next run. Set this param to False to
avoid deleting rules which were added outside of salt.
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string)
that contains a dict with region, key, and keyid.
tags
List of key:value pairs of tags to set on the security group
.. versionadded:: 2016.3.0
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
_ret = _security_group_present(name, description, vpc_id=vpc_id,
vpc_name=vpc_name, region=region,
key=key, keyid=keyid, profile=profile)
ret['changes'] = _ret['changes']
ret['comment'] = ' '.join([ret['comment'], _ret['comment']])
if not _ret['result']:
ret['result'] = _ret['result']
if ret['result'] is False:
return ret
elif ret['result'] is None:
return ret
if rules is not None:
_ret = _rules_present(name, rules, delete_ingress_rules, vpc_id=vpc_id,
vpc_name=vpc_name, region=region, key=key,
keyid=keyid, profile=profile)
ret['changes'] = dictupdate.update(ret['changes'], _ret['changes'])
ret['comment'] = ' '.join([ret['comment'], _ret['comment']])
if not _ret['result']:
ret['result'] = _ret['result']
if rules_egress is not None:
_ret = _rules_egress_present(name, rules_egress, delete_egress_rules,
vpc_id=vpc_id, vpc_name=vpc_name,
region=region, key=key, keyid=keyid,
profile=profile)
ret['changes'] = dictupdate.update(ret['changes'], _ret['changes'])
ret['comment'] = ' '.join([ret['comment'], _ret['comment']])
if not _ret['result']:
ret['result'] = _ret['result']
_ret = _tags_present(
name=name, tags=tags, vpc_id=vpc_id, vpc_name=vpc_name,
region=region, key=key, keyid=keyid, profile=profile
)
ret['changes'] = dictupdate.update(ret['changes'], _ret['changes'])
ret['comment'] = ' '.join([ret['comment'], _ret['comment']])
if not _ret['result']:
ret['result'] = _ret['result']
return ret
def _security_group_present(name, description, vpc_id=None, vpc_name=None,
region=None, key=None, keyid=None, profile=None):
'''
given a group name or a group name and vpc id (or vpc name):
1. determine if the group exists
2. if the group does not exist, creates the group
3. return the group's configuration and any changes made
'''
ret = {'result': True, 'comment': '', 'changes': {}}
exists = __salt__['boto_secgroup.exists'](name, region, key, keyid,
profile, vpc_id, vpc_name)
if not exists:
if __opts__['test']:
ret['comment'] = 'Security group {0} is set to be created.'.format(name)
ret['result'] = None
return ret
created = __salt__['boto_secgroup.create'](name=name, description=description,
vpc_id=vpc_id, vpc_name=vpc_name,
region=region, key=key, keyid=keyid,
profile=profile)
if created:
ret['changes']['old'] = {'secgroup': None}
sg = __salt__['boto_secgroup.get_config'](name=name, group_id=None, region=region, key=key,
keyid=keyid, profile=profile, vpc_id=vpc_id,
vpc_name=vpc_name)
ret['changes']['new'] = {'secgroup': sg}
ret['comment'] = 'Security group {0} created.'.format(name)
else:
ret['result'] = False
ret['comment'] = 'Failed to create {0} security group.'.format(name)
else:
ret['comment'] = 'Security group {0} present.'.format(name)
return ret
def _split_rules(rules):
'''
Split rules with lists into individual rules.
We accept some attributes as lists or strings. The data we get back from
the execution module lists rules as individual rules. We need to split the
provided rules into individual rules to compare them.
'''
split = []
for rule in rules:
cidr_ip = rule.get('cidr_ip')
group_name = rule.get('source_group_name')
group_id = rule.get('source_group_group_id')
if cidr_ip and not isinstance(cidr_ip, six.string_types):
for ip in cidr_ip:
_rule = rule.copy()
_rule['cidr_ip'] = ip
split.append(_rule)
elif group_name and not isinstance(group_name, six.string_types):
for name in group_name:
_rule = rule.copy()
_rule['source_group_name'] = name
split.append(_rule)
elif group_id and not isinstance(group_id, six.string_types):
for _id in group_id:
_rule = rule.copy()
_rule['source_group_group_id'] = _id
split.append(_rule)
else:
split.append(rule)
return split
def _check_rule(rule, _rule):
'''
Check to see if two rules are the same. Needed to compare rules fetched
from boto, since they may not completely match rules defined in sls files
but may be functionally equivalent.
'''
# We need to alter what Boto returns if no ports are specified
# so that we can compare rules fairly.
#
# Boto returns None for from_port and to_port where we're required
# to pass in "-1" instead.
if _rule.get('from_port') is None:
_rule['from_port'] = -1
if _rule.get('to_port') is None:
_rule['to_port'] = -1
if (rule['ip_protocol'] == _rule['ip_protocol'] and
six.text_type(rule['from_port']) == six.text_type(_rule['from_port']) and
six.text_type(rule['to_port']) == six.text_type(_rule['to_port'])):
_cidr_ip = _rule.get('cidr_ip')
if _cidr_ip and _cidr_ip == rule.get('cidr_ip'):
return True
_owner_id = _rule.get('source_group_owner_id')
if _owner_id and _owner_id == rule.get('source_group_owner_id'):
return True
_group_id = _rule.get('source_group_group_id')
if _group_id and _group_id == rule.get('source_group_group_id'):
return True
_group_name = _rule.get('source_group_name')
if _group_name and _group_id == rule.get('source_group_name'):
return True
return False
def _rules_present(name, rules, delete_ingress_rules=True, vpc_id=None,
vpc_name=None, region=None, key=None, keyid=None, profile=None):
'''
given a group name or group name and vpc_id (or vpc name):
1. get lists of desired rule changes (using _get_rule_changes)
2. authorize/create rules missing rules
3. if delete_ingress_rules is True, delete/revoke non-requested rules
4. return 'old' and 'new' group rules
'''
ret = {'result': True, 'comment': '', 'changes': {}}
sg = __salt__['boto_secgroup.get_config'](name=name, group_id=None, region=region, key=key,
keyid=keyid, profile=profile, vpc_id=vpc_id,
vpc_name=vpc_name)
if not sg:
ret['comment'] = '{0} security group configuration could not be retrieved.'.format(name)
ret['result'] = False
return ret
rules = _split_rules(rules)
if vpc_id or vpc_name:
for rule in rules:
_source_group_name = rule.get('source_group_name', None)
if _source_group_name:
_group_vpc_name = vpc_name
_group_vpc_id = vpc_id
_source_group_name_vpc = rule.get('source_group_name_vpc', None)
if _source_group_name_vpc:
_group_vpc_name = _source_group_name_vpc
_group_vpc_id = None
_group_id = __salt__['boto_secgroup.get_group_id'](
name=_source_group_name, vpc_id=_group_vpc_id, vpc_name=_group_vpc_name,
region=region, key=key, keyid=keyid, profile=profile
)
if not _group_id:
raise SaltInvocationError(
'source_group_name {0} does not map to a valid '
'source group id.'.format(_source_group_name)
)
rule['source_group_name'] = None
if _source_group_name_vpc:
rule.pop('source_group_name_vpc')
rule['source_group_group_id'] = _group_id
# rules = rules that exist in salt state
# sg['rules'] = that exist in present group
to_delete, to_create = _get_rule_changes(rules, sg['rules'])
to_delete = to_delete if delete_ingress_rules else []
if to_create or to_delete:
if __opts__['test']:
msg = """Security group {0} set to have rules modified.
To be created: {1}
To be deleted: {2}""".format(name, pprint.pformat(to_create),
pprint.pformat(to_delete))
ret['comment'] = msg
ret['result'] = None
return ret
if to_delete:
deleted = True
for rule in to_delete:
_deleted = __salt__['boto_secgroup.revoke'](
name, vpc_id=vpc_id, vpc_name=vpc_name, region=region,
key=key, keyid=keyid, profile=profile, **rule)
if not _deleted:
deleted = False
if deleted:
ret['comment'] = 'Removed rules on {0} security group.'.format(name)
else:
ret['comment'] = 'Failed to remove rules on {0} security group.'.format(name)
ret['result'] = False
if to_create:
created = True
for rule in to_create:
_created = __salt__['boto_secgroup.authorize'](
name, vpc_id=vpc_id, vpc_name=vpc_name, region=region,
key=key, keyid=keyid, profile=profile, **rule)
if not _created:
created = False
if created:
ret['comment'] = ' '.join([
ret['comment'],
'Created rules on {0} security group.'.format(name)
])
else:
ret['comment'] = ' '.join([
ret['comment'],
'Failed to create rules on {0} security group.'.format(name)
])
ret['result'] = False
ret['changes']['old'] = {'rules': sg['rules']}
sg = __salt__['boto_secgroup.get_config'](name=name, group_id=None, region=region, key=key,
keyid=keyid, profile=profile, vpc_id=vpc_id,
vpc_name=vpc_name)
ret['changes']['new'] = {'rules': sg['rules']}
return ret
def _rules_egress_present(name, rules_egress, delete_egress_rules=True, vpc_id=None,
vpc_name=None, region=None, key=None, keyid=None, profile=None):
'''
given a group name or group name and vpc_id (or vpc name):
1. get lists of desired rule changes (using _get_rule_changes)
2. authorize/create missing rules
3. if delete_egress_rules is True, delete/revoke non-requested rules
4. return 'old' and 'new' group rules
'''
ret = {'result': True, 'comment': '', 'changes': {}}
sg = __salt__['boto_secgroup.get_config'](name=name, group_id=None, region=region, key=key,
keyid=keyid, profile=profile, vpc_id=vpc_id,
vpc_name=vpc_name)
if not sg:
ret['comment'] = '{0} security group configuration could not be retrieved.'.format(name)
ret['result'] = False
return ret
rules_egress = _split_rules(rules_egress)
if vpc_id or vpc_name:
for rule in rules_egress:
_source_group_name = rule.get('source_group_name', None)
if _source_group_name:
_group_vpc_name = vpc_name
_group_vpc_id = vpc_id
_source_group_name_vpc = rule.get('source_group_name_vpc', None)
if _source_group_name_vpc:
_group_vpc_name = _source_group_name_vpc
_group_vpc_id = None
_group_id = __salt__['boto_secgroup.get_group_id'](
name=_source_group_name, vpc_id=_group_vpc_id, vpc_name=_group_vpc_name,
region=region, key=key, keyid=keyid, profile=profile
)
if not _group_id:
raise SaltInvocationError(
'source_group_name {0} does not map to a valid '
'source group id.'.format(_source_group_name)
)
rule['source_group_name'] = None
if _source_group_name_vpc:
rule.pop('source_group_name_vpc')
rule['source_group_group_id'] = _group_id
# rules_egress = rules that exist in salt state
# sg['rules_egress'] = that exist in present group
to_delete, to_create = _get_rule_changes(rules_egress, sg['rules_egress'])
to_delete = to_delete if delete_egress_rules else []
if to_create or to_delete:
if __opts__['test']:
msg = """Security group {0} set to have rules modified.
To be created: {1}
To be deleted: {2}""".format(name, pprint.pformat(to_create),
pprint.pformat(to_delete))
ret['comment'] = msg
ret['result'] = None
return ret
if to_delete:
deleted = True
for rule in to_delete:
_deleted = __salt__['boto_secgroup.revoke'](
name, vpc_id=vpc_id, vpc_name=vpc_name, region=region,
key=key, keyid=keyid, profile=profile, egress=True, **rule)
if not _deleted:
deleted = False
if deleted:
ret['comment'] = ' '.join([
ret['comment'],
'Removed egress rule on {0} security group.'.format(name)
])
else:
ret['comment'] = ' '.join([
ret['comment'],
'Failed to remove egress rule on {0} security group.'.format(name)
])
ret['result'] = False
if to_create:
created = True
for rule in to_create:
_created = __salt__['boto_secgroup.authorize'](
name, vpc_id=vpc_id, vpc_name=vpc_name, region=region,
key=key, keyid=keyid, profile=profile, egress=True, **rule)
if not _created:
created = False
if created:
ret['comment'] = ' '.join([
ret['comment'],
'Created egress rules on {0} security group.'.format(name)
])
else:
ret['comment'] = ' '.join([
ret['comment'],
'Failed to create egress rules on {0} security group.'.format(name)
])
ret['result'] = False
ret['changes']['old'] = {'rules_egress': sg['rules_egress']}
sg = __salt__['boto_secgroup.get_config'](name=name, group_id=None, region=region, key=key,
keyid=keyid, profile=profile, vpc_id=vpc_id,
vpc_name=vpc_name)
ret['changes']['new'] = {'rules_egress': sg['rules_egress']}
return ret
def absent(
name,
vpc_id=None,
vpc_name=None,
region=None,
key=None,
keyid=None,
profile=None):
'''
Ensure a security group with the specified name does not exist.
name
Name of the security group.
vpc_id
The ID of the VPC to remove the security group from, if any. Exclusive with vpc_name.
vpc_name
The name of the VPC to remove the security group from, if any. Exclusive with vpc_name.
.. versionadded:: 2016.3.0
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string)
that contains a dict with region, key and keyid.
.. versionadded:: 2016.3.0
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
sg = __salt__['boto_secgroup.get_config'](name=name, group_id=None, region=region, key=key,
keyid=keyid, profile=profile, vpc_id=vpc_id,
vpc_name=vpc_name)
if sg:
if __opts__['test']:
ret['comment'] = 'Security group {0} is set to be removed.'.format(name)
ret['result'] = None
return ret
deleted = __salt__['boto_secgroup.delete'](name=name, group_id=None, region=region, key=key,
keyid=keyid, profile=profile, vpc_id=vpc_id,
vpc_name=vpc_name)
if deleted:
ret['changes']['old'] = {'secgroup': sg}
ret['changes']['new'] = {'secgroup': None}
ret['comment'] = 'Security group {0} deleted.'.format(name)
else:
ret['result'] = False
ret['comment'] = 'Failed to delete {0} security group.'.format(name)
else:
ret['comment'] = '{0} security group does not exist.'.format(name)
return ret
def _tags_present(name, tags, vpc_id=None, vpc_name=None, region=None,
key=None, keyid=None, profile=None):
'''
helper function to validate tags are correct
'''
ret = {'result': True, 'comment': '', 'changes': {}}
if tags:
sg = __salt__['boto_secgroup.get_config'](name=name, group_id=None, region=region, key=key,
keyid=keyid, profile=profile, vpc_id=vpc_id,
vpc_name=vpc_name)
if not sg:
ret['comment'] = '{0} security group configuration could not be retrieved.'.format(name)
ret['result'] = False
return ret
tags_to_add = tags
tags_to_update = {}
tags_to_remove = []
if sg.get('tags'):
for existing_tag in sg['tags']:
if existing_tag not in tags:
if existing_tag not in tags_to_remove:
tags_to_remove.append(existing_tag)
else:
if tags[existing_tag] != sg['tags'][existing_tag]:
tags_to_update[existing_tag] = tags[existing_tag]
tags_to_add.pop(existing_tag)
if tags_to_remove:
if __opts__['test']:
msg = 'The following tag{0} set to be removed: {1}.'.format(
('s are' if len(tags_to_remove) > 1 else ' is'), ', '.join(tags_to_remove))
ret['comment'] = ' '.join([ret['comment'], msg])
ret['result'] = None
else:
temp_ret = __salt__['boto_secgroup.delete_tags'](tags_to_remove,
name=name,
group_id=None,
vpc_name=vpc_name,
vpc_id=vpc_id,
region=region,
key=key,
keyid=keyid,
profile=profile)
if not temp_ret:
ret['result'] = False
ret['comment'] = ' '.join([
ret['comment'],
'Error attempting to delete tags {0}.'.format(tags_to_remove)
])
return ret
if 'old' not in ret['changes']:
ret['changes'] = dictupdate.update(ret['changes'], {'old': {'tags': {}}})
for rem_tag in tags_to_remove:
ret['changes']['old']['tags'][rem_tag] = sg['tags'][rem_tag]
if tags_to_add or tags_to_update:
if __opts__['test']:
if tags_to_add:
msg = 'The following tag{0} set to be added: {1}.'.format(
('s are' if len(tags_to_add.keys()) > 1 else ' is'),
', '.join(tags_to_add.keys()))
ret['comment'] = ' '.join([ret['comment'], msg])
ret['result'] = None
if tags_to_update:
msg = 'The following tag {0} set to be updated: {1}.'.format(
('values are' if len(tags_to_update.keys()) > 1 else 'value is'),
', '.join(tags_to_update.keys()))
ret['comment'] = ' '.join([ret['comment'], msg])
ret['result'] = None
else:
all_tag_changes = dictupdate.update(tags_to_add, tags_to_update)
temp_ret = __salt__['boto_secgroup.set_tags'](all_tag_changes,
name=name,
group_id=None,
vpc_name=vpc_name,
vpc_id=vpc_id,
region=region,
key=key,
keyid=keyid,
profile=profile)
if not temp_ret:
ret['result'] = False
msg = 'Error attempting to set tags.'
ret['comment'] = ' '.join([ret['comment'], msg])
return ret
if 'old' not in ret['changes']:
ret['changes'] = dictupdate.update(ret['changes'], {'old': {'tags': {}}})
if 'new' not in ret['changes']:
ret['changes'] = dictupdate.update(ret['changes'], {'new': {'tags': {}}})
for tag in all_tag_changes:
ret['changes']['new']['tags'][tag] = tags[tag]
if 'tags' in sg:
if sg['tags']:
if tag in sg['tags']:
ret['changes']['old']['tags'][tag] = sg['tags'][tag]
if not tags_to_update and not tags_to_remove and not tags_to_add:
ret['comment'] = ' '.join([ret['comment'], 'Tags are already set.'])
return ret
|
saltstack/salt
|
salt/states/boto_secgroup.py
|
_rules_present
|
python
|
def _rules_present(name, rules, delete_ingress_rules=True, vpc_id=None,
vpc_name=None, region=None, key=None, keyid=None, profile=None):
'''
given a group name or group name and vpc_id (or vpc name):
1. get lists of desired rule changes (using _get_rule_changes)
2. authorize/create rules missing rules
3. if delete_ingress_rules is True, delete/revoke non-requested rules
4. return 'old' and 'new' group rules
'''
ret = {'result': True, 'comment': '', 'changes': {}}
sg = __salt__['boto_secgroup.get_config'](name=name, group_id=None, region=region, key=key,
keyid=keyid, profile=profile, vpc_id=vpc_id,
vpc_name=vpc_name)
if not sg:
ret['comment'] = '{0} security group configuration could not be retrieved.'.format(name)
ret['result'] = False
return ret
rules = _split_rules(rules)
if vpc_id or vpc_name:
for rule in rules:
_source_group_name = rule.get('source_group_name', None)
if _source_group_name:
_group_vpc_name = vpc_name
_group_vpc_id = vpc_id
_source_group_name_vpc = rule.get('source_group_name_vpc', None)
if _source_group_name_vpc:
_group_vpc_name = _source_group_name_vpc
_group_vpc_id = None
_group_id = __salt__['boto_secgroup.get_group_id'](
name=_source_group_name, vpc_id=_group_vpc_id, vpc_name=_group_vpc_name,
region=region, key=key, keyid=keyid, profile=profile
)
if not _group_id:
raise SaltInvocationError(
'source_group_name {0} does not map to a valid '
'source group id.'.format(_source_group_name)
)
rule['source_group_name'] = None
if _source_group_name_vpc:
rule.pop('source_group_name_vpc')
rule['source_group_group_id'] = _group_id
# rules = rules that exist in salt state
# sg['rules'] = that exist in present group
to_delete, to_create = _get_rule_changes(rules, sg['rules'])
to_delete = to_delete if delete_ingress_rules else []
if to_create or to_delete:
if __opts__['test']:
msg = """Security group {0} set to have rules modified.
To be created: {1}
To be deleted: {2}""".format(name, pprint.pformat(to_create),
pprint.pformat(to_delete))
ret['comment'] = msg
ret['result'] = None
return ret
if to_delete:
deleted = True
for rule in to_delete:
_deleted = __salt__['boto_secgroup.revoke'](
name, vpc_id=vpc_id, vpc_name=vpc_name, region=region,
key=key, keyid=keyid, profile=profile, **rule)
if not _deleted:
deleted = False
if deleted:
ret['comment'] = 'Removed rules on {0} security group.'.format(name)
else:
ret['comment'] = 'Failed to remove rules on {0} security group.'.format(name)
ret['result'] = False
if to_create:
created = True
for rule in to_create:
_created = __salt__['boto_secgroup.authorize'](
name, vpc_id=vpc_id, vpc_name=vpc_name, region=region,
key=key, keyid=keyid, profile=profile, **rule)
if not _created:
created = False
if created:
ret['comment'] = ' '.join([
ret['comment'],
'Created rules on {0} security group.'.format(name)
])
else:
ret['comment'] = ' '.join([
ret['comment'],
'Failed to create rules on {0} security group.'.format(name)
])
ret['result'] = False
ret['changes']['old'] = {'rules': sg['rules']}
sg = __salt__['boto_secgroup.get_config'](name=name, group_id=None, region=region, key=key,
keyid=keyid, profile=profile, vpc_id=vpc_id,
vpc_name=vpc_name)
ret['changes']['new'] = {'rules': sg['rules']}
return ret
|
given a group name or group name and vpc_id (or vpc name):
1. get lists of desired rule changes (using _get_rule_changes)
2. authorize/create rules missing rules
3. if delete_ingress_rules is True, delete/revoke non-requested rules
4. return 'old' and 'new' group rules
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_secgroup.py#L408-L499
| null |
# -*- coding: utf-8 -*-
'''
Manage Security Groups
======================
.. versionadded:: 2014.7.0
Create and destroy Security Groups. Be aware that this interacts with Amazon's
services, and so may incur charges.
This module uses ``boto``, which can be installed via package, or pip.
This module accepts explicit EC2 credentials but can also utilize
IAM roles assigned to the instance through Instance Profiles. Dynamic
credentials are then automatically obtained from AWS API and no further
configuration is necessary. More information available `here
<http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html>`_.
If IAM roles are not used you need to specify them either in a pillar file or
in the minion's config file:
.. code-block:: yaml
secgroup.keyid: GKTADJGHEIQSXMKKRBJ08H
secgroup.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
It's also possible to specify ``key``, ``keyid`` and ``region`` via a profile, either
passed in as a dict, or as a string to pull from pillars or minion config:
.. code-block:: yaml
myprofile:
keyid: GKTADJGHEIQSXMKKRBJ08H
key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
region: us-east-1
.. code-block:: yaml
Ensure mysecgroup exists:
boto_secgroup.present:
- name: mysecgroup
- description: My security group
- vpc_name: myvpc
- rules:
- ip_protocol: tcp
from_port: 80
to_port: 80
cidr_ip:
- 10.0.0.0/8
- 192.168.0.0/16
- ip_protocol: tcp
from_port: 8080
to_port: 8090
cidr_ip:
- 10.0.0.0/8
- 192.168.0.0/16
- ip_protocol: icmp
from_port: -1
to_port: -1
source_group_name: mysecgroup
- ip_protocol: tcp
from_port: 8080
to_port: 8080
source_group_name: MyOtherSecGroup
source_group_name_vpc: MyPeeredVPC
- rules_egress:
- ip_protocol: all
from_port: -1
to_port: -1
cidr_ip:
- 10.0.0.0/8
- 192.168.0.0/16
- tags:
SomeTag: 'My Tag Value'
SomeOtherTag: 'Other Tag Value'
- region: us-east-1
- keyid: GKTADJGHEIQSXMKKRBJ08H
- key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
# Using a profile from pillars
Ensure mysecgroup exists:
boto_secgroup.present:
- name: mysecgroup
- description: My security group
- profile: myprofile
# Passing in a profile
Ensure mysecgroup exists:
boto_secgroup.present:
- name: mysecgroup
- description: My security group
- profile:
keyid: GKTADJGHEIQSXMKKRBJ08H
key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
region: us-east-1
.. note::
When using the ``profile`` parameter and ``region`` is set outside of
the profile group, region is ignored and a default region will be used.
If ``region`` is missing from the ``profile`` data set, ``us-east-1``
will be used as the default region.
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import Python libs
import logging
import pprint
# Import salt libs
import salt.utils.dictupdate as dictupdate
from salt.exceptions import SaltInvocationError
from salt.ext import six
log = logging.getLogger(__name__)
def __virtual__():
'''
Only load if boto is available.
'''
return 'boto_secgroup' if 'boto_secgroup.exists' in __salt__ else False
def present(
name,
description,
vpc_id=None,
vpc_name=None,
rules=None,
rules_egress=None,
delete_ingress_rules=True,
delete_egress_rules=True,
region=None,
key=None,
keyid=None,
profile=None,
tags=None):
'''
Ensure the security group exists with the specified rules.
name
Name of the security group.
description
A description of this security group.
vpc_id
The ID of the VPC to create the security group in, if any. Exclusive with vpc_name.
vpc_name
The name of the VPC to create the security group in, if any. Exclusive with vpc_id.
.. versionadded:: 2016.3.0
.. versionadded:: 2015.8.2
rules
A list of ingress rule dicts. If not specified, ``rules=None``,
the ingress rules will be unmanaged. If set to an empty list, ``[]``,
then all ingress rules will be removed.
rules_egress
A list of egress rule dicts. If not specified, ``rules_egress=None``,
the egress rules will be unmanaged. If set to an empty list, ``[]``,
then all egress rules will be removed.
delete_ingress_rules
Some tools (EMR comes to mind) insist on adding rules on-the-fly, which
salt will happily remove on the next run. Set this param to False to
avoid deleting rules which were added outside of salt.
delete_egress_rules
Some tools (EMR comes to mind) insist on adding rules on-the-fly, which
salt will happily remove on the next run. Set this param to False to
avoid deleting rules which were added outside of salt.
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string)
that contains a dict with region, key, and keyid.
tags
List of key:value pairs of tags to set on the security group
.. versionadded:: 2016.3.0
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
_ret = _security_group_present(name, description, vpc_id=vpc_id,
vpc_name=vpc_name, region=region,
key=key, keyid=keyid, profile=profile)
ret['changes'] = _ret['changes']
ret['comment'] = ' '.join([ret['comment'], _ret['comment']])
if not _ret['result']:
ret['result'] = _ret['result']
if ret['result'] is False:
return ret
elif ret['result'] is None:
return ret
if rules is not None:
_ret = _rules_present(name, rules, delete_ingress_rules, vpc_id=vpc_id,
vpc_name=vpc_name, region=region, key=key,
keyid=keyid, profile=profile)
ret['changes'] = dictupdate.update(ret['changes'], _ret['changes'])
ret['comment'] = ' '.join([ret['comment'], _ret['comment']])
if not _ret['result']:
ret['result'] = _ret['result']
if rules_egress is not None:
_ret = _rules_egress_present(name, rules_egress, delete_egress_rules,
vpc_id=vpc_id, vpc_name=vpc_name,
region=region, key=key, keyid=keyid,
profile=profile)
ret['changes'] = dictupdate.update(ret['changes'], _ret['changes'])
ret['comment'] = ' '.join([ret['comment'], _ret['comment']])
if not _ret['result']:
ret['result'] = _ret['result']
_ret = _tags_present(
name=name, tags=tags, vpc_id=vpc_id, vpc_name=vpc_name,
region=region, key=key, keyid=keyid, profile=profile
)
ret['changes'] = dictupdate.update(ret['changes'], _ret['changes'])
ret['comment'] = ' '.join([ret['comment'], _ret['comment']])
if not _ret['result']:
ret['result'] = _ret['result']
return ret
def _security_group_present(name, description, vpc_id=None, vpc_name=None,
region=None, key=None, keyid=None, profile=None):
'''
given a group name or a group name and vpc id (or vpc name):
1. determine if the group exists
2. if the group does not exist, creates the group
3. return the group's configuration and any changes made
'''
ret = {'result': True, 'comment': '', 'changes': {}}
exists = __salt__['boto_secgroup.exists'](name, region, key, keyid,
profile, vpc_id, vpc_name)
if not exists:
if __opts__['test']:
ret['comment'] = 'Security group {0} is set to be created.'.format(name)
ret['result'] = None
return ret
created = __salt__['boto_secgroup.create'](name=name, description=description,
vpc_id=vpc_id, vpc_name=vpc_name,
region=region, key=key, keyid=keyid,
profile=profile)
if created:
ret['changes']['old'] = {'secgroup': None}
sg = __salt__['boto_secgroup.get_config'](name=name, group_id=None, region=region, key=key,
keyid=keyid, profile=profile, vpc_id=vpc_id,
vpc_name=vpc_name)
ret['changes']['new'] = {'secgroup': sg}
ret['comment'] = 'Security group {0} created.'.format(name)
else:
ret['result'] = False
ret['comment'] = 'Failed to create {0} security group.'.format(name)
else:
ret['comment'] = 'Security group {0} present.'.format(name)
return ret
def _split_rules(rules):
'''
Split rules with lists into individual rules.
We accept some attributes as lists or strings. The data we get back from
the execution module lists rules as individual rules. We need to split the
provided rules into individual rules to compare them.
'''
split = []
for rule in rules:
cidr_ip = rule.get('cidr_ip')
group_name = rule.get('source_group_name')
group_id = rule.get('source_group_group_id')
if cidr_ip and not isinstance(cidr_ip, six.string_types):
for ip in cidr_ip:
_rule = rule.copy()
_rule['cidr_ip'] = ip
split.append(_rule)
elif group_name and not isinstance(group_name, six.string_types):
for name in group_name:
_rule = rule.copy()
_rule['source_group_name'] = name
split.append(_rule)
elif group_id and not isinstance(group_id, six.string_types):
for _id in group_id:
_rule = rule.copy()
_rule['source_group_group_id'] = _id
split.append(_rule)
else:
split.append(rule)
return split
def _check_rule(rule, _rule):
'''
Check to see if two rules are the same. Needed to compare rules fetched
from boto, since they may not completely match rules defined in sls files
but may be functionally equivalent.
'''
# We need to alter what Boto returns if no ports are specified
# so that we can compare rules fairly.
#
# Boto returns None for from_port and to_port where we're required
# to pass in "-1" instead.
if _rule.get('from_port') is None:
_rule['from_port'] = -1
if _rule.get('to_port') is None:
_rule['to_port'] = -1
if (rule['ip_protocol'] == _rule['ip_protocol'] and
six.text_type(rule['from_port']) == six.text_type(_rule['from_port']) and
six.text_type(rule['to_port']) == six.text_type(_rule['to_port'])):
_cidr_ip = _rule.get('cidr_ip')
if _cidr_ip and _cidr_ip == rule.get('cidr_ip'):
return True
_owner_id = _rule.get('source_group_owner_id')
if _owner_id and _owner_id == rule.get('source_group_owner_id'):
return True
_group_id = _rule.get('source_group_group_id')
if _group_id and _group_id == rule.get('source_group_group_id'):
return True
_group_name = _rule.get('source_group_name')
if _group_name and _group_id == rule.get('source_group_name'):
return True
return False
def _get_rule_changes(rules, _rules):
'''
given a list of desired rules (rules) and existing rules (_rules) return
a list of rules to delete (to_delete) and to create (to_create)
'''
to_delete = []
to_create = []
# for each rule in state file
# 1. validate rule
# 2. determine if rule exists in existing security group rules
for rule in rules:
try:
ip_protocol = six.text_type(rule.get('ip_protocol'))
except KeyError:
raise SaltInvocationError('ip_protocol, to_port, and from_port are'
' required arguments for security group'
' rules.')
supported_protocols = ['tcp', '6', 6, 'udp', '17', 17, 'icmp', '1', 1,
'all', '-1', -1]
if ip_protocol not in supported_protocols and (not
'{0}'.format(ip_protocol).isdigit() or int(ip_protocol) > 255):
raise SaltInvocationError(
'Invalid ip_protocol {0} specified in security group rule.'.format(ip_protocol))
# For the 'all' case, we need to change the protocol name to '-1'.
if ip_protocol == 'all':
rule['ip_protocol'] = '-1'
cidr_ip = rule.get('cidr_ip', None)
group_name = rule.get('source_group_name', None)
group_id = rule.get('source_group_group_id', None)
if cidr_ip and (group_id or group_name):
raise SaltInvocationError('cidr_ip and source groups can not both'
' be specified in security group rules.')
if group_id and group_name:
raise SaltInvocationError('Either source_group_group_id or'
' source_group_name can be specified in'
' security group rules, but not both.')
if not (cidr_ip or group_id or group_name):
raise SaltInvocationError('cidr_ip, source_group_group_id, or'
' source_group_name must be provided for'
' security group rules.')
rule_found = False
# for each rule in existing security group ruleset determine if
# new rule exists
for _rule in _rules:
if _check_rule(rule, _rule):
rule_found = True
break
if not rule_found:
to_create.append(rule)
# for each rule in existing security group configuration
# 1. determine if rules needed to be deleted
for _rule in _rules:
rule_found = False
for rule in rules:
if _check_rule(rule, _rule):
rule_found = True
break
if not rule_found:
# Can only supply name or id, not both. Since we're deleting
# entries, it doesn't matter which we pick.
_rule.pop('source_group_name', None)
to_delete.append(_rule)
log.debug('Rules to be deleted: %s', to_delete)
log.debug('Rules to be created: %s', to_create)
return (to_delete, to_create)
def _rules_egress_present(name, rules_egress, delete_egress_rules=True, vpc_id=None,
vpc_name=None, region=None, key=None, keyid=None, profile=None):
'''
given a group name or group name and vpc_id (or vpc name):
1. get lists of desired rule changes (using _get_rule_changes)
2. authorize/create missing rules
3. if delete_egress_rules is True, delete/revoke non-requested rules
4. return 'old' and 'new' group rules
'''
ret = {'result': True, 'comment': '', 'changes': {}}
sg = __salt__['boto_secgroup.get_config'](name=name, group_id=None, region=region, key=key,
keyid=keyid, profile=profile, vpc_id=vpc_id,
vpc_name=vpc_name)
if not sg:
ret['comment'] = '{0} security group configuration could not be retrieved.'.format(name)
ret['result'] = False
return ret
rules_egress = _split_rules(rules_egress)
if vpc_id or vpc_name:
for rule in rules_egress:
_source_group_name = rule.get('source_group_name', None)
if _source_group_name:
_group_vpc_name = vpc_name
_group_vpc_id = vpc_id
_source_group_name_vpc = rule.get('source_group_name_vpc', None)
if _source_group_name_vpc:
_group_vpc_name = _source_group_name_vpc
_group_vpc_id = None
_group_id = __salt__['boto_secgroup.get_group_id'](
name=_source_group_name, vpc_id=_group_vpc_id, vpc_name=_group_vpc_name,
region=region, key=key, keyid=keyid, profile=profile
)
if not _group_id:
raise SaltInvocationError(
'source_group_name {0} does not map to a valid '
'source group id.'.format(_source_group_name)
)
rule['source_group_name'] = None
if _source_group_name_vpc:
rule.pop('source_group_name_vpc')
rule['source_group_group_id'] = _group_id
# rules_egress = rules that exist in salt state
# sg['rules_egress'] = that exist in present group
to_delete, to_create = _get_rule_changes(rules_egress, sg['rules_egress'])
to_delete = to_delete if delete_egress_rules else []
if to_create or to_delete:
if __opts__['test']:
msg = """Security group {0} set to have rules modified.
To be created: {1}
To be deleted: {2}""".format(name, pprint.pformat(to_create),
pprint.pformat(to_delete))
ret['comment'] = msg
ret['result'] = None
return ret
if to_delete:
deleted = True
for rule in to_delete:
_deleted = __salt__['boto_secgroup.revoke'](
name, vpc_id=vpc_id, vpc_name=vpc_name, region=region,
key=key, keyid=keyid, profile=profile, egress=True, **rule)
if not _deleted:
deleted = False
if deleted:
ret['comment'] = ' '.join([
ret['comment'],
'Removed egress rule on {0} security group.'.format(name)
])
else:
ret['comment'] = ' '.join([
ret['comment'],
'Failed to remove egress rule on {0} security group.'.format(name)
])
ret['result'] = False
if to_create:
created = True
for rule in to_create:
_created = __salt__['boto_secgroup.authorize'](
name, vpc_id=vpc_id, vpc_name=vpc_name, region=region,
key=key, keyid=keyid, profile=profile, egress=True, **rule)
if not _created:
created = False
if created:
ret['comment'] = ' '.join([
ret['comment'],
'Created egress rules on {0} security group.'.format(name)
])
else:
ret['comment'] = ' '.join([
ret['comment'],
'Failed to create egress rules on {0} security group.'.format(name)
])
ret['result'] = False
ret['changes']['old'] = {'rules_egress': sg['rules_egress']}
sg = __salt__['boto_secgroup.get_config'](name=name, group_id=None, region=region, key=key,
keyid=keyid, profile=profile, vpc_id=vpc_id,
vpc_name=vpc_name)
ret['changes']['new'] = {'rules_egress': sg['rules_egress']}
return ret
def absent(
name,
vpc_id=None,
vpc_name=None,
region=None,
key=None,
keyid=None,
profile=None):
'''
Ensure a security group with the specified name does not exist.
name
Name of the security group.
vpc_id
The ID of the VPC to remove the security group from, if any. Exclusive with vpc_name.
vpc_name
The name of the VPC to remove the security group from, if any. Exclusive with vpc_name.
.. versionadded:: 2016.3.0
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string)
that contains a dict with region, key and keyid.
.. versionadded:: 2016.3.0
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
sg = __salt__['boto_secgroup.get_config'](name=name, group_id=None, region=region, key=key,
keyid=keyid, profile=profile, vpc_id=vpc_id,
vpc_name=vpc_name)
if sg:
if __opts__['test']:
ret['comment'] = 'Security group {0} is set to be removed.'.format(name)
ret['result'] = None
return ret
deleted = __salt__['boto_secgroup.delete'](name=name, group_id=None, region=region, key=key,
keyid=keyid, profile=profile, vpc_id=vpc_id,
vpc_name=vpc_name)
if deleted:
ret['changes']['old'] = {'secgroup': sg}
ret['changes']['new'] = {'secgroup': None}
ret['comment'] = 'Security group {0} deleted.'.format(name)
else:
ret['result'] = False
ret['comment'] = 'Failed to delete {0} security group.'.format(name)
else:
ret['comment'] = '{0} security group does not exist.'.format(name)
return ret
def _tags_present(name, tags, vpc_id=None, vpc_name=None, region=None,
key=None, keyid=None, profile=None):
'''
helper function to validate tags are correct
'''
ret = {'result': True, 'comment': '', 'changes': {}}
if tags:
sg = __salt__['boto_secgroup.get_config'](name=name, group_id=None, region=region, key=key,
keyid=keyid, profile=profile, vpc_id=vpc_id,
vpc_name=vpc_name)
if not sg:
ret['comment'] = '{0} security group configuration could not be retrieved.'.format(name)
ret['result'] = False
return ret
tags_to_add = tags
tags_to_update = {}
tags_to_remove = []
if sg.get('tags'):
for existing_tag in sg['tags']:
if existing_tag not in tags:
if existing_tag not in tags_to_remove:
tags_to_remove.append(existing_tag)
else:
if tags[existing_tag] != sg['tags'][existing_tag]:
tags_to_update[existing_tag] = tags[existing_tag]
tags_to_add.pop(existing_tag)
if tags_to_remove:
if __opts__['test']:
msg = 'The following tag{0} set to be removed: {1}.'.format(
('s are' if len(tags_to_remove) > 1 else ' is'), ', '.join(tags_to_remove))
ret['comment'] = ' '.join([ret['comment'], msg])
ret['result'] = None
else:
temp_ret = __salt__['boto_secgroup.delete_tags'](tags_to_remove,
name=name,
group_id=None,
vpc_name=vpc_name,
vpc_id=vpc_id,
region=region,
key=key,
keyid=keyid,
profile=profile)
if not temp_ret:
ret['result'] = False
ret['comment'] = ' '.join([
ret['comment'],
'Error attempting to delete tags {0}.'.format(tags_to_remove)
])
return ret
if 'old' not in ret['changes']:
ret['changes'] = dictupdate.update(ret['changes'], {'old': {'tags': {}}})
for rem_tag in tags_to_remove:
ret['changes']['old']['tags'][rem_tag] = sg['tags'][rem_tag]
if tags_to_add or tags_to_update:
if __opts__['test']:
if tags_to_add:
msg = 'The following tag{0} set to be added: {1}.'.format(
('s are' if len(tags_to_add.keys()) > 1 else ' is'),
', '.join(tags_to_add.keys()))
ret['comment'] = ' '.join([ret['comment'], msg])
ret['result'] = None
if tags_to_update:
msg = 'The following tag {0} set to be updated: {1}.'.format(
('values are' if len(tags_to_update.keys()) > 1 else 'value is'),
', '.join(tags_to_update.keys()))
ret['comment'] = ' '.join([ret['comment'], msg])
ret['result'] = None
else:
all_tag_changes = dictupdate.update(tags_to_add, tags_to_update)
temp_ret = __salt__['boto_secgroup.set_tags'](all_tag_changes,
name=name,
group_id=None,
vpc_name=vpc_name,
vpc_id=vpc_id,
region=region,
key=key,
keyid=keyid,
profile=profile)
if not temp_ret:
ret['result'] = False
msg = 'Error attempting to set tags.'
ret['comment'] = ' '.join([ret['comment'], msg])
return ret
if 'old' not in ret['changes']:
ret['changes'] = dictupdate.update(ret['changes'], {'old': {'tags': {}}})
if 'new' not in ret['changes']:
ret['changes'] = dictupdate.update(ret['changes'], {'new': {'tags': {}}})
for tag in all_tag_changes:
ret['changes']['new']['tags'][tag] = tags[tag]
if 'tags' in sg:
if sg['tags']:
if tag in sg['tags']:
ret['changes']['old']['tags'][tag] = sg['tags'][tag]
if not tags_to_update and not tags_to_remove and not tags_to_add:
ret['comment'] = ' '.join([ret['comment'], 'Tags are already set.'])
return ret
|
saltstack/salt
|
salt/states/boto_secgroup.py
|
absent
|
python
|
def absent(
name,
vpc_id=None,
vpc_name=None,
region=None,
key=None,
keyid=None,
profile=None):
'''
Ensure a security group with the specified name does not exist.
name
Name of the security group.
vpc_id
The ID of the VPC to remove the security group from, if any. Exclusive with vpc_name.
vpc_name
The name of the VPC to remove the security group from, if any. Exclusive with vpc_name.
.. versionadded:: 2016.3.0
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string)
that contains a dict with region, key and keyid.
.. versionadded:: 2016.3.0
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
sg = __salt__['boto_secgroup.get_config'](name=name, group_id=None, region=region, key=key,
keyid=keyid, profile=profile, vpc_id=vpc_id,
vpc_name=vpc_name)
if sg:
if __opts__['test']:
ret['comment'] = 'Security group {0} is set to be removed.'.format(name)
ret['result'] = None
return ret
deleted = __salt__['boto_secgroup.delete'](name=name, group_id=None, region=region, key=key,
keyid=keyid, profile=profile, vpc_id=vpc_id,
vpc_name=vpc_name)
if deleted:
ret['changes']['old'] = {'secgroup': sg}
ret['changes']['new'] = {'secgroup': None}
ret['comment'] = 'Security group {0} deleted.'.format(name)
else:
ret['result'] = False
ret['comment'] = 'Failed to delete {0} security group.'.format(name)
else:
ret['comment'] = '{0} security group does not exist.'.format(name)
return ret
|
Ensure a security group with the specified name does not exist.
name
Name of the security group.
vpc_id
The ID of the VPC to remove the security group from, if any. Exclusive with vpc_name.
vpc_name
The name of the VPC to remove the security group from, if any. Exclusive with vpc_name.
.. versionadded:: 2016.3.0
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string)
that contains a dict with region, key and keyid.
.. versionadded:: 2016.3.0
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_secgroup.py#L603-L663
| null |
# -*- coding: utf-8 -*-
'''
Manage Security Groups
======================
.. versionadded:: 2014.7.0
Create and destroy Security Groups. Be aware that this interacts with Amazon's
services, and so may incur charges.
This module uses ``boto``, which can be installed via package, or pip.
This module accepts explicit EC2 credentials but can also utilize
IAM roles assigned to the instance through Instance Profiles. Dynamic
credentials are then automatically obtained from AWS API and no further
configuration is necessary. More information available `here
<http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html>`_.
If IAM roles are not used you need to specify them either in a pillar file or
in the minion's config file:
.. code-block:: yaml
secgroup.keyid: GKTADJGHEIQSXMKKRBJ08H
secgroup.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
It's also possible to specify ``key``, ``keyid`` and ``region`` via a profile, either
passed in as a dict, or as a string to pull from pillars or minion config:
.. code-block:: yaml
myprofile:
keyid: GKTADJGHEIQSXMKKRBJ08H
key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
region: us-east-1
.. code-block:: yaml
Ensure mysecgroup exists:
boto_secgroup.present:
- name: mysecgroup
- description: My security group
- vpc_name: myvpc
- rules:
- ip_protocol: tcp
from_port: 80
to_port: 80
cidr_ip:
- 10.0.0.0/8
- 192.168.0.0/16
- ip_protocol: tcp
from_port: 8080
to_port: 8090
cidr_ip:
- 10.0.0.0/8
- 192.168.0.0/16
- ip_protocol: icmp
from_port: -1
to_port: -1
source_group_name: mysecgroup
- ip_protocol: tcp
from_port: 8080
to_port: 8080
source_group_name: MyOtherSecGroup
source_group_name_vpc: MyPeeredVPC
- rules_egress:
- ip_protocol: all
from_port: -1
to_port: -1
cidr_ip:
- 10.0.0.0/8
- 192.168.0.0/16
- tags:
SomeTag: 'My Tag Value'
SomeOtherTag: 'Other Tag Value'
- region: us-east-1
- keyid: GKTADJGHEIQSXMKKRBJ08H
- key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
# Using a profile from pillars
Ensure mysecgroup exists:
boto_secgroup.present:
- name: mysecgroup
- description: My security group
- profile: myprofile
# Passing in a profile
Ensure mysecgroup exists:
boto_secgroup.present:
- name: mysecgroup
- description: My security group
- profile:
keyid: GKTADJGHEIQSXMKKRBJ08H
key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
region: us-east-1
.. note::
When using the ``profile`` parameter and ``region`` is set outside of
the profile group, region is ignored and a default region will be used.
If ``region`` is missing from the ``profile`` data set, ``us-east-1``
will be used as the default region.
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import Python libs
import logging
import pprint
# Import salt libs
import salt.utils.dictupdate as dictupdate
from salt.exceptions import SaltInvocationError
from salt.ext import six
log = logging.getLogger(__name__)
def __virtual__():
'''
Only load if boto is available.
'''
return 'boto_secgroup' if 'boto_secgroup.exists' in __salt__ else False
def present(
name,
description,
vpc_id=None,
vpc_name=None,
rules=None,
rules_egress=None,
delete_ingress_rules=True,
delete_egress_rules=True,
region=None,
key=None,
keyid=None,
profile=None,
tags=None):
'''
Ensure the security group exists with the specified rules.
name
Name of the security group.
description
A description of this security group.
vpc_id
The ID of the VPC to create the security group in, if any. Exclusive with vpc_name.
vpc_name
The name of the VPC to create the security group in, if any. Exclusive with vpc_id.
.. versionadded:: 2016.3.0
.. versionadded:: 2015.8.2
rules
A list of ingress rule dicts. If not specified, ``rules=None``,
the ingress rules will be unmanaged. If set to an empty list, ``[]``,
then all ingress rules will be removed.
rules_egress
A list of egress rule dicts. If not specified, ``rules_egress=None``,
the egress rules will be unmanaged. If set to an empty list, ``[]``,
then all egress rules will be removed.
delete_ingress_rules
Some tools (EMR comes to mind) insist on adding rules on-the-fly, which
salt will happily remove on the next run. Set this param to False to
avoid deleting rules which were added outside of salt.
delete_egress_rules
Some tools (EMR comes to mind) insist on adding rules on-the-fly, which
salt will happily remove on the next run. Set this param to False to
avoid deleting rules which were added outside of salt.
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string)
that contains a dict with region, key, and keyid.
tags
List of key:value pairs of tags to set on the security group
.. versionadded:: 2016.3.0
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
_ret = _security_group_present(name, description, vpc_id=vpc_id,
vpc_name=vpc_name, region=region,
key=key, keyid=keyid, profile=profile)
ret['changes'] = _ret['changes']
ret['comment'] = ' '.join([ret['comment'], _ret['comment']])
if not _ret['result']:
ret['result'] = _ret['result']
if ret['result'] is False:
return ret
elif ret['result'] is None:
return ret
if rules is not None:
_ret = _rules_present(name, rules, delete_ingress_rules, vpc_id=vpc_id,
vpc_name=vpc_name, region=region, key=key,
keyid=keyid, profile=profile)
ret['changes'] = dictupdate.update(ret['changes'], _ret['changes'])
ret['comment'] = ' '.join([ret['comment'], _ret['comment']])
if not _ret['result']:
ret['result'] = _ret['result']
if rules_egress is not None:
_ret = _rules_egress_present(name, rules_egress, delete_egress_rules,
vpc_id=vpc_id, vpc_name=vpc_name,
region=region, key=key, keyid=keyid,
profile=profile)
ret['changes'] = dictupdate.update(ret['changes'], _ret['changes'])
ret['comment'] = ' '.join([ret['comment'], _ret['comment']])
if not _ret['result']:
ret['result'] = _ret['result']
_ret = _tags_present(
name=name, tags=tags, vpc_id=vpc_id, vpc_name=vpc_name,
region=region, key=key, keyid=keyid, profile=profile
)
ret['changes'] = dictupdate.update(ret['changes'], _ret['changes'])
ret['comment'] = ' '.join([ret['comment'], _ret['comment']])
if not _ret['result']:
ret['result'] = _ret['result']
return ret
def _security_group_present(name, description, vpc_id=None, vpc_name=None,
region=None, key=None, keyid=None, profile=None):
'''
given a group name or a group name and vpc id (or vpc name):
1. determine if the group exists
2. if the group does not exist, creates the group
3. return the group's configuration and any changes made
'''
ret = {'result': True, 'comment': '', 'changes': {}}
exists = __salt__['boto_secgroup.exists'](name, region, key, keyid,
profile, vpc_id, vpc_name)
if not exists:
if __opts__['test']:
ret['comment'] = 'Security group {0} is set to be created.'.format(name)
ret['result'] = None
return ret
created = __salt__['boto_secgroup.create'](name=name, description=description,
vpc_id=vpc_id, vpc_name=vpc_name,
region=region, key=key, keyid=keyid,
profile=profile)
if created:
ret['changes']['old'] = {'secgroup': None}
sg = __salt__['boto_secgroup.get_config'](name=name, group_id=None, region=region, key=key,
keyid=keyid, profile=profile, vpc_id=vpc_id,
vpc_name=vpc_name)
ret['changes']['new'] = {'secgroup': sg}
ret['comment'] = 'Security group {0} created.'.format(name)
else:
ret['result'] = False
ret['comment'] = 'Failed to create {0} security group.'.format(name)
else:
ret['comment'] = 'Security group {0} present.'.format(name)
return ret
def _split_rules(rules):
'''
Split rules with lists into individual rules.
We accept some attributes as lists or strings. The data we get back from
the execution module lists rules as individual rules. We need to split the
provided rules into individual rules to compare them.
'''
split = []
for rule in rules:
cidr_ip = rule.get('cidr_ip')
group_name = rule.get('source_group_name')
group_id = rule.get('source_group_group_id')
if cidr_ip and not isinstance(cidr_ip, six.string_types):
for ip in cidr_ip:
_rule = rule.copy()
_rule['cidr_ip'] = ip
split.append(_rule)
elif group_name and not isinstance(group_name, six.string_types):
for name in group_name:
_rule = rule.copy()
_rule['source_group_name'] = name
split.append(_rule)
elif group_id and not isinstance(group_id, six.string_types):
for _id in group_id:
_rule = rule.copy()
_rule['source_group_group_id'] = _id
split.append(_rule)
else:
split.append(rule)
return split
def _check_rule(rule, _rule):
'''
Check to see if two rules are the same. Needed to compare rules fetched
from boto, since they may not completely match rules defined in sls files
but may be functionally equivalent.
'''
# We need to alter what Boto returns if no ports are specified
# so that we can compare rules fairly.
#
# Boto returns None for from_port and to_port where we're required
# to pass in "-1" instead.
if _rule.get('from_port') is None:
_rule['from_port'] = -1
if _rule.get('to_port') is None:
_rule['to_port'] = -1
if (rule['ip_protocol'] == _rule['ip_protocol'] and
six.text_type(rule['from_port']) == six.text_type(_rule['from_port']) and
six.text_type(rule['to_port']) == six.text_type(_rule['to_port'])):
_cidr_ip = _rule.get('cidr_ip')
if _cidr_ip and _cidr_ip == rule.get('cidr_ip'):
return True
_owner_id = _rule.get('source_group_owner_id')
if _owner_id and _owner_id == rule.get('source_group_owner_id'):
return True
_group_id = _rule.get('source_group_group_id')
if _group_id and _group_id == rule.get('source_group_group_id'):
return True
_group_name = _rule.get('source_group_name')
if _group_name and _group_id == rule.get('source_group_name'):
return True
return False
def _get_rule_changes(rules, _rules):
'''
given a list of desired rules (rules) and existing rules (_rules) return
a list of rules to delete (to_delete) and to create (to_create)
'''
to_delete = []
to_create = []
# for each rule in state file
# 1. validate rule
# 2. determine if rule exists in existing security group rules
for rule in rules:
try:
ip_protocol = six.text_type(rule.get('ip_protocol'))
except KeyError:
raise SaltInvocationError('ip_protocol, to_port, and from_port are'
' required arguments for security group'
' rules.')
supported_protocols = ['tcp', '6', 6, 'udp', '17', 17, 'icmp', '1', 1,
'all', '-1', -1]
if ip_protocol not in supported_protocols and (not
'{0}'.format(ip_protocol).isdigit() or int(ip_protocol) > 255):
raise SaltInvocationError(
'Invalid ip_protocol {0} specified in security group rule.'.format(ip_protocol))
# For the 'all' case, we need to change the protocol name to '-1'.
if ip_protocol == 'all':
rule['ip_protocol'] = '-1'
cidr_ip = rule.get('cidr_ip', None)
group_name = rule.get('source_group_name', None)
group_id = rule.get('source_group_group_id', None)
if cidr_ip and (group_id or group_name):
raise SaltInvocationError('cidr_ip and source groups can not both'
' be specified in security group rules.')
if group_id and group_name:
raise SaltInvocationError('Either source_group_group_id or'
' source_group_name can be specified in'
' security group rules, but not both.')
if not (cidr_ip or group_id or group_name):
raise SaltInvocationError('cidr_ip, source_group_group_id, or'
' source_group_name must be provided for'
' security group rules.')
rule_found = False
# for each rule in existing security group ruleset determine if
# new rule exists
for _rule in _rules:
if _check_rule(rule, _rule):
rule_found = True
break
if not rule_found:
to_create.append(rule)
# for each rule in existing security group configuration
# 1. determine if rules needed to be deleted
for _rule in _rules:
rule_found = False
for rule in rules:
if _check_rule(rule, _rule):
rule_found = True
break
if not rule_found:
# Can only supply name or id, not both. Since we're deleting
# entries, it doesn't matter which we pick.
_rule.pop('source_group_name', None)
to_delete.append(_rule)
log.debug('Rules to be deleted: %s', to_delete)
log.debug('Rules to be created: %s', to_create)
return (to_delete, to_create)
def _rules_present(name, rules, delete_ingress_rules=True, vpc_id=None,
vpc_name=None, region=None, key=None, keyid=None, profile=None):
'''
given a group name or group name and vpc_id (or vpc name):
1. get lists of desired rule changes (using _get_rule_changes)
2. authorize/create rules missing rules
3. if delete_ingress_rules is True, delete/revoke non-requested rules
4. return 'old' and 'new' group rules
'''
ret = {'result': True, 'comment': '', 'changes': {}}
sg = __salt__['boto_secgroup.get_config'](name=name, group_id=None, region=region, key=key,
keyid=keyid, profile=profile, vpc_id=vpc_id,
vpc_name=vpc_name)
if not sg:
ret['comment'] = '{0} security group configuration could not be retrieved.'.format(name)
ret['result'] = False
return ret
rules = _split_rules(rules)
if vpc_id or vpc_name:
for rule in rules:
_source_group_name = rule.get('source_group_name', None)
if _source_group_name:
_group_vpc_name = vpc_name
_group_vpc_id = vpc_id
_source_group_name_vpc = rule.get('source_group_name_vpc', None)
if _source_group_name_vpc:
_group_vpc_name = _source_group_name_vpc
_group_vpc_id = None
_group_id = __salt__['boto_secgroup.get_group_id'](
name=_source_group_name, vpc_id=_group_vpc_id, vpc_name=_group_vpc_name,
region=region, key=key, keyid=keyid, profile=profile
)
if not _group_id:
raise SaltInvocationError(
'source_group_name {0} does not map to a valid '
'source group id.'.format(_source_group_name)
)
rule['source_group_name'] = None
if _source_group_name_vpc:
rule.pop('source_group_name_vpc')
rule['source_group_group_id'] = _group_id
# rules = rules that exist in salt state
# sg['rules'] = that exist in present group
to_delete, to_create = _get_rule_changes(rules, sg['rules'])
to_delete = to_delete if delete_ingress_rules else []
if to_create or to_delete:
if __opts__['test']:
msg = """Security group {0} set to have rules modified.
To be created: {1}
To be deleted: {2}""".format(name, pprint.pformat(to_create),
pprint.pformat(to_delete))
ret['comment'] = msg
ret['result'] = None
return ret
if to_delete:
deleted = True
for rule in to_delete:
_deleted = __salt__['boto_secgroup.revoke'](
name, vpc_id=vpc_id, vpc_name=vpc_name, region=region,
key=key, keyid=keyid, profile=profile, **rule)
if not _deleted:
deleted = False
if deleted:
ret['comment'] = 'Removed rules on {0} security group.'.format(name)
else:
ret['comment'] = 'Failed to remove rules on {0} security group.'.format(name)
ret['result'] = False
if to_create:
created = True
for rule in to_create:
_created = __salt__['boto_secgroup.authorize'](
name, vpc_id=vpc_id, vpc_name=vpc_name, region=region,
key=key, keyid=keyid, profile=profile, **rule)
if not _created:
created = False
if created:
ret['comment'] = ' '.join([
ret['comment'],
'Created rules on {0} security group.'.format(name)
])
else:
ret['comment'] = ' '.join([
ret['comment'],
'Failed to create rules on {0} security group.'.format(name)
])
ret['result'] = False
ret['changes']['old'] = {'rules': sg['rules']}
sg = __salt__['boto_secgroup.get_config'](name=name, group_id=None, region=region, key=key,
keyid=keyid, profile=profile, vpc_id=vpc_id,
vpc_name=vpc_name)
ret['changes']['new'] = {'rules': sg['rules']}
return ret
def _rules_egress_present(name, rules_egress, delete_egress_rules=True, vpc_id=None,
vpc_name=None, region=None, key=None, keyid=None, profile=None):
'''
given a group name or group name and vpc_id (or vpc name):
1. get lists of desired rule changes (using _get_rule_changes)
2. authorize/create missing rules
3. if delete_egress_rules is True, delete/revoke non-requested rules
4. return 'old' and 'new' group rules
'''
ret = {'result': True, 'comment': '', 'changes': {}}
sg = __salt__['boto_secgroup.get_config'](name=name, group_id=None, region=region, key=key,
keyid=keyid, profile=profile, vpc_id=vpc_id,
vpc_name=vpc_name)
if not sg:
ret['comment'] = '{0} security group configuration could not be retrieved.'.format(name)
ret['result'] = False
return ret
rules_egress = _split_rules(rules_egress)
if vpc_id or vpc_name:
for rule in rules_egress:
_source_group_name = rule.get('source_group_name', None)
if _source_group_name:
_group_vpc_name = vpc_name
_group_vpc_id = vpc_id
_source_group_name_vpc = rule.get('source_group_name_vpc', None)
if _source_group_name_vpc:
_group_vpc_name = _source_group_name_vpc
_group_vpc_id = None
_group_id = __salt__['boto_secgroup.get_group_id'](
name=_source_group_name, vpc_id=_group_vpc_id, vpc_name=_group_vpc_name,
region=region, key=key, keyid=keyid, profile=profile
)
if not _group_id:
raise SaltInvocationError(
'source_group_name {0} does not map to a valid '
'source group id.'.format(_source_group_name)
)
rule['source_group_name'] = None
if _source_group_name_vpc:
rule.pop('source_group_name_vpc')
rule['source_group_group_id'] = _group_id
# rules_egress = rules that exist in salt state
# sg['rules_egress'] = that exist in present group
to_delete, to_create = _get_rule_changes(rules_egress, sg['rules_egress'])
to_delete = to_delete if delete_egress_rules else []
if to_create or to_delete:
if __opts__['test']:
msg = """Security group {0} set to have rules modified.
To be created: {1}
To be deleted: {2}""".format(name, pprint.pformat(to_create),
pprint.pformat(to_delete))
ret['comment'] = msg
ret['result'] = None
return ret
if to_delete:
deleted = True
for rule in to_delete:
_deleted = __salt__['boto_secgroup.revoke'](
name, vpc_id=vpc_id, vpc_name=vpc_name, region=region,
key=key, keyid=keyid, profile=profile, egress=True, **rule)
if not _deleted:
deleted = False
if deleted:
ret['comment'] = ' '.join([
ret['comment'],
'Removed egress rule on {0} security group.'.format(name)
])
else:
ret['comment'] = ' '.join([
ret['comment'],
'Failed to remove egress rule on {0} security group.'.format(name)
])
ret['result'] = False
if to_create:
created = True
for rule in to_create:
_created = __salt__['boto_secgroup.authorize'](
name, vpc_id=vpc_id, vpc_name=vpc_name, region=region,
key=key, keyid=keyid, profile=profile, egress=True, **rule)
if not _created:
created = False
if created:
ret['comment'] = ' '.join([
ret['comment'],
'Created egress rules on {0} security group.'.format(name)
])
else:
ret['comment'] = ' '.join([
ret['comment'],
'Failed to create egress rules on {0} security group.'.format(name)
])
ret['result'] = False
ret['changes']['old'] = {'rules_egress': sg['rules_egress']}
sg = __salt__['boto_secgroup.get_config'](name=name, group_id=None, region=region, key=key,
keyid=keyid, profile=profile, vpc_id=vpc_id,
vpc_name=vpc_name)
ret['changes']['new'] = {'rules_egress': sg['rules_egress']}
return ret
def _tags_present(name, tags, vpc_id=None, vpc_name=None, region=None,
key=None, keyid=None, profile=None):
'''
helper function to validate tags are correct
'''
ret = {'result': True, 'comment': '', 'changes': {}}
if tags:
sg = __salt__['boto_secgroup.get_config'](name=name, group_id=None, region=region, key=key,
keyid=keyid, profile=profile, vpc_id=vpc_id,
vpc_name=vpc_name)
if not sg:
ret['comment'] = '{0} security group configuration could not be retrieved.'.format(name)
ret['result'] = False
return ret
tags_to_add = tags
tags_to_update = {}
tags_to_remove = []
if sg.get('tags'):
for existing_tag in sg['tags']:
if existing_tag not in tags:
if existing_tag not in tags_to_remove:
tags_to_remove.append(existing_tag)
else:
if tags[existing_tag] != sg['tags'][existing_tag]:
tags_to_update[existing_tag] = tags[existing_tag]
tags_to_add.pop(existing_tag)
if tags_to_remove:
if __opts__['test']:
msg = 'The following tag{0} set to be removed: {1}.'.format(
('s are' if len(tags_to_remove) > 1 else ' is'), ', '.join(tags_to_remove))
ret['comment'] = ' '.join([ret['comment'], msg])
ret['result'] = None
else:
temp_ret = __salt__['boto_secgroup.delete_tags'](tags_to_remove,
name=name,
group_id=None,
vpc_name=vpc_name,
vpc_id=vpc_id,
region=region,
key=key,
keyid=keyid,
profile=profile)
if not temp_ret:
ret['result'] = False
ret['comment'] = ' '.join([
ret['comment'],
'Error attempting to delete tags {0}.'.format(tags_to_remove)
])
return ret
if 'old' not in ret['changes']:
ret['changes'] = dictupdate.update(ret['changes'], {'old': {'tags': {}}})
for rem_tag in tags_to_remove:
ret['changes']['old']['tags'][rem_tag] = sg['tags'][rem_tag]
if tags_to_add or tags_to_update:
if __opts__['test']:
if tags_to_add:
msg = 'The following tag{0} set to be added: {1}.'.format(
('s are' if len(tags_to_add.keys()) > 1 else ' is'),
', '.join(tags_to_add.keys()))
ret['comment'] = ' '.join([ret['comment'], msg])
ret['result'] = None
if tags_to_update:
msg = 'The following tag {0} set to be updated: {1}.'.format(
('values are' if len(tags_to_update.keys()) > 1 else 'value is'),
', '.join(tags_to_update.keys()))
ret['comment'] = ' '.join([ret['comment'], msg])
ret['result'] = None
else:
all_tag_changes = dictupdate.update(tags_to_add, tags_to_update)
temp_ret = __salt__['boto_secgroup.set_tags'](all_tag_changes,
name=name,
group_id=None,
vpc_name=vpc_name,
vpc_id=vpc_id,
region=region,
key=key,
keyid=keyid,
profile=profile)
if not temp_ret:
ret['result'] = False
msg = 'Error attempting to set tags.'
ret['comment'] = ' '.join([ret['comment'], msg])
return ret
if 'old' not in ret['changes']:
ret['changes'] = dictupdate.update(ret['changes'], {'old': {'tags': {}}})
if 'new' not in ret['changes']:
ret['changes'] = dictupdate.update(ret['changes'], {'new': {'tags': {}}})
for tag in all_tag_changes:
ret['changes']['new']['tags'][tag] = tags[tag]
if 'tags' in sg:
if sg['tags']:
if tag in sg['tags']:
ret['changes']['old']['tags'][tag] = sg['tags'][tag]
if not tags_to_update and not tags_to_remove and not tags_to_add:
ret['comment'] = ' '.join([ret['comment'], 'Tags are already set.'])
return ret
|
saltstack/salt
|
salt/states/boto_secgroup.py
|
_tags_present
|
python
|
def _tags_present(name, tags, vpc_id=None, vpc_name=None, region=None,
key=None, keyid=None, profile=None):
'''
helper function to validate tags are correct
'''
ret = {'result': True, 'comment': '', 'changes': {}}
if tags:
sg = __salt__['boto_secgroup.get_config'](name=name, group_id=None, region=region, key=key,
keyid=keyid, profile=profile, vpc_id=vpc_id,
vpc_name=vpc_name)
if not sg:
ret['comment'] = '{0} security group configuration could not be retrieved.'.format(name)
ret['result'] = False
return ret
tags_to_add = tags
tags_to_update = {}
tags_to_remove = []
if sg.get('tags'):
for existing_tag in sg['tags']:
if existing_tag not in tags:
if existing_tag not in tags_to_remove:
tags_to_remove.append(existing_tag)
else:
if tags[existing_tag] != sg['tags'][existing_tag]:
tags_to_update[existing_tag] = tags[existing_tag]
tags_to_add.pop(existing_tag)
if tags_to_remove:
if __opts__['test']:
msg = 'The following tag{0} set to be removed: {1}.'.format(
('s are' if len(tags_to_remove) > 1 else ' is'), ', '.join(tags_to_remove))
ret['comment'] = ' '.join([ret['comment'], msg])
ret['result'] = None
else:
temp_ret = __salt__['boto_secgroup.delete_tags'](tags_to_remove,
name=name,
group_id=None,
vpc_name=vpc_name,
vpc_id=vpc_id,
region=region,
key=key,
keyid=keyid,
profile=profile)
if not temp_ret:
ret['result'] = False
ret['comment'] = ' '.join([
ret['comment'],
'Error attempting to delete tags {0}.'.format(tags_to_remove)
])
return ret
if 'old' not in ret['changes']:
ret['changes'] = dictupdate.update(ret['changes'], {'old': {'tags': {}}})
for rem_tag in tags_to_remove:
ret['changes']['old']['tags'][rem_tag] = sg['tags'][rem_tag]
if tags_to_add or tags_to_update:
if __opts__['test']:
if tags_to_add:
msg = 'The following tag{0} set to be added: {1}.'.format(
('s are' if len(tags_to_add.keys()) > 1 else ' is'),
', '.join(tags_to_add.keys()))
ret['comment'] = ' '.join([ret['comment'], msg])
ret['result'] = None
if tags_to_update:
msg = 'The following tag {0} set to be updated: {1}.'.format(
('values are' if len(tags_to_update.keys()) > 1 else 'value is'),
', '.join(tags_to_update.keys()))
ret['comment'] = ' '.join([ret['comment'], msg])
ret['result'] = None
else:
all_tag_changes = dictupdate.update(tags_to_add, tags_to_update)
temp_ret = __salt__['boto_secgroup.set_tags'](all_tag_changes,
name=name,
group_id=None,
vpc_name=vpc_name,
vpc_id=vpc_id,
region=region,
key=key,
keyid=keyid,
profile=profile)
if not temp_ret:
ret['result'] = False
msg = 'Error attempting to set tags.'
ret['comment'] = ' '.join([ret['comment'], msg])
return ret
if 'old' not in ret['changes']:
ret['changes'] = dictupdate.update(ret['changes'], {'old': {'tags': {}}})
if 'new' not in ret['changes']:
ret['changes'] = dictupdate.update(ret['changes'], {'new': {'tags': {}}})
for tag in all_tag_changes:
ret['changes']['new']['tags'][tag] = tags[tag]
if 'tags' in sg:
if sg['tags']:
if tag in sg['tags']:
ret['changes']['old']['tags'][tag] = sg['tags'][tag]
if not tags_to_update and not tags_to_remove and not tags_to_add:
ret['comment'] = ' '.join([ret['comment'], 'Tags are already set.'])
return ret
|
helper function to validate tags are correct
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_secgroup.py#L666-L761
| null |
# -*- coding: utf-8 -*-
'''
Manage Security Groups
======================
.. versionadded:: 2014.7.0
Create and destroy Security Groups. Be aware that this interacts with Amazon's
services, and so may incur charges.
This module uses ``boto``, which can be installed via package, or pip.
This module accepts explicit EC2 credentials but can also utilize
IAM roles assigned to the instance through Instance Profiles. Dynamic
credentials are then automatically obtained from AWS API and no further
configuration is necessary. More information available `here
<http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html>`_.
If IAM roles are not used you need to specify them either in a pillar file or
in the minion's config file:
.. code-block:: yaml
secgroup.keyid: GKTADJGHEIQSXMKKRBJ08H
secgroup.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
It's also possible to specify ``key``, ``keyid`` and ``region`` via a profile, either
passed in as a dict, or as a string to pull from pillars or minion config:
.. code-block:: yaml
myprofile:
keyid: GKTADJGHEIQSXMKKRBJ08H
key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
region: us-east-1
.. code-block:: yaml
Ensure mysecgroup exists:
boto_secgroup.present:
- name: mysecgroup
- description: My security group
- vpc_name: myvpc
- rules:
- ip_protocol: tcp
from_port: 80
to_port: 80
cidr_ip:
- 10.0.0.0/8
- 192.168.0.0/16
- ip_protocol: tcp
from_port: 8080
to_port: 8090
cidr_ip:
- 10.0.0.0/8
- 192.168.0.0/16
- ip_protocol: icmp
from_port: -1
to_port: -1
source_group_name: mysecgroup
- ip_protocol: tcp
from_port: 8080
to_port: 8080
source_group_name: MyOtherSecGroup
source_group_name_vpc: MyPeeredVPC
- rules_egress:
- ip_protocol: all
from_port: -1
to_port: -1
cidr_ip:
- 10.0.0.0/8
- 192.168.0.0/16
- tags:
SomeTag: 'My Tag Value'
SomeOtherTag: 'Other Tag Value'
- region: us-east-1
- keyid: GKTADJGHEIQSXMKKRBJ08H
- key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
# Using a profile from pillars
Ensure mysecgroup exists:
boto_secgroup.present:
- name: mysecgroup
- description: My security group
- profile: myprofile
# Passing in a profile
Ensure mysecgroup exists:
boto_secgroup.present:
- name: mysecgroup
- description: My security group
- profile:
keyid: GKTADJGHEIQSXMKKRBJ08H
key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs
region: us-east-1
.. note::
When using the ``profile`` parameter and ``region`` is set outside of
the profile group, region is ignored and a default region will be used.
If ``region`` is missing from the ``profile`` data set, ``us-east-1``
will be used as the default region.
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import Python libs
import logging
import pprint
# Import salt libs
import salt.utils.dictupdate as dictupdate
from salt.exceptions import SaltInvocationError
from salt.ext import six
log = logging.getLogger(__name__)
def __virtual__():
'''
Only load if boto is available.
'''
return 'boto_secgroup' if 'boto_secgroup.exists' in __salt__ else False
def present(
name,
description,
vpc_id=None,
vpc_name=None,
rules=None,
rules_egress=None,
delete_ingress_rules=True,
delete_egress_rules=True,
region=None,
key=None,
keyid=None,
profile=None,
tags=None):
'''
Ensure the security group exists with the specified rules.
name
Name of the security group.
description
A description of this security group.
vpc_id
The ID of the VPC to create the security group in, if any. Exclusive with vpc_name.
vpc_name
The name of the VPC to create the security group in, if any. Exclusive with vpc_id.
.. versionadded:: 2016.3.0
.. versionadded:: 2015.8.2
rules
A list of ingress rule dicts. If not specified, ``rules=None``,
the ingress rules will be unmanaged. If set to an empty list, ``[]``,
then all ingress rules will be removed.
rules_egress
A list of egress rule dicts. If not specified, ``rules_egress=None``,
the egress rules will be unmanaged. If set to an empty list, ``[]``,
then all egress rules will be removed.
delete_ingress_rules
Some tools (EMR comes to mind) insist on adding rules on-the-fly, which
salt will happily remove on the next run. Set this param to False to
avoid deleting rules which were added outside of salt.
delete_egress_rules
Some tools (EMR comes to mind) insist on adding rules on-the-fly, which
salt will happily remove on the next run. Set this param to False to
avoid deleting rules which were added outside of salt.
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string)
that contains a dict with region, key, and keyid.
tags
List of key:value pairs of tags to set on the security group
.. versionadded:: 2016.3.0
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
_ret = _security_group_present(name, description, vpc_id=vpc_id,
vpc_name=vpc_name, region=region,
key=key, keyid=keyid, profile=profile)
ret['changes'] = _ret['changes']
ret['comment'] = ' '.join([ret['comment'], _ret['comment']])
if not _ret['result']:
ret['result'] = _ret['result']
if ret['result'] is False:
return ret
elif ret['result'] is None:
return ret
if rules is not None:
_ret = _rules_present(name, rules, delete_ingress_rules, vpc_id=vpc_id,
vpc_name=vpc_name, region=region, key=key,
keyid=keyid, profile=profile)
ret['changes'] = dictupdate.update(ret['changes'], _ret['changes'])
ret['comment'] = ' '.join([ret['comment'], _ret['comment']])
if not _ret['result']:
ret['result'] = _ret['result']
if rules_egress is not None:
_ret = _rules_egress_present(name, rules_egress, delete_egress_rules,
vpc_id=vpc_id, vpc_name=vpc_name,
region=region, key=key, keyid=keyid,
profile=profile)
ret['changes'] = dictupdate.update(ret['changes'], _ret['changes'])
ret['comment'] = ' '.join([ret['comment'], _ret['comment']])
if not _ret['result']:
ret['result'] = _ret['result']
_ret = _tags_present(
name=name, tags=tags, vpc_id=vpc_id, vpc_name=vpc_name,
region=region, key=key, keyid=keyid, profile=profile
)
ret['changes'] = dictupdate.update(ret['changes'], _ret['changes'])
ret['comment'] = ' '.join([ret['comment'], _ret['comment']])
if not _ret['result']:
ret['result'] = _ret['result']
return ret
def _security_group_present(name, description, vpc_id=None, vpc_name=None,
region=None, key=None, keyid=None, profile=None):
'''
given a group name or a group name and vpc id (or vpc name):
1. determine if the group exists
2. if the group does not exist, creates the group
3. return the group's configuration and any changes made
'''
ret = {'result': True, 'comment': '', 'changes': {}}
exists = __salt__['boto_secgroup.exists'](name, region, key, keyid,
profile, vpc_id, vpc_name)
if not exists:
if __opts__['test']:
ret['comment'] = 'Security group {0} is set to be created.'.format(name)
ret['result'] = None
return ret
created = __salt__['boto_secgroup.create'](name=name, description=description,
vpc_id=vpc_id, vpc_name=vpc_name,
region=region, key=key, keyid=keyid,
profile=profile)
if created:
ret['changes']['old'] = {'secgroup': None}
sg = __salt__['boto_secgroup.get_config'](name=name, group_id=None, region=region, key=key,
keyid=keyid, profile=profile, vpc_id=vpc_id,
vpc_name=vpc_name)
ret['changes']['new'] = {'secgroup': sg}
ret['comment'] = 'Security group {0} created.'.format(name)
else:
ret['result'] = False
ret['comment'] = 'Failed to create {0} security group.'.format(name)
else:
ret['comment'] = 'Security group {0} present.'.format(name)
return ret
def _split_rules(rules):
'''
Split rules with lists into individual rules.
We accept some attributes as lists or strings. The data we get back from
the execution module lists rules as individual rules. We need to split the
provided rules into individual rules to compare them.
'''
split = []
for rule in rules:
cidr_ip = rule.get('cidr_ip')
group_name = rule.get('source_group_name')
group_id = rule.get('source_group_group_id')
if cidr_ip and not isinstance(cidr_ip, six.string_types):
for ip in cidr_ip:
_rule = rule.copy()
_rule['cidr_ip'] = ip
split.append(_rule)
elif group_name and not isinstance(group_name, six.string_types):
for name in group_name:
_rule = rule.copy()
_rule['source_group_name'] = name
split.append(_rule)
elif group_id and not isinstance(group_id, six.string_types):
for _id in group_id:
_rule = rule.copy()
_rule['source_group_group_id'] = _id
split.append(_rule)
else:
split.append(rule)
return split
def _check_rule(rule, _rule):
'''
Check to see if two rules are the same. Needed to compare rules fetched
from boto, since they may not completely match rules defined in sls files
but may be functionally equivalent.
'''
# We need to alter what Boto returns if no ports are specified
# so that we can compare rules fairly.
#
# Boto returns None for from_port and to_port where we're required
# to pass in "-1" instead.
if _rule.get('from_port') is None:
_rule['from_port'] = -1
if _rule.get('to_port') is None:
_rule['to_port'] = -1
if (rule['ip_protocol'] == _rule['ip_protocol'] and
six.text_type(rule['from_port']) == six.text_type(_rule['from_port']) and
six.text_type(rule['to_port']) == six.text_type(_rule['to_port'])):
_cidr_ip = _rule.get('cidr_ip')
if _cidr_ip and _cidr_ip == rule.get('cidr_ip'):
return True
_owner_id = _rule.get('source_group_owner_id')
if _owner_id and _owner_id == rule.get('source_group_owner_id'):
return True
_group_id = _rule.get('source_group_group_id')
if _group_id and _group_id == rule.get('source_group_group_id'):
return True
_group_name = _rule.get('source_group_name')
if _group_name and _group_id == rule.get('source_group_name'):
return True
return False
def _get_rule_changes(rules, _rules):
'''
given a list of desired rules (rules) and existing rules (_rules) return
a list of rules to delete (to_delete) and to create (to_create)
'''
to_delete = []
to_create = []
# for each rule in state file
# 1. validate rule
# 2. determine if rule exists in existing security group rules
for rule in rules:
try:
ip_protocol = six.text_type(rule.get('ip_protocol'))
except KeyError:
raise SaltInvocationError('ip_protocol, to_port, and from_port are'
' required arguments for security group'
' rules.')
supported_protocols = ['tcp', '6', 6, 'udp', '17', 17, 'icmp', '1', 1,
'all', '-1', -1]
if ip_protocol not in supported_protocols and (not
'{0}'.format(ip_protocol).isdigit() or int(ip_protocol) > 255):
raise SaltInvocationError(
'Invalid ip_protocol {0} specified in security group rule.'.format(ip_protocol))
# For the 'all' case, we need to change the protocol name to '-1'.
if ip_protocol == 'all':
rule['ip_protocol'] = '-1'
cidr_ip = rule.get('cidr_ip', None)
group_name = rule.get('source_group_name', None)
group_id = rule.get('source_group_group_id', None)
if cidr_ip and (group_id or group_name):
raise SaltInvocationError('cidr_ip and source groups can not both'
' be specified in security group rules.')
if group_id and group_name:
raise SaltInvocationError('Either source_group_group_id or'
' source_group_name can be specified in'
' security group rules, but not both.')
if not (cidr_ip or group_id or group_name):
raise SaltInvocationError('cidr_ip, source_group_group_id, or'
' source_group_name must be provided for'
' security group rules.')
rule_found = False
# for each rule in existing security group ruleset determine if
# new rule exists
for _rule in _rules:
if _check_rule(rule, _rule):
rule_found = True
break
if not rule_found:
to_create.append(rule)
# for each rule in existing security group configuration
# 1. determine if rules needed to be deleted
for _rule in _rules:
rule_found = False
for rule in rules:
if _check_rule(rule, _rule):
rule_found = True
break
if not rule_found:
# Can only supply name or id, not both. Since we're deleting
# entries, it doesn't matter which we pick.
_rule.pop('source_group_name', None)
to_delete.append(_rule)
log.debug('Rules to be deleted: %s', to_delete)
log.debug('Rules to be created: %s', to_create)
return (to_delete, to_create)
def _rules_present(name, rules, delete_ingress_rules=True, vpc_id=None,
vpc_name=None, region=None, key=None, keyid=None, profile=None):
'''
given a group name or group name and vpc_id (or vpc name):
1. get lists of desired rule changes (using _get_rule_changes)
2. authorize/create rules missing rules
3. if delete_ingress_rules is True, delete/revoke non-requested rules
4. return 'old' and 'new' group rules
'''
ret = {'result': True, 'comment': '', 'changes': {}}
sg = __salt__['boto_secgroup.get_config'](name=name, group_id=None, region=region, key=key,
keyid=keyid, profile=profile, vpc_id=vpc_id,
vpc_name=vpc_name)
if not sg:
ret['comment'] = '{0} security group configuration could not be retrieved.'.format(name)
ret['result'] = False
return ret
rules = _split_rules(rules)
if vpc_id or vpc_name:
for rule in rules:
_source_group_name = rule.get('source_group_name', None)
if _source_group_name:
_group_vpc_name = vpc_name
_group_vpc_id = vpc_id
_source_group_name_vpc = rule.get('source_group_name_vpc', None)
if _source_group_name_vpc:
_group_vpc_name = _source_group_name_vpc
_group_vpc_id = None
_group_id = __salt__['boto_secgroup.get_group_id'](
name=_source_group_name, vpc_id=_group_vpc_id, vpc_name=_group_vpc_name,
region=region, key=key, keyid=keyid, profile=profile
)
if not _group_id:
raise SaltInvocationError(
'source_group_name {0} does not map to a valid '
'source group id.'.format(_source_group_name)
)
rule['source_group_name'] = None
if _source_group_name_vpc:
rule.pop('source_group_name_vpc')
rule['source_group_group_id'] = _group_id
# rules = rules that exist in salt state
# sg['rules'] = that exist in present group
to_delete, to_create = _get_rule_changes(rules, sg['rules'])
to_delete = to_delete if delete_ingress_rules else []
if to_create or to_delete:
if __opts__['test']:
msg = """Security group {0} set to have rules modified.
To be created: {1}
To be deleted: {2}""".format(name, pprint.pformat(to_create),
pprint.pformat(to_delete))
ret['comment'] = msg
ret['result'] = None
return ret
if to_delete:
deleted = True
for rule in to_delete:
_deleted = __salt__['boto_secgroup.revoke'](
name, vpc_id=vpc_id, vpc_name=vpc_name, region=region,
key=key, keyid=keyid, profile=profile, **rule)
if not _deleted:
deleted = False
if deleted:
ret['comment'] = 'Removed rules on {0} security group.'.format(name)
else:
ret['comment'] = 'Failed to remove rules on {0} security group.'.format(name)
ret['result'] = False
if to_create:
created = True
for rule in to_create:
_created = __salt__['boto_secgroup.authorize'](
name, vpc_id=vpc_id, vpc_name=vpc_name, region=region,
key=key, keyid=keyid, profile=profile, **rule)
if not _created:
created = False
if created:
ret['comment'] = ' '.join([
ret['comment'],
'Created rules on {0} security group.'.format(name)
])
else:
ret['comment'] = ' '.join([
ret['comment'],
'Failed to create rules on {0} security group.'.format(name)
])
ret['result'] = False
ret['changes']['old'] = {'rules': sg['rules']}
sg = __salt__['boto_secgroup.get_config'](name=name, group_id=None, region=region, key=key,
keyid=keyid, profile=profile, vpc_id=vpc_id,
vpc_name=vpc_name)
ret['changes']['new'] = {'rules': sg['rules']}
return ret
def _rules_egress_present(name, rules_egress, delete_egress_rules=True, vpc_id=None,
vpc_name=None, region=None, key=None, keyid=None, profile=None):
'''
given a group name or group name and vpc_id (or vpc name):
1. get lists of desired rule changes (using _get_rule_changes)
2. authorize/create missing rules
3. if delete_egress_rules is True, delete/revoke non-requested rules
4. return 'old' and 'new' group rules
'''
ret = {'result': True, 'comment': '', 'changes': {}}
sg = __salt__['boto_secgroup.get_config'](name=name, group_id=None, region=region, key=key,
keyid=keyid, profile=profile, vpc_id=vpc_id,
vpc_name=vpc_name)
if not sg:
ret['comment'] = '{0} security group configuration could not be retrieved.'.format(name)
ret['result'] = False
return ret
rules_egress = _split_rules(rules_egress)
if vpc_id or vpc_name:
for rule in rules_egress:
_source_group_name = rule.get('source_group_name', None)
if _source_group_name:
_group_vpc_name = vpc_name
_group_vpc_id = vpc_id
_source_group_name_vpc = rule.get('source_group_name_vpc', None)
if _source_group_name_vpc:
_group_vpc_name = _source_group_name_vpc
_group_vpc_id = None
_group_id = __salt__['boto_secgroup.get_group_id'](
name=_source_group_name, vpc_id=_group_vpc_id, vpc_name=_group_vpc_name,
region=region, key=key, keyid=keyid, profile=profile
)
if not _group_id:
raise SaltInvocationError(
'source_group_name {0} does not map to a valid '
'source group id.'.format(_source_group_name)
)
rule['source_group_name'] = None
if _source_group_name_vpc:
rule.pop('source_group_name_vpc')
rule['source_group_group_id'] = _group_id
# rules_egress = rules that exist in salt state
# sg['rules_egress'] = that exist in present group
to_delete, to_create = _get_rule_changes(rules_egress, sg['rules_egress'])
to_delete = to_delete if delete_egress_rules else []
if to_create or to_delete:
if __opts__['test']:
msg = """Security group {0} set to have rules modified.
To be created: {1}
To be deleted: {2}""".format(name, pprint.pformat(to_create),
pprint.pformat(to_delete))
ret['comment'] = msg
ret['result'] = None
return ret
if to_delete:
deleted = True
for rule in to_delete:
_deleted = __salt__['boto_secgroup.revoke'](
name, vpc_id=vpc_id, vpc_name=vpc_name, region=region,
key=key, keyid=keyid, profile=profile, egress=True, **rule)
if not _deleted:
deleted = False
if deleted:
ret['comment'] = ' '.join([
ret['comment'],
'Removed egress rule on {0} security group.'.format(name)
])
else:
ret['comment'] = ' '.join([
ret['comment'],
'Failed to remove egress rule on {0} security group.'.format(name)
])
ret['result'] = False
if to_create:
created = True
for rule in to_create:
_created = __salt__['boto_secgroup.authorize'](
name, vpc_id=vpc_id, vpc_name=vpc_name, region=region,
key=key, keyid=keyid, profile=profile, egress=True, **rule)
if not _created:
created = False
if created:
ret['comment'] = ' '.join([
ret['comment'],
'Created egress rules on {0} security group.'.format(name)
])
else:
ret['comment'] = ' '.join([
ret['comment'],
'Failed to create egress rules on {0} security group.'.format(name)
])
ret['result'] = False
ret['changes']['old'] = {'rules_egress': sg['rules_egress']}
sg = __salt__['boto_secgroup.get_config'](name=name, group_id=None, region=region, key=key,
keyid=keyid, profile=profile, vpc_id=vpc_id,
vpc_name=vpc_name)
ret['changes']['new'] = {'rules_egress': sg['rules_egress']}
return ret
def absent(
name,
vpc_id=None,
vpc_name=None,
region=None,
key=None,
keyid=None,
profile=None):
'''
Ensure a security group with the specified name does not exist.
name
Name of the security group.
vpc_id
The ID of the VPC to remove the security group from, if any. Exclusive with vpc_name.
vpc_name
The name of the VPC to remove the security group from, if any. Exclusive with vpc_name.
.. versionadded:: 2016.3.0
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string)
that contains a dict with region, key and keyid.
.. versionadded:: 2016.3.0
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
sg = __salt__['boto_secgroup.get_config'](name=name, group_id=None, region=region, key=key,
keyid=keyid, profile=profile, vpc_id=vpc_id,
vpc_name=vpc_name)
if sg:
if __opts__['test']:
ret['comment'] = 'Security group {0} is set to be removed.'.format(name)
ret['result'] = None
return ret
deleted = __salt__['boto_secgroup.delete'](name=name, group_id=None, region=region, key=key,
keyid=keyid, profile=profile, vpc_id=vpc_id,
vpc_name=vpc_name)
if deleted:
ret['changes']['old'] = {'secgroup': sg}
ret['changes']['new'] = {'secgroup': None}
ret['comment'] = 'Security group {0} deleted.'.format(name)
else:
ret['result'] = False
ret['comment'] = 'Failed to delete {0} security group.'.format(name)
else:
ret['comment'] = '{0} security group does not exist.'.format(name)
return ret
|
saltstack/salt
|
salt/states/ceph.py
|
_ordereddict2dict
|
python
|
def _ordereddict2dict(input_ordered_dict):
'''
Convert ordered dictionary to a dictionary
'''
return salt.utils.json.loads(salt.utils.json.dumps(input_ordered_dict))
|
Convert ordered dictionary to a dictionary
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/ceph.py#L47-L51
|
[
"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",
"def dumps(obj, **kwargs):\n '''\n .. versionadded:: 2018.3.0\n\n Wraps json.dumps, and assumes that ensure_ascii is False (unless explicitly\n passed as True) for unicode compatibility. Note that setting it to True\n will mess up any unicode characters, as they will be dumped as the string\n literal version of the unicode code point.\n\n On Python 2, encodes the result to a str since json.dumps does not want\n unicode types.\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 orig_enc_func = kwargs.pop('default', lambda x: x)\n\n def _enc_func(obj):\n obj = ThreadLocalProxy.unproxy(obj)\n return orig_enc_func(obj)\n\n if 'ensure_ascii' not in kwargs:\n kwargs['ensure_ascii'] = False\n if six.PY2:\n obj = salt.utils.data.encode(obj)\n return json_module.dumps(obj, default=_enc_func, **kwargs) # future lint: blacklisted-function\n"
] |
# -*- coding: utf-8 -*-
'''
Manage ceph with salt.
.. versionadded:: 2016.11.0
'''
# Import Python Libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import Salt Libs
import salt.utils.json
from salt.exceptions import CommandExecutionError, CommandNotFoundError
log = logging.getLogger(__name__)
def _unchanged(name, msg):
'''
Utility function: Return structure unchanged
'''
return {'name': name, 'result': True, 'comment': msg, 'changes': {}}
def _test(name, msg):
'''
Utility function: Return structure test
'''
return {'name': name, 'result': None, 'comment': msg, 'changes': {}}
def _error(name, msg):
'''
Utility function: Return structure error
'''
return {'name': name, 'result': False, 'comment': msg, 'changes': {}}
def _changed(name, msg, **changes):
'''
Utility function: Return structure changed
'''
return {'name': name, 'result': True, 'comment': msg, 'changes': changes}
def quorum(name, **kwargs):
'''
Quorum state
This state checks the mon daemons are in quorum. It does not alter the
cluster but can be used in formula as a dependency for many cluster
operations.
Example usage in sls file:
.. code-block:: yaml
quorum:
sesceph.quorum:
- require:
- sesceph: mon_running
'''
parameters = _ordereddict2dict(kwargs)
if parameters is None:
return _error(name, "Invalid parameters:%s")
if __opts__['test']:
return _test(name, "cluster quorum")
try:
cluster_quorum = __salt__['ceph.cluster_quorum'](**parameters)
except (CommandExecutionError, CommandNotFoundError) as err:
return _error(name, err.strerror)
if cluster_quorum:
return _unchanged(name, "cluster is quorum")
return _error(name, "cluster is not quorum")
|
saltstack/salt
|
salt/states/ceph.py
|
quorum
|
python
|
def quorum(name, **kwargs):
'''
Quorum state
This state checks the mon daemons are in quorum. It does not alter the
cluster but can be used in formula as a dependency for many cluster
operations.
Example usage in sls file:
.. code-block:: yaml
quorum:
sesceph.quorum:
- require:
- sesceph: mon_running
'''
parameters = _ordereddict2dict(kwargs)
if parameters is None:
return _error(name, "Invalid parameters:%s")
if __opts__['test']:
return _test(name, "cluster quorum")
try:
cluster_quorum = __salt__['ceph.cluster_quorum'](**parameters)
except (CommandExecutionError, CommandNotFoundError) as err:
return _error(name, err.strerror)
if cluster_quorum:
return _unchanged(name, "cluster is quorum")
return _error(name, "cluster is not quorum")
|
Quorum state
This state checks the mon daemons are in quorum. It does not alter the
cluster but can be used in formula as a dependency for many cluster
operations.
Example usage in sls file:
.. code-block:: yaml
quorum:
sesceph.quorum:
- require:
- sesceph: mon_running
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/ceph.py#L54-L83
|
[
"def _ordereddict2dict(input_ordered_dict):\n '''\n Convert ordered dictionary to a dictionary\n '''\n return salt.utils.json.loads(salt.utils.json.dumps(input_ordered_dict))\n"
] |
# -*- coding: utf-8 -*-
'''
Manage ceph with salt.
.. versionadded:: 2016.11.0
'''
# Import Python Libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import Salt Libs
import salt.utils.json
from salt.exceptions import CommandExecutionError, CommandNotFoundError
log = logging.getLogger(__name__)
def _unchanged(name, msg):
'''
Utility function: Return structure unchanged
'''
return {'name': name, 'result': True, 'comment': msg, 'changes': {}}
def _test(name, msg):
'''
Utility function: Return structure test
'''
return {'name': name, 'result': None, 'comment': msg, 'changes': {}}
def _error(name, msg):
'''
Utility function: Return structure error
'''
return {'name': name, 'result': False, 'comment': msg, 'changes': {}}
def _changed(name, msg, **changes):
'''
Utility function: Return structure changed
'''
return {'name': name, 'result': True, 'comment': msg, 'changes': changes}
def _ordereddict2dict(input_ordered_dict):
'''
Convert ordered dictionary to a dictionary
'''
return salt.utils.json.loads(salt.utils.json.dumps(input_ordered_dict))
|
saltstack/salt
|
salt/pillar/consul_pillar.py
|
ext_pillar
|
python
|
def ext_pillar(minion_id,
pillar, # pylint: disable=W0613
conf):
'''
Check consul for all data
'''
opts = {}
temp = conf
target_re = re.compile('target="(.*?)"')
match = target_re.search(temp)
if match:
opts['target'] = match.group(1)
temp = temp.replace(match.group(0), '')
checker = salt.utils.minions.CkMinions(__opts__)
_res = checker.check_minions(opts['target'], 'compound')
minions = _res['minions']
log.debug('Targeted minions: %r', minions)
if minion_id not in minions:
return {}
root_re = re.compile('(?<!_)root=(\S*)') # pylint: disable=W1401
match = root_re.search(temp)
if match:
opts['root'] = match.group(1).rstrip('/')
temp = temp.replace(match.group(0), '')
else:
opts['root'] = ""
pillar_root_re = re.compile('pillar_root=(\S*)') # pylint: disable=W1401
match = pillar_root_re.search(temp)
if match:
opts['pillar_root'] = match.group(1).rstrip('/')
temp = temp.replace(match.group(0), '')
else:
opts['pillar_root'] = ""
profile_re = re.compile('(?:profile=)?(\S+)') # pylint: disable=W1401
match = profile_re.search(temp)
if match:
opts['profile'] = match.group(1)
temp = temp.replace(match.group(0), '')
else:
opts['profile'] = None
expand_keys_re = re.compile('expand_keys=False', re.IGNORECASE) # pylint: disable=W1401
match = expand_keys_re.search(temp)
if match:
opts['expand_keys'] = False
temp = temp.replace(match.group(0), '')
else:
opts['expand_keys'] = True
client = get_conn(__opts__, opts['profile'])
role = __salt__['grains.get']('role', None)
environment = __salt__['grains.get']('environment', None)
# put the minion's ID in the path if necessary
opts['root'] %= {
'minion_id': minion_id,
'role': role,
'environment': environment
}
try:
pillar_tree = fetch_tree(client, opts['root'], opts['expand_keys'])
if opts['pillar_root']:
log.debug('Merging consul path %s/ into pillar at %s/', opts['root'], opts['pillar_root'])
pillar = {}
branch = pillar
keys = opts['pillar_root'].split('/')
for i, k in enumerate(keys):
if i == len(keys) - 1:
branch[k] = pillar_tree
else:
branch[k] = {}
branch = branch[k]
else:
pillar = pillar_tree
except KeyError:
log.error('No such key in consul profile %s: %s', opts['profile'], opts['root'])
pillar = {}
return pillar
|
Check consul for all data
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/pillar/consul_pillar.py#L170-L254
|
[
"def get_conn(opts, profile):\n\n '''\n Return a client object for accessing consul\n '''\n opts_pillar = opts.get('pillar', {})\n opts_master = opts_pillar.get('master', {})\n\n opts_merged = {}\n opts_merged.update(opts_master)\n opts_merged.update(opts_pillar)\n opts_merged.update(opts)\n\n if profile:\n conf = opts_merged.get(profile, {})\n else:\n conf = opts_merged\n\n params = {}\n for key in conf:\n if key.startswith('consul.'):\n params[key.split('.')[1]] = conf[key]\n\n if 'dc' in params:\n pillarenv = opts_merged.get('pillarenv') or 'base'\n params['dc'] = _resolve_datacenter(params['dc'], pillarenv)\n\n if consul:\n # Sanity check. ACL Tokens are supported on python-consul 0.4.7 onwards only.\n if consul.__version__ < '0.4.7' and params.get('target'):\n params.pop('target')\n return consul.Consul(**params)\n else:\n raise CommandExecutionError(\n '(unable to import consul, '\n 'module most likely not installed. Download python-consul '\n 'module and be sure to import consul)'\n )\n",
"def fetch_tree(client, path, expand_keys):\n '''\n Grab data from consul, trim base path and remove any keys which\n are folders. Take the remaining data and send it to be formatted\n in such a way as to be used as pillar data.\n '''\n _, items = consul_fetch(client, path)\n ret = {}\n has_children = re.compile(r'/$')\n\n log.debug('Fetched items: %r', items)\n\n if items is None:\n return ret\n for item in reversed(items):\n key = re.sub(r'^' + re.escape(path) + '/?', '', item['Key'])\n if key != '':\n log.debug('path/key - %s: %s', path, key)\n log.debug('has_children? %r', has_children.search(key))\n if has_children.search(key) is None:\n ret = pillar_format(ret, key.split('/'), item['Value'], expand_keys)\n log.debug('Fetching subkeys for key: %r', item)\n\n return ret\n",
"def check_minions(self,\n expr,\n tgt_type='glob',\n delimiter=DEFAULT_TARGET_DELIM,\n greedy=True):\n '''\n Check the passed regex against the available minions' public keys\n stored for authentication. This should return a set of ids which\n match the regex, this will then be used to parse the returns to\n make sure everyone has checked back in.\n '''\n\n try:\n if expr is None:\n expr = ''\n check_func = getattr(self, '_check_{0}_minions'.format(tgt_type), None)\n if tgt_type in ('grain',\n 'grain_pcre',\n 'pillar',\n 'pillar_pcre',\n 'pillar_exact',\n 'compound',\n 'compound_pillar_exact'):\n _res = check_func(expr, delimiter, greedy)\n else:\n _res = check_func(expr, greedy)\n _res['ssh_minions'] = False\n if self.opts.get('enable_ssh_minions', False) is True and isinstance('tgt', six.string_types):\n roster = salt.roster.Roster(self.opts, self.opts.get('roster', 'flat'))\n ssh_minions = roster.targets(expr, tgt_type)\n if ssh_minions:\n _res['minions'].extend(ssh_minions)\n _res['ssh_minions'] = True\n except Exception:\n log.exception(\n 'Failed matching available minions with %s pattern: %s',\n tgt_type, expr)\n _res = {'minions': [], 'missing': []}\n return _res\n"
] |
# -*- coding: utf-8 -*-
'''
Use Consul K/V as a Pillar source with values parsed as YAML
:depends: - python-consul
In order to use an consul server, a profile must be created in the master
configuration file:
.. code-block:: yaml
my_consul_config:
consul.host: 127.0.0.1
consul.port: 8500
consul.token: b6376760-a8bb-edd5-fcda-33bc13bfc556
consul.scheme: http
consul.consistency: default
consul.dc: dev
consul.verify: True
All parameters are optional.
The ``consul.token`` requires python-consul >= 0.4.7.
If you have a multi-datacenter Consul cluster you can map your ``pillarenv``s
to your data centers by providing a dictionary of mappings in ``consul.dc``
field:
.. code-block:: yaml
my_consul_config:
consul.dc:
dev: us-east-1
prod: us-west-1
In the example above we specifying static mapping between Pillar environments
and data centers: the data for ``dev`` and ``prod`` Pillar environments will
be fetched from ``us-east-1`` and ``us-west-1`` datacenter respectively.
In fact when ``consul.dc`` is set to dictionary keys are processed as regular
expressions (that can capture named parameters) and values are processed as
string templates as per PEP 3101.
.. code-block:: yaml
my_consul_config:
consul.dc:
^dev-.*$: dev-datacenter
^(?P<region>.*)-prod$: prod-datacenter-{region}
This example maps all Pillar environments starting with ``dev-`` to
``dev-datacenter`` whereas Pillar environment like ``eu-prod`` will be
mapped to ``prod-datacenter-eu``.
Before evaluation patterns are sorted by length in descending order.
If Pillar environment names correspond to data center names a single pattern
can be used:
.. code-block:: yaml
my_consul_config:
consul.dc:
^(?P<env>.*)$: '{env}'
After the profile is created, configure the external pillar system to use it.
Optionally, a root may be specified.
.. code-block:: yaml
ext_pillar:
- consul: my_consul_config
ext_pillar:
- consul: my_consul_config root=salt
Using these configuration profiles, multiple consul sources may also be used:
.. code-block:: yaml
ext_pillar:
- consul: my_consul_config
- consul: my_other_consul_config
Either the ``minion_id``, or the ``role``, or the ``environment`` grain may be used in the ``root``
path to expose minion-specific information stored in consul.
.. code-block:: yaml
ext_pillar:
- consul: my_consul_config root=salt/%(minion_id)s
- consul: my_consul_config root=salt/%(role)s
- consul: my_consul_config root=salt/%(environment)s
Minion-specific values may override shared values when the minion-specific root
appears after the shared root:
.. code-block:: yaml
ext_pillar:
- consul: my_consul_config root=salt-shared
- consul: my_other_consul_config root=salt-private/%(minion_id)s
If using the ``role`` or ``environment`` grain in the consul key path, be sure to define it using
`/etc/salt/grains`, or similar:
.. code-block:: yaml
role: my-minion-role
environment: dev
It's possible to lock down where the pillar values are shared through minion
targeting. Note that double quotes ``"`` are required around the target value
and cannot be used inside the matching statement. See the section on Compound
Matchers for more examples.
.. code-block:: yaml
ext_pillar:
- consul: my_consul_config root=salt target="L@salt.example.com and G@osarch:x86_64"
The data from Consul can be merged into a nested key in Pillar.
.. code-block:: yaml
ext_pillar:
- consul: my_consul_config pillar_root=consul_data
By default, keys containing YAML data will be deserialized before being merged into Pillar.
This behavior can be disabled by setting ``expand_keys`` to ``false``.
.. code-block:: yaml
ext_pillar:
- consul: my_consul_config expand_keys=false
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import logging
import re
from salt.exceptions import CommandExecutionError
from salt.utils.dictupdate import update as dict_merge
import salt.utils.minions
import salt.utils.yaml
# Import third party libs
try:
import consul
if not hasattr(consul, '__version__'):
consul.__version__ = '0.1' # Some packages has no version, and so this pillar crashes on access to it.
except ImportError:
consul = None
__virtualname__ = 'consul'
# Set up logging
log = logging.getLogger(__name__)
def __virtual__():
'''
Only return if python-consul is installed
'''
return __virtualname__ if consul is not None else False
def consul_fetch(client, path):
'''
Query consul for all keys/values within base path
'''
# Unless the root path is blank, it needs a trailing slash for
# the kv get from Consul to work as expected
return client.kv.get('' if not path else path.rstrip('/') + '/', recurse=True)
def fetch_tree(client, path, expand_keys):
'''
Grab data from consul, trim base path and remove any keys which
are folders. Take the remaining data and send it to be formatted
in such a way as to be used as pillar data.
'''
_, items = consul_fetch(client, path)
ret = {}
has_children = re.compile(r'/$')
log.debug('Fetched items: %r', items)
if items is None:
return ret
for item in reversed(items):
key = re.sub(r'^' + re.escape(path) + '/?', '', item['Key'])
if key != '':
log.debug('path/key - %s: %s', path, key)
log.debug('has_children? %r', has_children.search(key))
if has_children.search(key) is None:
ret = pillar_format(ret, key.split('/'), item['Value'], expand_keys)
log.debug('Fetching subkeys for key: %r', item)
return ret
def pillar_format(ret, keys, value, expand_keys):
'''
Perform data formatting to be used as pillar data and
merge it with the current pillar data
'''
# if value is empty in Consul then it's None here - skip it
if value is None:
return ret
# If value is not None then it's a string
# YAML strips whitespaces unless they're surrounded by quotes
# If expand_keys is true, deserialize the YAML data
if expand_keys:
pillar_value = salt.utils.yaml.safe_load(value)
else:
pillar_value = value
keyvalue = keys.pop()
pil = {keyvalue: pillar_value}
keys.reverse()
for k in keys:
pil = {k: pil}
return dict_merge(ret, pil)
def get_conn(opts, profile):
'''
Return a client object for accessing consul
'''
opts_pillar = opts.get('pillar', {})
opts_master = opts_pillar.get('master', {})
opts_merged = {}
opts_merged.update(opts_master)
opts_merged.update(opts_pillar)
opts_merged.update(opts)
if profile:
conf = opts_merged.get(profile, {})
else:
conf = opts_merged
params = {}
for key in conf:
if key.startswith('consul.'):
params[key.split('.')[1]] = conf[key]
if 'dc' in params:
pillarenv = opts_merged.get('pillarenv') or 'base'
params['dc'] = _resolve_datacenter(params['dc'], pillarenv)
if consul:
# Sanity check. ACL Tokens are supported on python-consul 0.4.7 onwards only.
if consul.__version__ < '0.4.7' and params.get('target'):
params.pop('target')
return consul.Consul(**params)
else:
raise CommandExecutionError(
'(unable to import consul, '
'module most likely not installed. Download python-consul '
'module and be sure to import consul)'
)
def _resolve_datacenter(dc, pillarenv):
'''
If ``dc`` is a string - return it as is.
If it's a dict then sort it in descending order by key length and try
to use keys as RegEx patterns to match against ``pillarenv``.
The value for matched pattern should be a string (that can use
``str.format`` syntax togetehr with captured variables from pattern)
pointing to targe data center to use.
If none patterns matched return ``None`` which meanse us datacenter of
conencted Consul agent.
'''
log.debug('Resolving Consul datacenter based on: %s', dc)
try:
mappings = dc.items() # is it a dict?
except AttributeError:
log.debug('Using pre-defined DC: \'%s\'', dc)
return dc
log.debug('Selecting DC based on pillarenv using %d pattern(s)', len(mappings))
log.debug('Pillarenv set to \'%s\'', pillarenv)
# sort in reverse based on pattern length
# but use alphabetic order within groups of patterns of same length
sorted_mappings = sorted(mappings, key=lambda m: (-len(m[0]), m[0]))
for pattern, target in sorted_mappings:
match = re.match(pattern, pillarenv)
if match:
log.debug('Matched pattern: \'%s\'', pattern)
result = target.format(**match.groupdict())
log.debug('Resolved datacenter: \'%s\'', result)
return result
log.debug(
'None of following patterns matched pillarenv=%s: %s',
pillarenv, ', '.join(repr(x) for x in mappings)
)
|
saltstack/salt
|
salt/pillar/consul_pillar.py
|
consul_fetch
|
python
|
def consul_fetch(client, path):
'''
Query consul for all keys/values within base path
'''
# Unless the root path is blank, it needs a trailing slash for
# the kv get from Consul to work as expected
return client.kv.get('' if not path else path.rstrip('/') + '/', recurse=True)
|
Query consul for all keys/values within base path
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/pillar/consul_pillar.py#L257-L263
| null |
# -*- coding: utf-8 -*-
'''
Use Consul K/V as a Pillar source with values parsed as YAML
:depends: - python-consul
In order to use an consul server, a profile must be created in the master
configuration file:
.. code-block:: yaml
my_consul_config:
consul.host: 127.0.0.1
consul.port: 8500
consul.token: b6376760-a8bb-edd5-fcda-33bc13bfc556
consul.scheme: http
consul.consistency: default
consul.dc: dev
consul.verify: True
All parameters are optional.
The ``consul.token`` requires python-consul >= 0.4.7.
If you have a multi-datacenter Consul cluster you can map your ``pillarenv``s
to your data centers by providing a dictionary of mappings in ``consul.dc``
field:
.. code-block:: yaml
my_consul_config:
consul.dc:
dev: us-east-1
prod: us-west-1
In the example above we specifying static mapping between Pillar environments
and data centers: the data for ``dev`` and ``prod`` Pillar environments will
be fetched from ``us-east-1`` and ``us-west-1`` datacenter respectively.
In fact when ``consul.dc`` is set to dictionary keys are processed as regular
expressions (that can capture named parameters) and values are processed as
string templates as per PEP 3101.
.. code-block:: yaml
my_consul_config:
consul.dc:
^dev-.*$: dev-datacenter
^(?P<region>.*)-prod$: prod-datacenter-{region}
This example maps all Pillar environments starting with ``dev-`` to
``dev-datacenter`` whereas Pillar environment like ``eu-prod`` will be
mapped to ``prod-datacenter-eu``.
Before evaluation patterns are sorted by length in descending order.
If Pillar environment names correspond to data center names a single pattern
can be used:
.. code-block:: yaml
my_consul_config:
consul.dc:
^(?P<env>.*)$: '{env}'
After the profile is created, configure the external pillar system to use it.
Optionally, a root may be specified.
.. code-block:: yaml
ext_pillar:
- consul: my_consul_config
ext_pillar:
- consul: my_consul_config root=salt
Using these configuration profiles, multiple consul sources may also be used:
.. code-block:: yaml
ext_pillar:
- consul: my_consul_config
- consul: my_other_consul_config
Either the ``minion_id``, or the ``role``, or the ``environment`` grain may be used in the ``root``
path to expose minion-specific information stored in consul.
.. code-block:: yaml
ext_pillar:
- consul: my_consul_config root=salt/%(minion_id)s
- consul: my_consul_config root=salt/%(role)s
- consul: my_consul_config root=salt/%(environment)s
Minion-specific values may override shared values when the minion-specific root
appears after the shared root:
.. code-block:: yaml
ext_pillar:
- consul: my_consul_config root=salt-shared
- consul: my_other_consul_config root=salt-private/%(minion_id)s
If using the ``role`` or ``environment`` grain in the consul key path, be sure to define it using
`/etc/salt/grains`, or similar:
.. code-block:: yaml
role: my-minion-role
environment: dev
It's possible to lock down where the pillar values are shared through minion
targeting. Note that double quotes ``"`` are required around the target value
and cannot be used inside the matching statement. See the section on Compound
Matchers for more examples.
.. code-block:: yaml
ext_pillar:
- consul: my_consul_config root=salt target="L@salt.example.com and G@osarch:x86_64"
The data from Consul can be merged into a nested key in Pillar.
.. code-block:: yaml
ext_pillar:
- consul: my_consul_config pillar_root=consul_data
By default, keys containing YAML data will be deserialized before being merged into Pillar.
This behavior can be disabled by setting ``expand_keys`` to ``false``.
.. code-block:: yaml
ext_pillar:
- consul: my_consul_config expand_keys=false
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import logging
import re
from salt.exceptions import CommandExecutionError
from salt.utils.dictupdate import update as dict_merge
import salt.utils.minions
import salt.utils.yaml
# Import third party libs
try:
import consul
if not hasattr(consul, '__version__'):
consul.__version__ = '0.1' # Some packages has no version, and so this pillar crashes on access to it.
except ImportError:
consul = None
__virtualname__ = 'consul'
# Set up logging
log = logging.getLogger(__name__)
def __virtual__():
'''
Only return if python-consul is installed
'''
return __virtualname__ if consul is not None else False
def ext_pillar(minion_id,
pillar, # pylint: disable=W0613
conf):
'''
Check consul for all data
'''
opts = {}
temp = conf
target_re = re.compile('target="(.*?)"')
match = target_re.search(temp)
if match:
opts['target'] = match.group(1)
temp = temp.replace(match.group(0), '')
checker = salt.utils.minions.CkMinions(__opts__)
_res = checker.check_minions(opts['target'], 'compound')
minions = _res['minions']
log.debug('Targeted minions: %r', minions)
if minion_id not in minions:
return {}
root_re = re.compile('(?<!_)root=(\S*)') # pylint: disable=W1401
match = root_re.search(temp)
if match:
opts['root'] = match.group(1).rstrip('/')
temp = temp.replace(match.group(0), '')
else:
opts['root'] = ""
pillar_root_re = re.compile('pillar_root=(\S*)') # pylint: disable=W1401
match = pillar_root_re.search(temp)
if match:
opts['pillar_root'] = match.group(1).rstrip('/')
temp = temp.replace(match.group(0), '')
else:
opts['pillar_root'] = ""
profile_re = re.compile('(?:profile=)?(\S+)') # pylint: disable=W1401
match = profile_re.search(temp)
if match:
opts['profile'] = match.group(1)
temp = temp.replace(match.group(0), '')
else:
opts['profile'] = None
expand_keys_re = re.compile('expand_keys=False', re.IGNORECASE) # pylint: disable=W1401
match = expand_keys_re.search(temp)
if match:
opts['expand_keys'] = False
temp = temp.replace(match.group(0), '')
else:
opts['expand_keys'] = True
client = get_conn(__opts__, opts['profile'])
role = __salt__['grains.get']('role', None)
environment = __salt__['grains.get']('environment', None)
# put the minion's ID in the path if necessary
opts['root'] %= {
'minion_id': minion_id,
'role': role,
'environment': environment
}
try:
pillar_tree = fetch_tree(client, opts['root'], opts['expand_keys'])
if opts['pillar_root']:
log.debug('Merging consul path %s/ into pillar at %s/', opts['root'], opts['pillar_root'])
pillar = {}
branch = pillar
keys = opts['pillar_root'].split('/')
for i, k in enumerate(keys):
if i == len(keys) - 1:
branch[k] = pillar_tree
else:
branch[k] = {}
branch = branch[k]
else:
pillar = pillar_tree
except KeyError:
log.error('No such key in consul profile %s: %s', opts['profile'], opts['root'])
pillar = {}
return pillar
def fetch_tree(client, path, expand_keys):
'''
Grab data from consul, trim base path and remove any keys which
are folders. Take the remaining data and send it to be formatted
in such a way as to be used as pillar data.
'''
_, items = consul_fetch(client, path)
ret = {}
has_children = re.compile(r'/$')
log.debug('Fetched items: %r', items)
if items is None:
return ret
for item in reversed(items):
key = re.sub(r'^' + re.escape(path) + '/?', '', item['Key'])
if key != '':
log.debug('path/key - %s: %s', path, key)
log.debug('has_children? %r', has_children.search(key))
if has_children.search(key) is None:
ret = pillar_format(ret, key.split('/'), item['Value'], expand_keys)
log.debug('Fetching subkeys for key: %r', item)
return ret
def pillar_format(ret, keys, value, expand_keys):
'''
Perform data formatting to be used as pillar data and
merge it with the current pillar data
'''
# if value is empty in Consul then it's None here - skip it
if value is None:
return ret
# If value is not None then it's a string
# YAML strips whitespaces unless they're surrounded by quotes
# If expand_keys is true, deserialize the YAML data
if expand_keys:
pillar_value = salt.utils.yaml.safe_load(value)
else:
pillar_value = value
keyvalue = keys.pop()
pil = {keyvalue: pillar_value}
keys.reverse()
for k in keys:
pil = {k: pil}
return dict_merge(ret, pil)
def get_conn(opts, profile):
'''
Return a client object for accessing consul
'''
opts_pillar = opts.get('pillar', {})
opts_master = opts_pillar.get('master', {})
opts_merged = {}
opts_merged.update(opts_master)
opts_merged.update(opts_pillar)
opts_merged.update(opts)
if profile:
conf = opts_merged.get(profile, {})
else:
conf = opts_merged
params = {}
for key in conf:
if key.startswith('consul.'):
params[key.split('.')[1]] = conf[key]
if 'dc' in params:
pillarenv = opts_merged.get('pillarenv') or 'base'
params['dc'] = _resolve_datacenter(params['dc'], pillarenv)
if consul:
# Sanity check. ACL Tokens are supported on python-consul 0.4.7 onwards only.
if consul.__version__ < '0.4.7' and params.get('target'):
params.pop('target')
return consul.Consul(**params)
else:
raise CommandExecutionError(
'(unable to import consul, '
'module most likely not installed. Download python-consul '
'module and be sure to import consul)'
)
def _resolve_datacenter(dc, pillarenv):
'''
If ``dc`` is a string - return it as is.
If it's a dict then sort it in descending order by key length and try
to use keys as RegEx patterns to match against ``pillarenv``.
The value for matched pattern should be a string (that can use
``str.format`` syntax togetehr with captured variables from pattern)
pointing to targe data center to use.
If none patterns matched return ``None`` which meanse us datacenter of
conencted Consul agent.
'''
log.debug('Resolving Consul datacenter based on: %s', dc)
try:
mappings = dc.items() # is it a dict?
except AttributeError:
log.debug('Using pre-defined DC: \'%s\'', dc)
return dc
log.debug('Selecting DC based on pillarenv using %d pattern(s)', len(mappings))
log.debug('Pillarenv set to \'%s\'', pillarenv)
# sort in reverse based on pattern length
# but use alphabetic order within groups of patterns of same length
sorted_mappings = sorted(mappings, key=lambda m: (-len(m[0]), m[0]))
for pattern, target in sorted_mappings:
match = re.match(pattern, pillarenv)
if match:
log.debug('Matched pattern: \'%s\'', pattern)
result = target.format(**match.groupdict())
log.debug('Resolved datacenter: \'%s\'', result)
return result
log.debug(
'None of following patterns matched pillarenv=%s: %s',
pillarenv, ', '.join(repr(x) for x in mappings)
)
|
saltstack/salt
|
salt/pillar/consul_pillar.py
|
fetch_tree
|
python
|
def fetch_tree(client, path, expand_keys):
'''
Grab data from consul, trim base path and remove any keys which
are folders. Take the remaining data and send it to be formatted
in such a way as to be used as pillar data.
'''
_, items = consul_fetch(client, path)
ret = {}
has_children = re.compile(r'/$')
log.debug('Fetched items: %r', items)
if items is None:
return ret
for item in reversed(items):
key = re.sub(r'^' + re.escape(path) + '/?', '', item['Key'])
if key != '':
log.debug('path/key - %s: %s', path, key)
log.debug('has_children? %r', has_children.search(key))
if has_children.search(key) is None:
ret = pillar_format(ret, key.split('/'), item['Value'], expand_keys)
log.debug('Fetching subkeys for key: %r', item)
return ret
|
Grab data from consul, trim base path and remove any keys which
are folders. Take the remaining data and send it to be formatted
in such a way as to be used as pillar data.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/pillar/consul_pillar.py#L266-L289
|
[
"def consul_fetch(client, path):\n '''\n Query consul for all keys/values within base path\n '''\n # Unless the root path is blank, it needs a trailing slash for\n # the kv get from Consul to work as expected\n return client.kv.get('' if not path else path.rstrip('/') + '/', recurse=True)\n",
"def pillar_format(ret, keys, value, expand_keys):\n '''\n Perform data formatting to be used as pillar data and\n merge it with the current pillar data\n '''\n # if value is empty in Consul then it's None here - skip it\n if value is None:\n return ret\n\n # If value is not None then it's a string\n # YAML strips whitespaces unless they're surrounded by quotes\n # If expand_keys is true, deserialize the YAML data\n if expand_keys:\n pillar_value = salt.utils.yaml.safe_load(value)\n else:\n pillar_value = value\n\n keyvalue = keys.pop()\n pil = {keyvalue: pillar_value}\n keys.reverse()\n for k in keys:\n pil = {k: pil}\n\n return dict_merge(ret, pil)\n"
] |
# -*- coding: utf-8 -*-
'''
Use Consul K/V as a Pillar source with values parsed as YAML
:depends: - python-consul
In order to use an consul server, a profile must be created in the master
configuration file:
.. code-block:: yaml
my_consul_config:
consul.host: 127.0.0.1
consul.port: 8500
consul.token: b6376760-a8bb-edd5-fcda-33bc13bfc556
consul.scheme: http
consul.consistency: default
consul.dc: dev
consul.verify: True
All parameters are optional.
The ``consul.token`` requires python-consul >= 0.4.7.
If you have a multi-datacenter Consul cluster you can map your ``pillarenv``s
to your data centers by providing a dictionary of mappings in ``consul.dc``
field:
.. code-block:: yaml
my_consul_config:
consul.dc:
dev: us-east-1
prod: us-west-1
In the example above we specifying static mapping between Pillar environments
and data centers: the data for ``dev`` and ``prod`` Pillar environments will
be fetched from ``us-east-1`` and ``us-west-1`` datacenter respectively.
In fact when ``consul.dc`` is set to dictionary keys are processed as regular
expressions (that can capture named parameters) and values are processed as
string templates as per PEP 3101.
.. code-block:: yaml
my_consul_config:
consul.dc:
^dev-.*$: dev-datacenter
^(?P<region>.*)-prod$: prod-datacenter-{region}
This example maps all Pillar environments starting with ``dev-`` to
``dev-datacenter`` whereas Pillar environment like ``eu-prod`` will be
mapped to ``prod-datacenter-eu``.
Before evaluation patterns are sorted by length in descending order.
If Pillar environment names correspond to data center names a single pattern
can be used:
.. code-block:: yaml
my_consul_config:
consul.dc:
^(?P<env>.*)$: '{env}'
After the profile is created, configure the external pillar system to use it.
Optionally, a root may be specified.
.. code-block:: yaml
ext_pillar:
- consul: my_consul_config
ext_pillar:
- consul: my_consul_config root=salt
Using these configuration profiles, multiple consul sources may also be used:
.. code-block:: yaml
ext_pillar:
- consul: my_consul_config
- consul: my_other_consul_config
Either the ``minion_id``, or the ``role``, or the ``environment`` grain may be used in the ``root``
path to expose minion-specific information stored in consul.
.. code-block:: yaml
ext_pillar:
- consul: my_consul_config root=salt/%(minion_id)s
- consul: my_consul_config root=salt/%(role)s
- consul: my_consul_config root=salt/%(environment)s
Minion-specific values may override shared values when the minion-specific root
appears after the shared root:
.. code-block:: yaml
ext_pillar:
- consul: my_consul_config root=salt-shared
- consul: my_other_consul_config root=salt-private/%(minion_id)s
If using the ``role`` or ``environment`` grain in the consul key path, be sure to define it using
`/etc/salt/grains`, or similar:
.. code-block:: yaml
role: my-minion-role
environment: dev
It's possible to lock down where the pillar values are shared through minion
targeting. Note that double quotes ``"`` are required around the target value
and cannot be used inside the matching statement. See the section on Compound
Matchers for more examples.
.. code-block:: yaml
ext_pillar:
- consul: my_consul_config root=salt target="L@salt.example.com and G@osarch:x86_64"
The data from Consul can be merged into a nested key in Pillar.
.. code-block:: yaml
ext_pillar:
- consul: my_consul_config pillar_root=consul_data
By default, keys containing YAML data will be deserialized before being merged into Pillar.
This behavior can be disabled by setting ``expand_keys`` to ``false``.
.. code-block:: yaml
ext_pillar:
- consul: my_consul_config expand_keys=false
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import logging
import re
from salt.exceptions import CommandExecutionError
from salt.utils.dictupdate import update as dict_merge
import salt.utils.minions
import salt.utils.yaml
# Import third party libs
try:
import consul
if not hasattr(consul, '__version__'):
consul.__version__ = '0.1' # Some packages has no version, and so this pillar crashes on access to it.
except ImportError:
consul = None
__virtualname__ = 'consul'
# Set up logging
log = logging.getLogger(__name__)
def __virtual__():
'''
Only return if python-consul is installed
'''
return __virtualname__ if consul is not None else False
def ext_pillar(minion_id,
pillar, # pylint: disable=W0613
conf):
'''
Check consul for all data
'''
opts = {}
temp = conf
target_re = re.compile('target="(.*?)"')
match = target_re.search(temp)
if match:
opts['target'] = match.group(1)
temp = temp.replace(match.group(0), '')
checker = salt.utils.minions.CkMinions(__opts__)
_res = checker.check_minions(opts['target'], 'compound')
minions = _res['minions']
log.debug('Targeted minions: %r', minions)
if minion_id not in minions:
return {}
root_re = re.compile('(?<!_)root=(\S*)') # pylint: disable=W1401
match = root_re.search(temp)
if match:
opts['root'] = match.group(1).rstrip('/')
temp = temp.replace(match.group(0), '')
else:
opts['root'] = ""
pillar_root_re = re.compile('pillar_root=(\S*)') # pylint: disable=W1401
match = pillar_root_re.search(temp)
if match:
opts['pillar_root'] = match.group(1).rstrip('/')
temp = temp.replace(match.group(0), '')
else:
opts['pillar_root'] = ""
profile_re = re.compile('(?:profile=)?(\S+)') # pylint: disable=W1401
match = profile_re.search(temp)
if match:
opts['profile'] = match.group(1)
temp = temp.replace(match.group(0), '')
else:
opts['profile'] = None
expand_keys_re = re.compile('expand_keys=False', re.IGNORECASE) # pylint: disable=W1401
match = expand_keys_re.search(temp)
if match:
opts['expand_keys'] = False
temp = temp.replace(match.group(0), '')
else:
opts['expand_keys'] = True
client = get_conn(__opts__, opts['profile'])
role = __salt__['grains.get']('role', None)
environment = __salt__['grains.get']('environment', None)
# put the minion's ID in the path if necessary
opts['root'] %= {
'minion_id': minion_id,
'role': role,
'environment': environment
}
try:
pillar_tree = fetch_tree(client, opts['root'], opts['expand_keys'])
if opts['pillar_root']:
log.debug('Merging consul path %s/ into pillar at %s/', opts['root'], opts['pillar_root'])
pillar = {}
branch = pillar
keys = opts['pillar_root'].split('/')
for i, k in enumerate(keys):
if i == len(keys) - 1:
branch[k] = pillar_tree
else:
branch[k] = {}
branch = branch[k]
else:
pillar = pillar_tree
except KeyError:
log.error('No such key in consul profile %s: %s', opts['profile'], opts['root'])
pillar = {}
return pillar
def consul_fetch(client, path):
'''
Query consul for all keys/values within base path
'''
# Unless the root path is blank, it needs a trailing slash for
# the kv get from Consul to work as expected
return client.kv.get('' if not path else path.rstrip('/') + '/', recurse=True)
def pillar_format(ret, keys, value, expand_keys):
'''
Perform data formatting to be used as pillar data and
merge it with the current pillar data
'''
# if value is empty in Consul then it's None here - skip it
if value is None:
return ret
# If value is not None then it's a string
# YAML strips whitespaces unless they're surrounded by quotes
# If expand_keys is true, deserialize the YAML data
if expand_keys:
pillar_value = salt.utils.yaml.safe_load(value)
else:
pillar_value = value
keyvalue = keys.pop()
pil = {keyvalue: pillar_value}
keys.reverse()
for k in keys:
pil = {k: pil}
return dict_merge(ret, pil)
def get_conn(opts, profile):
'''
Return a client object for accessing consul
'''
opts_pillar = opts.get('pillar', {})
opts_master = opts_pillar.get('master', {})
opts_merged = {}
opts_merged.update(opts_master)
opts_merged.update(opts_pillar)
opts_merged.update(opts)
if profile:
conf = opts_merged.get(profile, {})
else:
conf = opts_merged
params = {}
for key in conf:
if key.startswith('consul.'):
params[key.split('.')[1]] = conf[key]
if 'dc' in params:
pillarenv = opts_merged.get('pillarenv') or 'base'
params['dc'] = _resolve_datacenter(params['dc'], pillarenv)
if consul:
# Sanity check. ACL Tokens are supported on python-consul 0.4.7 onwards only.
if consul.__version__ < '0.4.7' and params.get('target'):
params.pop('target')
return consul.Consul(**params)
else:
raise CommandExecutionError(
'(unable to import consul, '
'module most likely not installed. Download python-consul '
'module and be sure to import consul)'
)
def _resolve_datacenter(dc, pillarenv):
'''
If ``dc`` is a string - return it as is.
If it's a dict then sort it in descending order by key length and try
to use keys as RegEx patterns to match against ``pillarenv``.
The value for matched pattern should be a string (that can use
``str.format`` syntax togetehr with captured variables from pattern)
pointing to targe data center to use.
If none patterns matched return ``None`` which meanse us datacenter of
conencted Consul agent.
'''
log.debug('Resolving Consul datacenter based on: %s', dc)
try:
mappings = dc.items() # is it a dict?
except AttributeError:
log.debug('Using pre-defined DC: \'%s\'', dc)
return dc
log.debug('Selecting DC based on pillarenv using %d pattern(s)', len(mappings))
log.debug('Pillarenv set to \'%s\'', pillarenv)
# sort in reverse based on pattern length
# but use alphabetic order within groups of patterns of same length
sorted_mappings = sorted(mappings, key=lambda m: (-len(m[0]), m[0]))
for pattern, target in sorted_mappings:
match = re.match(pattern, pillarenv)
if match:
log.debug('Matched pattern: \'%s\'', pattern)
result = target.format(**match.groupdict())
log.debug('Resolved datacenter: \'%s\'', result)
return result
log.debug(
'None of following patterns matched pillarenv=%s: %s',
pillarenv, ', '.join(repr(x) for x in mappings)
)
|
saltstack/salt
|
salt/pillar/consul_pillar.py
|
pillar_format
|
python
|
def pillar_format(ret, keys, value, expand_keys):
'''
Perform data formatting to be used as pillar data and
merge it with the current pillar data
'''
# if value is empty in Consul then it's None here - skip it
if value is None:
return ret
# If value is not None then it's a string
# YAML strips whitespaces unless they're surrounded by quotes
# If expand_keys is true, deserialize the YAML data
if expand_keys:
pillar_value = salt.utils.yaml.safe_load(value)
else:
pillar_value = value
keyvalue = keys.pop()
pil = {keyvalue: pillar_value}
keys.reverse()
for k in keys:
pil = {k: pil}
return dict_merge(ret, pil)
|
Perform data formatting to be used as pillar data and
merge it with the current pillar data
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/pillar/consul_pillar.py#L292-L315
|
[
"def update(dest, upd, recursive_update=True, merge_lists=False):\n '''\n Recursive version of the default dict.update\n\n Merges upd recursively into dest\n\n If recursive_update=False, will use the classic dict.update, or fall back\n on a manual merge (helpful for non-dict types like FunctionWrapper)\n\n If merge_lists=True, will aggregate list object types instead of replace.\n The list in ``upd`` is added to the list in ``dest``, so the resulting list\n is ``dest[key] + upd[key]``. This behavior is only activated when\n recursive_update=True. By default merge_lists=False.\n\n .. versionchanged: 2016.11.6\n When merging lists, duplicate values are removed. Values already\n present in the ``dest`` list are not added from the ``upd`` list.\n '''\n if (not isinstance(dest, Mapping)) \\\n or (not isinstance(upd, Mapping)):\n raise TypeError('Cannot update using non-dict types in dictupdate.update()')\n updkeys = list(upd.keys())\n if not set(list(dest.keys())) & set(updkeys):\n recursive_update = False\n if recursive_update:\n for key in updkeys:\n val = upd[key]\n try:\n dest_subkey = dest.get(key, None)\n except AttributeError:\n dest_subkey = None\n if isinstance(dest_subkey, Mapping) \\\n and isinstance(val, Mapping):\n ret = update(dest_subkey, val, merge_lists=merge_lists)\n dest[key] = ret\n elif isinstance(dest_subkey, list) and isinstance(val, list):\n if merge_lists:\n merged = copy.deepcopy(dest_subkey)\n merged.extend([x for x in val if x not in merged])\n dest[key] = merged\n else:\n dest[key] = upd[key]\n else:\n dest[key] = upd[key]\n return dest\n try:\n for k in upd:\n dest[k] = upd[k]\n except AttributeError:\n # this mapping is not a dict\n for k in upd:\n dest[k] = upd[k]\n return dest\n",
"def safe_load(stream, Loader=SaltYamlSafeLoader):\n '''\n .. versionadded:: 2018.3.0\n\n Helper function which automagically uses our custom loader.\n '''\n return yaml.load(stream, Loader=Loader)\n"
] |
# -*- coding: utf-8 -*-
'''
Use Consul K/V as a Pillar source with values parsed as YAML
:depends: - python-consul
In order to use an consul server, a profile must be created in the master
configuration file:
.. code-block:: yaml
my_consul_config:
consul.host: 127.0.0.1
consul.port: 8500
consul.token: b6376760-a8bb-edd5-fcda-33bc13bfc556
consul.scheme: http
consul.consistency: default
consul.dc: dev
consul.verify: True
All parameters are optional.
The ``consul.token`` requires python-consul >= 0.4.7.
If you have a multi-datacenter Consul cluster you can map your ``pillarenv``s
to your data centers by providing a dictionary of mappings in ``consul.dc``
field:
.. code-block:: yaml
my_consul_config:
consul.dc:
dev: us-east-1
prod: us-west-1
In the example above we specifying static mapping between Pillar environments
and data centers: the data for ``dev`` and ``prod`` Pillar environments will
be fetched from ``us-east-1`` and ``us-west-1`` datacenter respectively.
In fact when ``consul.dc`` is set to dictionary keys are processed as regular
expressions (that can capture named parameters) and values are processed as
string templates as per PEP 3101.
.. code-block:: yaml
my_consul_config:
consul.dc:
^dev-.*$: dev-datacenter
^(?P<region>.*)-prod$: prod-datacenter-{region}
This example maps all Pillar environments starting with ``dev-`` to
``dev-datacenter`` whereas Pillar environment like ``eu-prod`` will be
mapped to ``prod-datacenter-eu``.
Before evaluation patterns are sorted by length in descending order.
If Pillar environment names correspond to data center names a single pattern
can be used:
.. code-block:: yaml
my_consul_config:
consul.dc:
^(?P<env>.*)$: '{env}'
After the profile is created, configure the external pillar system to use it.
Optionally, a root may be specified.
.. code-block:: yaml
ext_pillar:
- consul: my_consul_config
ext_pillar:
- consul: my_consul_config root=salt
Using these configuration profiles, multiple consul sources may also be used:
.. code-block:: yaml
ext_pillar:
- consul: my_consul_config
- consul: my_other_consul_config
Either the ``minion_id``, or the ``role``, or the ``environment`` grain may be used in the ``root``
path to expose minion-specific information stored in consul.
.. code-block:: yaml
ext_pillar:
- consul: my_consul_config root=salt/%(minion_id)s
- consul: my_consul_config root=salt/%(role)s
- consul: my_consul_config root=salt/%(environment)s
Minion-specific values may override shared values when the minion-specific root
appears after the shared root:
.. code-block:: yaml
ext_pillar:
- consul: my_consul_config root=salt-shared
- consul: my_other_consul_config root=salt-private/%(minion_id)s
If using the ``role`` or ``environment`` grain in the consul key path, be sure to define it using
`/etc/salt/grains`, or similar:
.. code-block:: yaml
role: my-minion-role
environment: dev
It's possible to lock down where the pillar values are shared through minion
targeting. Note that double quotes ``"`` are required around the target value
and cannot be used inside the matching statement. See the section on Compound
Matchers for more examples.
.. code-block:: yaml
ext_pillar:
- consul: my_consul_config root=salt target="L@salt.example.com and G@osarch:x86_64"
The data from Consul can be merged into a nested key in Pillar.
.. code-block:: yaml
ext_pillar:
- consul: my_consul_config pillar_root=consul_data
By default, keys containing YAML data will be deserialized before being merged into Pillar.
This behavior can be disabled by setting ``expand_keys`` to ``false``.
.. code-block:: yaml
ext_pillar:
- consul: my_consul_config expand_keys=false
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import logging
import re
from salt.exceptions import CommandExecutionError
from salt.utils.dictupdate import update as dict_merge
import salt.utils.minions
import salt.utils.yaml
# Import third party libs
try:
import consul
if not hasattr(consul, '__version__'):
consul.__version__ = '0.1' # Some packages has no version, and so this pillar crashes on access to it.
except ImportError:
consul = None
__virtualname__ = 'consul'
# Set up logging
log = logging.getLogger(__name__)
def __virtual__():
'''
Only return if python-consul is installed
'''
return __virtualname__ if consul is not None else False
def ext_pillar(minion_id,
pillar, # pylint: disable=W0613
conf):
'''
Check consul for all data
'''
opts = {}
temp = conf
target_re = re.compile('target="(.*?)"')
match = target_re.search(temp)
if match:
opts['target'] = match.group(1)
temp = temp.replace(match.group(0), '')
checker = salt.utils.minions.CkMinions(__opts__)
_res = checker.check_minions(opts['target'], 'compound')
minions = _res['minions']
log.debug('Targeted minions: %r', minions)
if minion_id not in minions:
return {}
root_re = re.compile('(?<!_)root=(\S*)') # pylint: disable=W1401
match = root_re.search(temp)
if match:
opts['root'] = match.group(1).rstrip('/')
temp = temp.replace(match.group(0), '')
else:
opts['root'] = ""
pillar_root_re = re.compile('pillar_root=(\S*)') # pylint: disable=W1401
match = pillar_root_re.search(temp)
if match:
opts['pillar_root'] = match.group(1).rstrip('/')
temp = temp.replace(match.group(0), '')
else:
opts['pillar_root'] = ""
profile_re = re.compile('(?:profile=)?(\S+)') # pylint: disable=W1401
match = profile_re.search(temp)
if match:
opts['profile'] = match.group(1)
temp = temp.replace(match.group(0), '')
else:
opts['profile'] = None
expand_keys_re = re.compile('expand_keys=False', re.IGNORECASE) # pylint: disable=W1401
match = expand_keys_re.search(temp)
if match:
opts['expand_keys'] = False
temp = temp.replace(match.group(0), '')
else:
opts['expand_keys'] = True
client = get_conn(__opts__, opts['profile'])
role = __salt__['grains.get']('role', None)
environment = __salt__['grains.get']('environment', None)
# put the minion's ID in the path if necessary
opts['root'] %= {
'minion_id': minion_id,
'role': role,
'environment': environment
}
try:
pillar_tree = fetch_tree(client, opts['root'], opts['expand_keys'])
if opts['pillar_root']:
log.debug('Merging consul path %s/ into pillar at %s/', opts['root'], opts['pillar_root'])
pillar = {}
branch = pillar
keys = opts['pillar_root'].split('/')
for i, k in enumerate(keys):
if i == len(keys) - 1:
branch[k] = pillar_tree
else:
branch[k] = {}
branch = branch[k]
else:
pillar = pillar_tree
except KeyError:
log.error('No such key in consul profile %s: %s', opts['profile'], opts['root'])
pillar = {}
return pillar
def consul_fetch(client, path):
'''
Query consul for all keys/values within base path
'''
# Unless the root path is blank, it needs a trailing slash for
# the kv get from Consul to work as expected
return client.kv.get('' if not path else path.rstrip('/') + '/', recurse=True)
def fetch_tree(client, path, expand_keys):
'''
Grab data from consul, trim base path and remove any keys which
are folders. Take the remaining data and send it to be formatted
in such a way as to be used as pillar data.
'''
_, items = consul_fetch(client, path)
ret = {}
has_children = re.compile(r'/$')
log.debug('Fetched items: %r', items)
if items is None:
return ret
for item in reversed(items):
key = re.sub(r'^' + re.escape(path) + '/?', '', item['Key'])
if key != '':
log.debug('path/key - %s: %s', path, key)
log.debug('has_children? %r', has_children.search(key))
if has_children.search(key) is None:
ret = pillar_format(ret, key.split('/'), item['Value'], expand_keys)
log.debug('Fetching subkeys for key: %r', item)
return ret
def get_conn(opts, profile):
'''
Return a client object for accessing consul
'''
opts_pillar = opts.get('pillar', {})
opts_master = opts_pillar.get('master', {})
opts_merged = {}
opts_merged.update(opts_master)
opts_merged.update(opts_pillar)
opts_merged.update(opts)
if profile:
conf = opts_merged.get(profile, {})
else:
conf = opts_merged
params = {}
for key in conf:
if key.startswith('consul.'):
params[key.split('.')[1]] = conf[key]
if 'dc' in params:
pillarenv = opts_merged.get('pillarenv') or 'base'
params['dc'] = _resolve_datacenter(params['dc'], pillarenv)
if consul:
# Sanity check. ACL Tokens are supported on python-consul 0.4.7 onwards only.
if consul.__version__ < '0.4.7' and params.get('target'):
params.pop('target')
return consul.Consul(**params)
else:
raise CommandExecutionError(
'(unable to import consul, '
'module most likely not installed. Download python-consul '
'module and be sure to import consul)'
)
def _resolve_datacenter(dc, pillarenv):
'''
If ``dc`` is a string - return it as is.
If it's a dict then sort it in descending order by key length and try
to use keys as RegEx patterns to match against ``pillarenv``.
The value for matched pattern should be a string (that can use
``str.format`` syntax togetehr with captured variables from pattern)
pointing to targe data center to use.
If none patterns matched return ``None`` which meanse us datacenter of
conencted Consul agent.
'''
log.debug('Resolving Consul datacenter based on: %s', dc)
try:
mappings = dc.items() # is it a dict?
except AttributeError:
log.debug('Using pre-defined DC: \'%s\'', dc)
return dc
log.debug('Selecting DC based on pillarenv using %d pattern(s)', len(mappings))
log.debug('Pillarenv set to \'%s\'', pillarenv)
# sort in reverse based on pattern length
# but use alphabetic order within groups of patterns of same length
sorted_mappings = sorted(mappings, key=lambda m: (-len(m[0]), m[0]))
for pattern, target in sorted_mappings:
match = re.match(pattern, pillarenv)
if match:
log.debug('Matched pattern: \'%s\'', pattern)
result = target.format(**match.groupdict())
log.debug('Resolved datacenter: \'%s\'', result)
return result
log.debug(
'None of following patterns matched pillarenv=%s: %s',
pillarenv, ', '.join(repr(x) for x in mappings)
)
|
saltstack/salt
|
salt/pillar/consul_pillar.py
|
get_conn
|
python
|
def get_conn(opts, profile):
'''
Return a client object for accessing consul
'''
opts_pillar = opts.get('pillar', {})
opts_master = opts_pillar.get('master', {})
opts_merged = {}
opts_merged.update(opts_master)
opts_merged.update(opts_pillar)
opts_merged.update(opts)
if profile:
conf = opts_merged.get(profile, {})
else:
conf = opts_merged
params = {}
for key in conf:
if key.startswith('consul.'):
params[key.split('.')[1]] = conf[key]
if 'dc' in params:
pillarenv = opts_merged.get('pillarenv') or 'base'
params['dc'] = _resolve_datacenter(params['dc'], pillarenv)
if consul:
# Sanity check. ACL Tokens are supported on python-consul 0.4.7 onwards only.
if consul.__version__ < '0.4.7' and params.get('target'):
params.pop('target')
return consul.Consul(**params)
else:
raise CommandExecutionError(
'(unable to import consul, '
'module most likely not installed. Download python-consul '
'module and be sure to import consul)'
)
|
Return a client object for accessing consul
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/pillar/consul_pillar.py#L318-L355
|
[
"def _resolve_datacenter(dc, pillarenv):\n '''\n If ``dc`` is a string - return it as is.\n\n If it's a dict then sort it in descending order by key length and try\n to use keys as RegEx patterns to match against ``pillarenv``.\n The value for matched pattern should be a string (that can use\n ``str.format`` syntax togetehr with captured variables from pattern)\n pointing to targe data center to use.\n\n If none patterns matched return ``None`` which meanse us datacenter of\n conencted Consul agent.\n '''\n log.debug('Resolving Consul datacenter based on: %s', dc)\n\n try:\n mappings = dc.items() # is it a dict?\n except AttributeError:\n log.debug('Using pre-defined DC: \\'%s\\'', dc)\n return dc\n\n log.debug('Selecting DC based on pillarenv using %d pattern(s)', len(mappings))\n log.debug('Pillarenv set to \\'%s\\'', pillarenv)\n\n # sort in reverse based on pattern length\n # but use alphabetic order within groups of patterns of same length\n sorted_mappings = sorted(mappings, key=lambda m: (-len(m[0]), m[0]))\n\n for pattern, target in sorted_mappings:\n match = re.match(pattern, pillarenv)\n if match:\n log.debug('Matched pattern: \\'%s\\'', pattern)\n result = target.format(**match.groupdict())\n log.debug('Resolved datacenter: \\'%s\\'', result)\n return result\n\n log.debug(\n 'None of following patterns matched pillarenv=%s: %s',\n pillarenv, ', '.join(repr(x) for x in mappings)\n )\n"
] |
# -*- coding: utf-8 -*-
'''
Use Consul K/V as a Pillar source with values parsed as YAML
:depends: - python-consul
In order to use an consul server, a profile must be created in the master
configuration file:
.. code-block:: yaml
my_consul_config:
consul.host: 127.0.0.1
consul.port: 8500
consul.token: b6376760-a8bb-edd5-fcda-33bc13bfc556
consul.scheme: http
consul.consistency: default
consul.dc: dev
consul.verify: True
All parameters are optional.
The ``consul.token`` requires python-consul >= 0.4.7.
If you have a multi-datacenter Consul cluster you can map your ``pillarenv``s
to your data centers by providing a dictionary of mappings in ``consul.dc``
field:
.. code-block:: yaml
my_consul_config:
consul.dc:
dev: us-east-1
prod: us-west-1
In the example above we specifying static mapping between Pillar environments
and data centers: the data for ``dev`` and ``prod`` Pillar environments will
be fetched from ``us-east-1`` and ``us-west-1`` datacenter respectively.
In fact when ``consul.dc`` is set to dictionary keys are processed as regular
expressions (that can capture named parameters) and values are processed as
string templates as per PEP 3101.
.. code-block:: yaml
my_consul_config:
consul.dc:
^dev-.*$: dev-datacenter
^(?P<region>.*)-prod$: prod-datacenter-{region}
This example maps all Pillar environments starting with ``dev-`` to
``dev-datacenter`` whereas Pillar environment like ``eu-prod`` will be
mapped to ``prod-datacenter-eu``.
Before evaluation patterns are sorted by length in descending order.
If Pillar environment names correspond to data center names a single pattern
can be used:
.. code-block:: yaml
my_consul_config:
consul.dc:
^(?P<env>.*)$: '{env}'
After the profile is created, configure the external pillar system to use it.
Optionally, a root may be specified.
.. code-block:: yaml
ext_pillar:
- consul: my_consul_config
ext_pillar:
- consul: my_consul_config root=salt
Using these configuration profiles, multiple consul sources may also be used:
.. code-block:: yaml
ext_pillar:
- consul: my_consul_config
- consul: my_other_consul_config
Either the ``minion_id``, or the ``role``, or the ``environment`` grain may be used in the ``root``
path to expose minion-specific information stored in consul.
.. code-block:: yaml
ext_pillar:
- consul: my_consul_config root=salt/%(minion_id)s
- consul: my_consul_config root=salt/%(role)s
- consul: my_consul_config root=salt/%(environment)s
Minion-specific values may override shared values when the minion-specific root
appears after the shared root:
.. code-block:: yaml
ext_pillar:
- consul: my_consul_config root=salt-shared
- consul: my_other_consul_config root=salt-private/%(minion_id)s
If using the ``role`` or ``environment`` grain in the consul key path, be sure to define it using
`/etc/salt/grains`, or similar:
.. code-block:: yaml
role: my-minion-role
environment: dev
It's possible to lock down where the pillar values are shared through minion
targeting. Note that double quotes ``"`` are required around the target value
and cannot be used inside the matching statement. See the section on Compound
Matchers for more examples.
.. code-block:: yaml
ext_pillar:
- consul: my_consul_config root=salt target="L@salt.example.com and G@osarch:x86_64"
The data from Consul can be merged into a nested key in Pillar.
.. code-block:: yaml
ext_pillar:
- consul: my_consul_config pillar_root=consul_data
By default, keys containing YAML data will be deserialized before being merged into Pillar.
This behavior can be disabled by setting ``expand_keys`` to ``false``.
.. code-block:: yaml
ext_pillar:
- consul: my_consul_config expand_keys=false
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import logging
import re
from salt.exceptions import CommandExecutionError
from salt.utils.dictupdate import update as dict_merge
import salt.utils.minions
import salt.utils.yaml
# Import third party libs
try:
import consul
if not hasattr(consul, '__version__'):
consul.__version__ = '0.1' # Some packages has no version, and so this pillar crashes on access to it.
except ImportError:
consul = None
__virtualname__ = 'consul'
# Set up logging
log = logging.getLogger(__name__)
def __virtual__():
'''
Only return if python-consul is installed
'''
return __virtualname__ if consul is not None else False
def ext_pillar(minion_id,
pillar, # pylint: disable=W0613
conf):
'''
Check consul for all data
'''
opts = {}
temp = conf
target_re = re.compile('target="(.*?)"')
match = target_re.search(temp)
if match:
opts['target'] = match.group(1)
temp = temp.replace(match.group(0), '')
checker = salt.utils.minions.CkMinions(__opts__)
_res = checker.check_minions(opts['target'], 'compound')
minions = _res['minions']
log.debug('Targeted minions: %r', minions)
if minion_id not in minions:
return {}
root_re = re.compile('(?<!_)root=(\S*)') # pylint: disable=W1401
match = root_re.search(temp)
if match:
opts['root'] = match.group(1).rstrip('/')
temp = temp.replace(match.group(0), '')
else:
opts['root'] = ""
pillar_root_re = re.compile('pillar_root=(\S*)') # pylint: disable=W1401
match = pillar_root_re.search(temp)
if match:
opts['pillar_root'] = match.group(1).rstrip('/')
temp = temp.replace(match.group(0), '')
else:
opts['pillar_root'] = ""
profile_re = re.compile('(?:profile=)?(\S+)') # pylint: disable=W1401
match = profile_re.search(temp)
if match:
opts['profile'] = match.group(1)
temp = temp.replace(match.group(0), '')
else:
opts['profile'] = None
expand_keys_re = re.compile('expand_keys=False', re.IGNORECASE) # pylint: disable=W1401
match = expand_keys_re.search(temp)
if match:
opts['expand_keys'] = False
temp = temp.replace(match.group(0), '')
else:
opts['expand_keys'] = True
client = get_conn(__opts__, opts['profile'])
role = __salt__['grains.get']('role', None)
environment = __salt__['grains.get']('environment', None)
# put the minion's ID in the path if necessary
opts['root'] %= {
'minion_id': minion_id,
'role': role,
'environment': environment
}
try:
pillar_tree = fetch_tree(client, opts['root'], opts['expand_keys'])
if opts['pillar_root']:
log.debug('Merging consul path %s/ into pillar at %s/', opts['root'], opts['pillar_root'])
pillar = {}
branch = pillar
keys = opts['pillar_root'].split('/')
for i, k in enumerate(keys):
if i == len(keys) - 1:
branch[k] = pillar_tree
else:
branch[k] = {}
branch = branch[k]
else:
pillar = pillar_tree
except KeyError:
log.error('No such key in consul profile %s: %s', opts['profile'], opts['root'])
pillar = {}
return pillar
def consul_fetch(client, path):
'''
Query consul for all keys/values within base path
'''
# Unless the root path is blank, it needs a trailing slash for
# the kv get from Consul to work as expected
return client.kv.get('' if not path else path.rstrip('/') + '/', recurse=True)
def fetch_tree(client, path, expand_keys):
'''
Grab data from consul, trim base path and remove any keys which
are folders. Take the remaining data and send it to be formatted
in such a way as to be used as pillar data.
'''
_, items = consul_fetch(client, path)
ret = {}
has_children = re.compile(r'/$')
log.debug('Fetched items: %r', items)
if items is None:
return ret
for item in reversed(items):
key = re.sub(r'^' + re.escape(path) + '/?', '', item['Key'])
if key != '':
log.debug('path/key - %s: %s', path, key)
log.debug('has_children? %r', has_children.search(key))
if has_children.search(key) is None:
ret = pillar_format(ret, key.split('/'), item['Value'], expand_keys)
log.debug('Fetching subkeys for key: %r', item)
return ret
def pillar_format(ret, keys, value, expand_keys):
'''
Perform data formatting to be used as pillar data and
merge it with the current pillar data
'''
# if value is empty in Consul then it's None here - skip it
if value is None:
return ret
# If value is not None then it's a string
# YAML strips whitespaces unless they're surrounded by quotes
# If expand_keys is true, deserialize the YAML data
if expand_keys:
pillar_value = salt.utils.yaml.safe_load(value)
else:
pillar_value = value
keyvalue = keys.pop()
pil = {keyvalue: pillar_value}
keys.reverse()
for k in keys:
pil = {k: pil}
return dict_merge(ret, pil)
def _resolve_datacenter(dc, pillarenv):
'''
If ``dc`` is a string - return it as is.
If it's a dict then sort it in descending order by key length and try
to use keys as RegEx patterns to match against ``pillarenv``.
The value for matched pattern should be a string (that can use
``str.format`` syntax togetehr with captured variables from pattern)
pointing to targe data center to use.
If none patterns matched return ``None`` which meanse us datacenter of
conencted Consul agent.
'''
log.debug('Resolving Consul datacenter based on: %s', dc)
try:
mappings = dc.items() # is it a dict?
except AttributeError:
log.debug('Using pre-defined DC: \'%s\'', dc)
return dc
log.debug('Selecting DC based on pillarenv using %d pattern(s)', len(mappings))
log.debug('Pillarenv set to \'%s\'', pillarenv)
# sort in reverse based on pattern length
# but use alphabetic order within groups of patterns of same length
sorted_mappings = sorted(mappings, key=lambda m: (-len(m[0]), m[0]))
for pattern, target in sorted_mappings:
match = re.match(pattern, pillarenv)
if match:
log.debug('Matched pattern: \'%s\'', pattern)
result = target.format(**match.groupdict())
log.debug('Resolved datacenter: \'%s\'', result)
return result
log.debug(
'None of following patterns matched pillarenv=%s: %s',
pillarenv, ', '.join(repr(x) for x in mappings)
)
|
saltstack/salt
|
salt/pillar/consul_pillar.py
|
_resolve_datacenter
|
python
|
def _resolve_datacenter(dc, pillarenv):
'''
If ``dc`` is a string - return it as is.
If it's a dict then sort it in descending order by key length and try
to use keys as RegEx patterns to match against ``pillarenv``.
The value for matched pattern should be a string (that can use
``str.format`` syntax togetehr with captured variables from pattern)
pointing to targe data center to use.
If none patterns matched return ``None`` which meanse us datacenter of
conencted Consul agent.
'''
log.debug('Resolving Consul datacenter based on: %s', dc)
try:
mappings = dc.items() # is it a dict?
except AttributeError:
log.debug('Using pre-defined DC: \'%s\'', dc)
return dc
log.debug('Selecting DC based on pillarenv using %d pattern(s)', len(mappings))
log.debug('Pillarenv set to \'%s\'', pillarenv)
# sort in reverse based on pattern length
# but use alphabetic order within groups of patterns of same length
sorted_mappings = sorted(mappings, key=lambda m: (-len(m[0]), m[0]))
for pattern, target in sorted_mappings:
match = re.match(pattern, pillarenv)
if match:
log.debug('Matched pattern: \'%s\'', pattern)
result = target.format(**match.groupdict())
log.debug('Resolved datacenter: \'%s\'', result)
return result
log.debug(
'None of following patterns matched pillarenv=%s: %s',
pillarenv, ', '.join(repr(x) for x in mappings)
)
|
If ``dc`` is a string - return it as is.
If it's a dict then sort it in descending order by key length and try
to use keys as RegEx patterns to match against ``pillarenv``.
The value for matched pattern should be a string (that can use
``str.format`` syntax togetehr with captured variables from pattern)
pointing to targe data center to use.
If none patterns matched return ``None`` which meanse us datacenter of
conencted Consul agent.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/pillar/consul_pillar.py#L358-L397
| null |
# -*- coding: utf-8 -*-
'''
Use Consul K/V as a Pillar source with values parsed as YAML
:depends: - python-consul
In order to use an consul server, a profile must be created in the master
configuration file:
.. code-block:: yaml
my_consul_config:
consul.host: 127.0.0.1
consul.port: 8500
consul.token: b6376760-a8bb-edd5-fcda-33bc13bfc556
consul.scheme: http
consul.consistency: default
consul.dc: dev
consul.verify: True
All parameters are optional.
The ``consul.token`` requires python-consul >= 0.4.7.
If you have a multi-datacenter Consul cluster you can map your ``pillarenv``s
to your data centers by providing a dictionary of mappings in ``consul.dc``
field:
.. code-block:: yaml
my_consul_config:
consul.dc:
dev: us-east-1
prod: us-west-1
In the example above we specifying static mapping between Pillar environments
and data centers: the data for ``dev`` and ``prod`` Pillar environments will
be fetched from ``us-east-1`` and ``us-west-1`` datacenter respectively.
In fact when ``consul.dc`` is set to dictionary keys are processed as regular
expressions (that can capture named parameters) and values are processed as
string templates as per PEP 3101.
.. code-block:: yaml
my_consul_config:
consul.dc:
^dev-.*$: dev-datacenter
^(?P<region>.*)-prod$: prod-datacenter-{region}
This example maps all Pillar environments starting with ``dev-`` to
``dev-datacenter`` whereas Pillar environment like ``eu-prod`` will be
mapped to ``prod-datacenter-eu``.
Before evaluation patterns are sorted by length in descending order.
If Pillar environment names correspond to data center names a single pattern
can be used:
.. code-block:: yaml
my_consul_config:
consul.dc:
^(?P<env>.*)$: '{env}'
After the profile is created, configure the external pillar system to use it.
Optionally, a root may be specified.
.. code-block:: yaml
ext_pillar:
- consul: my_consul_config
ext_pillar:
- consul: my_consul_config root=salt
Using these configuration profiles, multiple consul sources may also be used:
.. code-block:: yaml
ext_pillar:
- consul: my_consul_config
- consul: my_other_consul_config
Either the ``minion_id``, or the ``role``, or the ``environment`` grain may be used in the ``root``
path to expose minion-specific information stored in consul.
.. code-block:: yaml
ext_pillar:
- consul: my_consul_config root=salt/%(minion_id)s
- consul: my_consul_config root=salt/%(role)s
- consul: my_consul_config root=salt/%(environment)s
Minion-specific values may override shared values when the minion-specific root
appears after the shared root:
.. code-block:: yaml
ext_pillar:
- consul: my_consul_config root=salt-shared
- consul: my_other_consul_config root=salt-private/%(minion_id)s
If using the ``role`` or ``environment`` grain in the consul key path, be sure to define it using
`/etc/salt/grains`, or similar:
.. code-block:: yaml
role: my-minion-role
environment: dev
It's possible to lock down where the pillar values are shared through minion
targeting. Note that double quotes ``"`` are required around the target value
and cannot be used inside the matching statement. See the section on Compound
Matchers for more examples.
.. code-block:: yaml
ext_pillar:
- consul: my_consul_config root=salt target="L@salt.example.com and G@osarch:x86_64"
The data from Consul can be merged into a nested key in Pillar.
.. code-block:: yaml
ext_pillar:
- consul: my_consul_config pillar_root=consul_data
By default, keys containing YAML data will be deserialized before being merged into Pillar.
This behavior can be disabled by setting ``expand_keys`` to ``false``.
.. code-block:: yaml
ext_pillar:
- consul: my_consul_config expand_keys=false
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import logging
import re
from salt.exceptions import CommandExecutionError
from salt.utils.dictupdate import update as dict_merge
import salt.utils.minions
import salt.utils.yaml
# Import third party libs
try:
import consul
if not hasattr(consul, '__version__'):
consul.__version__ = '0.1' # Some packages has no version, and so this pillar crashes on access to it.
except ImportError:
consul = None
__virtualname__ = 'consul'
# Set up logging
log = logging.getLogger(__name__)
def __virtual__():
'''
Only return if python-consul is installed
'''
return __virtualname__ if consul is not None else False
def ext_pillar(minion_id,
pillar, # pylint: disable=W0613
conf):
'''
Check consul for all data
'''
opts = {}
temp = conf
target_re = re.compile('target="(.*?)"')
match = target_re.search(temp)
if match:
opts['target'] = match.group(1)
temp = temp.replace(match.group(0), '')
checker = salt.utils.minions.CkMinions(__opts__)
_res = checker.check_minions(opts['target'], 'compound')
minions = _res['minions']
log.debug('Targeted minions: %r', minions)
if minion_id not in minions:
return {}
root_re = re.compile('(?<!_)root=(\S*)') # pylint: disable=W1401
match = root_re.search(temp)
if match:
opts['root'] = match.group(1).rstrip('/')
temp = temp.replace(match.group(0), '')
else:
opts['root'] = ""
pillar_root_re = re.compile('pillar_root=(\S*)') # pylint: disable=W1401
match = pillar_root_re.search(temp)
if match:
opts['pillar_root'] = match.group(1).rstrip('/')
temp = temp.replace(match.group(0), '')
else:
opts['pillar_root'] = ""
profile_re = re.compile('(?:profile=)?(\S+)') # pylint: disable=W1401
match = profile_re.search(temp)
if match:
opts['profile'] = match.group(1)
temp = temp.replace(match.group(0), '')
else:
opts['profile'] = None
expand_keys_re = re.compile('expand_keys=False', re.IGNORECASE) # pylint: disable=W1401
match = expand_keys_re.search(temp)
if match:
opts['expand_keys'] = False
temp = temp.replace(match.group(0), '')
else:
opts['expand_keys'] = True
client = get_conn(__opts__, opts['profile'])
role = __salt__['grains.get']('role', None)
environment = __salt__['grains.get']('environment', None)
# put the minion's ID in the path if necessary
opts['root'] %= {
'minion_id': minion_id,
'role': role,
'environment': environment
}
try:
pillar_tree = fetch_tree(client, opts['root'], opts['expand_keys'])
if opts['pillar_root']:
log.debug('Merging consul path %s/ into pillar at %s/', opts['root'], opts['pillar_root'])
pillar = {}
branch = pillar
keys = opts['pillar_root'].split('/')
for i, k in enumerate(keys):
if i == len(keys) - 1:
branch[k] = pillar_tree
else:
branch[k] = {}
branch = branch[k]
else:
pillar = pillar_tree
except KeyError:
log.error('No such key in consul profile %s: %s', opts['profile'], opts['root'])
pillar = {}
return pillar
def consul_fetch(client, path):
'''
Query consul for all keys/values within base path
'''
# Unless the root path is blank, it needs a trailing slash for
# the kv get from Consul to work as expected
return client.kv.get('' if not path else path.rstrip('/') + '/', recurse=True)
def fetch_tree(client, path, expand_keys):
'''
Grab data from consul, trim base path and remove any keys which
are folders. Take the remaining data and send it to be formatted
in such a way as to be used as pillar data.
'''
_, items = consul_fetch(client, path)
ret = {}
has_children = re.compile(r'/$')
log.debug('Fetched items: %r', items)
if items is None:
return ret
for item in reversed(items):
key = re.sub(r'^' + re.escape(path) + '/?', '', item['Key'])
if key != '':
log.debug('path/key - %s: %s', path, key)
log.debug('has_children? %r', has_children.search(key))
if has_children.search(key) is None:
ret = pillar_format(ret, key.split('/'), item['Value'], expand_keys)
log.debug('Fetching subkeys for key: %r', item)
return ret
def pillar_format(ret, keys, value, expand_keys):
'''
Perform data formatting to be used as pillar data and
merge it with the current pillar data
'''
# if value is empty in Consul then it's None here - skip it
if value is None:
return ret
# If value is not None then it's a string
# YAML strips whitespaces unless they're surrounded by quotes
# If expand_keys is true, deserialize the YAML data
if expand_keys:
pillar_value = salt.utils.yaml.safe_load(value)
else:
pillar_value = value
keyvalue = keys.pop()
pil = {keyvalue: pillar_value}
keys.reverse()
for k in keys:
pil = {k: pil}
return dict_merge(ret, pil)
def get_conn(opts, profile):
'''
Return a client object for accessing consul
'''
opts_pillar = opts.get('pillar', {})
opts_master = opts_pillar.get('master', {})
opts_merged = {}
opts_merged.update(opts_master)
opts_merged.update(opts_pillar)
opts_merged.update(opts)
if profile:
conf = opts_merged.get(profile, {})
else:
conf = opts_merged
params = {}
for key in conf:
if key.startswith('consul.'):
params[key.split('.')[1]] = conf[key]
if 'dc' in params:
pillarenv = opts_merged.get('pillarenv') or 'base'
params['dc'] = _resolve_datacenter(params['dc'], pillarenv)
if consul:
# Sanity check. ACL Tokens are supported on python-consul 0.4.7 onwards only.
if consul.__version__ < '0.4.7' and params.get('target'):
params.pop('target')
return consul.Consul(**params)
else:
raise CommandExecutionError(
'(unable to import consul, '
'module most likely not installed. Download python-consul '
'module and be sure to import consul)'
)
|
saltstack/salt
|
salt/beacons/btmp.py
|
_gather_group_members
|
python
|
def _gather_group_members(group, groups, users):
'''
Gather group members
'''
_group = __salt__['group.info'](group)
if not _group:
log.warning('Group %s does not exist, ignoring.', group)
return
for member in _group['members']:
if member not in users:
users[member] = groups[group]
|
Gather group members
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/beacons/btmp.py#L168-L180
| null |
# -*- coding: utf-8 -*-
'''
Beacon to fire events at failed login of users
.. versionadded:: 2015.5.0
Example Configuration
=====================
.. code-block:: yaml
# Fire events on all failed logins
beacons:
btmp: []
# Matching on user name, using a default time range
beacons:
btmp:
- users:
gareth:
- defaults:
time_range:
start: '8am'
end: '4pm'
# Matching on user name, overriding the default time range
beacons:
btmp:
- users:
gareth:
time_range:
start: '8am'
end: '4pm'
- defaults:
time_range:
start: '8am'
end: '4pm'
# Matching on group name, overriding the default time range
beacons:
btmp:
- groups:
users:
time_range:
start: '8am'
end: '4pm'
- defaults:
time_range:
start: '8am'
end: '4pm'
Use Case: Posting Failed Login Events to Slack
==============================================
This can be done using the following reactor SLS:
.. code-block:: jinja
report-wtmp:
runner.salt.cmd:
- args:
- fun: slack.post_message
- channel: mychannel # Slack channel
- from_name: someuser # Slack user
- message: "Failed login from `{{ data.get('user', '') or 'unknown user' }}` on `{{ data['id'] }}`"
Match the event like so in the master config file:
.. code-block:: yaml
reactor:
- 'salt/beacon/*/btmp/':
- salt://reactor/btmp.sls
.. note::
This approach uses the :py:mod:`slack execution module
<salt.modules.slack_notify>` directly on the master, and therefore requires
that the master has a slack API key in its configuration:
.. code-block:: yaml
slack:
api_key: xoxb-XXXXXXXXXXXX-XXXXXXXXXXXX-XXXXXXXXXXXXXXXXXXXXXXXX
See the :py:mod:`slack execution module <salt.modules.slack_notify>`
documentation for more information. While you can use an individual user's
API key to post to Slack, a bot user is likely better suited for this. The
:py:mod:`slack engine <salt.engines.slack>` documentation has information
on how to set up a bot user.
'''
# Import python libs
from __future__ import absolute_import, unicode_literals
import datetime
import logging
import os
import struct
# Import Salt Libs
import salt.utils.stringutils
import salt.utils.files
# Import 3rd-party libs
import salt.ext.six
# pylint: disable=import-error
from salt.ext.six.moves import map
# pylint: enable=import-error
__virtualname__ = 'btmp'
BTMP = '/var/log/btmp'
FMT = b'hi32s4s32s256shhiii4i20x'
FIELDS = [
'type',
'PID',
'line',
'inittab',
'user',
'hostname',
'exit_status',
'session',
'time',
'addr'
]
SIZE = struct.calcsize(FMT)
LOC_KEY = 'btmp.loc'
log = logging.getLogger(__name__)
# pylint: disable=import-error
try:
import dateutil.parser as dateutil_parser
_TIME_SUPPORTED = True
except ImportError:
_TIME_SUPPORTED = False
def __virtual__():
if os.path.isfile(BTMP):
return __virtualname__
return False
def _validate_time_range(trange, status, msg):
'''
Check time range
'''
# If trange is empty, just return the current status & msg
if not trange:
return status, msg
if not isinstance(trange, dict):
status = False
msg = ('The time_range parameter for '
'btmp beacon must '
'be a dictionary.')
if not all(k in trange for k in ('start', 'end')):
status = False
msg = ('The time_range parameter for '
'btmp beacon must contain '
'start & end options.')
return status, msg
def _check_time_range(time_range, now):
'''
Check time range
'''
if _TIME_SUPPORTED:
_start = dateutil_parser.parse(time_range['start'])
_end = dateutil_parser.parse(time_range['end'])
return bool(_start <= now <= _end)
else:
log.error('Dateutil is required.')
return False
def _get_loc():
'''
return the active file location
'''
if LOC_KEY in __context__:
return __context__[LOC_KEY]
def validate(config):
'''
Validate the beacon configuration
'''
vstatus = True
vmsg = 'Valid beacon configuration'
# Configuration for load beacon should be a list of dicts
if not isinstance(config, list):
vstatus = False
vmsg = ('Configuration for btmp beacon must '
'be a list.')
else:
_config = {}
list(map(_config.update, config))
if 'users' in _config:
if not isinstance(_config['users'], dict):
vstatus = False
vmsg = ('User configuration for btmp beacon must '
'be a dictionary.')
else:
for user in _config['users']:
_time_range = _config['users'][user].get('time_range', {})
vstatus, vmsg = _validate_time_range(_time_range,
vstatus,
vmsg)
if not vstatus:
return vstatus, vmsg
if 'groups' in _config:
if not isinstance(_config['groups'], dict):
vstatus = False
vmsg = ('Group configuration for btmp beacon must '
'be a dictionary.')
else:
for group in _config['groups']:
_time_range = _config['groups'][group].get('time_range', {})
vstatus, vmsg = _validate_time_range(_time_range,
vstatus,
vmsg)
if not vstatus:
return vstatus, vmsg
if 'defaults' in _config:
if not isinstance(_config['defaults'], dict):
vstatus = False
vmsg = ('Defaults configuration for btmp beacon must '
'be a dictionary.')
else:
_time_range = _config['defaults'].get('time_range', {})
vstatus, vmsg = _validate_time_range(_time_range,
vstatus,
vmsg)
if not vstatus:
return vstatus, vmsg
return vstatus, vmsg
def beacon(config):
'''
Read the last btmp file and return information on the failed logins
'''
ret = []
users = {}
groups = {}
defaults = None
for config_item in config:
if 'users' in config_item:
users = config_item['users']
if 'groups' in config_item:
groups = config_item['groups']
if 'defaults' in config_item:
defaults = config_item['defaults']
with salt.utils.files.fopen(BTMP, 'rb') as fp_:
loc = __context__.get(LOC_KEY, 0)
if loc == 0:
fp_.seek(0, 2)
__context__[LOC_KEY] = fp_.tell()
return ret
else:
fp_.seek(loc)
while True:
now = datetime.datetime.now()
raw = fp_.read(SIZE)
if len(raw) != SIZE:
return ret
__context__[LOC_KEY] = fp_.tell()
pack = struct.unpack(FMT, raw)
event = {}
for ind, field in enumerate(FIELDS):
event[field] = pack[ind]
if isinstance(event[field], salt.ext.six.string_types):
if isinstance(event[field], bytes):
event[field] = salt.utils.stringutils.to_unicode(event[field])
event[field] = event[field].strip('\x00')
for group in groups:
_gather_group_members(group, groups, users)
if users:
if event['user'] in users:
_user = users[event['user']]
if isinstance(_user, dict) and 'time_range' in _user:
if _check_time_range(_user['time_range'], now):
ret.append(event)
else:
if defaults and 'time_range' in defaults:
if _check_time_range(defaults['time_range'],
now):
ret.append(event)
else:
ret.append(event)
else:
if defaults and 'time_range' in defaults:
if _check_time_range(defaults['time_range'], now):
ret.append(event)
else:
ret.append(event)
return ret
|
saltstack/salt
|
salt/beacons/btmp.py
|
_check_time_range
|
python
|
def _check_time_range(time_range, now):
'''
Check time range
'''
if _TIME_SUPPORTED:
_start = dateutil_parser.parse(time_range['start'])
_end = dateutil_parser.parse(time_range['end'])
return bool(_start <= now <= _end)
else:
log.error('Dateutil is required.')
return False
|
Check time range
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/beacons/btmp.py#L183-L194
| null |
# -*- coding: utf-8 -*-
'''
Beacon to fire events at failed login of users
.. versionadded:: 2015.5.0
Example Configuration
=====================
.. code-block:: yaml
# Fire events on all failed logins
beacons:
btmp: []
# Matching on user name, using a default time range
beacons:
btmp:
- users:
gareth:
- defaults:
time_range:
start: '8am'
end: '4pm'
# Matching on user name, overriding the default time range
beacons:
btmp:
- users:
gareth:
time_range:
start: '8am'
end: '4pm'
- defaults:
time_range:
start: '8am'
end: '4pm'
# Matching on group name, overriding the default time range
beacons:
btmp:
- groups:
users:
time_range:
start: '8am'
end: '4pm'
- defaults:
time_range:
start: '8am'
end: '4pm'
Use Case: Posting Failed Login Events to Slack
==============================================
This can be done using the following reactor SLS:
.. code-block:: jinja
report-wtmp:
runner.salt.cmd:
- args:
- fun: slack.post_message
- channel: mychannel # Slack channel
- from_name: someuser # Slack user
- message: "Failed login from `{{ data.get('user', '') or 'unknown user' }}` on `{{ data['id'] }}`"
Match the event like so in the master config file:
.. code-block:: yaml
reactor:
- 'salt/beacon/*/btmp/':
- salt://reactor/btmp.sls
.. note::
This approach uses the :py:mod:`slack execution module
<salt.modules.slack_notify>` directly on the master, and therefore requires
that the master has a slack API key in its configuration:
.. code-block:: yaml
slack:
api_key: xoxb-XXXXXXXXXXXX-XXXXXXXXXXXX-XXXXXXXXXXXXXXXXXXXXXXXX
See the :py:mod:`slack execution module <salt.modules.slack_notify>`
documentation for more information. While you can use an individual user's
API key to post to Slack, a bot user is likely better suited for this. The
:py:mod:`slack engine <salt.engines.slack>` documentation has information
on how to set up a bot user.
'''
# Import python libs
from __future__ import absolute_import, unicode_literals
import datetime
import logging
import os
import struct
# Import Salt Libs
import salt.utils.stringutils
import salt.utils.files
# Import 3rd-party libs
import salt.ext.six
# pylint: disable=import-error
from salt.ext.six.moves import map
# pylint: enable=import-error
__virtualname__ = 'btmp'
BTMP = '/var/log/btmp'
FMT = b'hi32s4s32s256shhiii4i20x'
FIELDS = [
'type',
'PID',
'line',
'inittab',
'user',
'hostname',
'exit_status',
'session',
'time',
'addr'
]
SIZE = struct.calcsize(FMT)
LOC_KEY = 'btmp.loc'
log = logging.getLogger(__name__)
# pylint: disable=import-error
try:
import dateutil.parser as dateutil_parser
_TIME_SUPPORTED = True
except ImportError:
_TIME_SUPPORTED = False
def __virtual__():
if os.path.isfile(BTMP):
return __virtualname__
return False
def _validate_time_range(trange, status, msg):
'''
Check time range
'''
# If trange is empty, just return the current status & msg
if not trange:
return status, msg
if not isinstance(trange, dict):
status = False
msg = ('The time_range parameter for '
'btmp beacon must '
'be a dictionary.')
if not all(k in trange for k in ('start', 'end')):
status = False
msg = ('The time_range parameter for '
'btmp beacon must contain '
'start & end options.')
return status, msg
def _gather_group_members(group, groups, users):
'''
Gather group members
'''
_group = __salt__['group.info'](group)
if not _group:
log.warning('Group %s does not exist, ignoring.', group)
return
for member in _group['members']:
if member not in users:
users[member] = groups[group]
def _get_loc():
'''
return the active file location
'''
if LOC_KEY in __context__:
return __context__[LOC_KEY]
def validate(config):
'''
Validate the beacon configuration
'''
vstatus = True
vmsg = 'Valid beacon configuration'
# Configuration for load beacon should be a list of dicts
if not isinstance(config, list):
vstatus = False
vmsg = ('Configuration for btmp beacon must '
'be a list.')
else:
_config = {}
list(map(_config.update, config))
if 'users' in _config:
if not isinstance(_config['users'], dict):
vstatus = False
vmsg = ('User configuration for btmp beacon must '
'be a dictionary.')
else:
for user in _config['users']:
_time_range = _config['users'][user].get('time_range', {})
vstatus, vmsg = _validate_time_range(_time_range,
vstatus,
vmsg)
if not vstatus:
return vstatus, vmsg
if 'groups' in _config:
if not isinstance(_config['groups'], dict):
vstatus = False
vmsg = ('Group configuration for btmp beacon must '
'be a dictionary.')
else:
for group in _config['groups']:
_time_range = _config['groups'][group].get('time_range', {})
vstatus, vmsg = _validate_time_range(_time_range,
vstatus,
vmsg)
if not vstatus:
return vstatus, vmsg
if 'defaults' in _config:
if not isinstance(_config['defaults'], dict):
vstatus = False
vmsg = ('Defaults configuration for btmp beacon must '
'be a dictionary.')
else:
_time_range = _config['defaults'].get('time_range', {})
vstatus, vmsg = _validate_time_range(_time_range,
vstatus,
vmsg)
if not vstatus:
return vstatus, vmsg
return vstatus, vmsg
def beacon(config):
'''
Read the last btmp file and return information on the failed logins
'''
ret = []
users = {}
groups = {}
defaults = None
for config_item in config:
if 'users' in config_item:
users = config_item['users']
if 'groups' in config_item:
groups = config_item['groups']
if 'defaults' in config_item:
defaults = config_item['defaults']
with salt.utils.files.fopen(BTMP, 'rb') as fp_:
loc = __context__.get(LOC_KEY, 0)
if loc == 0:
fp_.seek(0, 2)
__context__[LOC_KEY] = fp_.tell()
return ret
else:
fp_.seek(loc)
while True:
now = datetime.datetime.now()
raw = fp_.read(SIZE)
if len(raw) != SIZE:
return ret
__context__[LOC_KEY] = fp_.tell()
pack = struct.unpack(FMT, raw)
event = {}
for ind, field in enumerate(FIELDS):
event[field] = pack[ind]
if isinstance(event[field], salt.ext.six.string_types):
if isinstance(event[field], bytes):
event[field] = salt.utils.stringutils.to_unicode(event[field])
event[field] = event[field].strip('\x00')
for group in groups:
_gather_group_members(group, groups, users)
if users:
if event['user'] in users:
_user = users[event['user']]
if isinstance(_user, dict) and 'time_range' in _user:
if _check_time_range(_user['time_range'], now):
ret.append(event)
else:
if defaults and 'time_range' in defaults:
if _check_time_range(defaults['time_range'],
now):
ret.append(event)
else:
ret.append(event)
else:
if defaults and 'time_range' in defaults:
if _check_time_range(defaults['time_range'], now):
ret.append(event)
else:
ret.append(event)
return ret
|
saltstack/salt
|
salt/beacons/btmp.py
|
beacon
|
python
|
def beacon(config):
'''
Read the last btmp file and return information on the failed logins
'''
ret = []
users = {}
groups = {}
defaults = None
for config_item in config:
if 'users' in config_item:
users = config_item['users']
if 'groups' in config_item:
groups = config_item['groups']
if 'defaults' in config_item:
defaults = config_item['defaults']
with salt.utils.files.fopen(BTMP, 'rb') as fp_:
loc = __context__.get(LOC_KEY, 0)
if loc == 0:
fp_.seek(0, 2)
__context__[LOC_KEY] = fp_.tell()
return ret
else:
fp_.seek(loc)
while True:
now = datetime.datetime.now()
raw = fp_.read(SIZE)
if len(raw) != SIZE:
return ret
__context__[LOC_KEY] = fp_.tell()
pack = struct.unpack(FMT, raw)
event = {}
for ind, field in enumerate(FIELDS):
event[field] = pack[ind]
if isinstance(event[field], salt.ext.six.string_types):
if isinstance(event[field], bytes):
event[field] = salt.utils.stringutils.to_unicode(event[field])
event[field] = event[field].strip('\x00')
for group in groups:
_gather_group_members(group, groups, users)
if users:
if event['user'] in users:
_user = users[event['user']]
if isinstance(_user, dict) and 'time_range' in _user:
if _check_time_range(_user['time_range'], now):
ret.append(event)
else:
if defaults and 'time_range' in defaults:
if _check_time_range(defaults['time_range'],
now):
ret.append(event)
else:
ret.append(event)
else:
if defaults and 'time_range' in defaults:
if _check_time_range(defaults['time_range'], now):
ret.append(event)
else:
ret.append(event)
return ret
|
Read the last btmp file and return information on the failed logins
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/beacons/btmp.py#L266-L331
|
[
"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 _gather_group_members(group, groups, users):\n '''\n Gather group members\n '''\n _group = __salt__['group.info'](group)\n\n if not _group:\n log.warning('Group %s does not exist, ignoring.', group)\n return\n\n for member in _group['members']:\n if member not in users:\n users[member] = groups[group]\n",
"def _check_time_range(time_range, now):\n '''\n Check time range\n '''\n if _TIME_SUPPORTED:\n _start = dateutil_parser.parse(time_range['start'])\n _end = dateutil_parser.parse(time_range['end'])\n\n return bool(_start <= now <= _end)\n else:\n log.error('Dateutil is required.')\n return False\n"
] |
# -*- coding: utf-8 -*-
'''
Beacon to fire events at failed login of users
.. versionadded:: 2015.5.0
Example Configuration
=====================
.. code-block:: yaml
# Fire events on all failed logins
beacons:
btmp: []
# Matching on user name, using a default time range
beacons:
btmp:
- users:
gareth:
- defaults:
time_range:
start: '8am'
end: '4pm'
# Matching on user name, overriding the default time range
beacons:
btmp:
- users:
gareth:
time_range:
start: '8am'
end: '4pm'
- defaults:
time_range:
start: '8am'
end: '4pm'
# Matching on group name, overriding the default time range
beacons:
btmp:
- groups:
users:
time_range:
start: '8am'
end: '4pm'
- defaults:
time_range:
start: '8am'
end: '4pm'
Use Case: Posting Failed Login Events to Slack
==============================================
This can be done using the following reactor SLS:
.. code-block:: jinja
report-wtmp:
runner.salt.cmd:
- args:
- fun: slack.post_message
- channel: mychannel # Slack channel
- from_name: someuser # Slack user
- message: "Failed login from `{{ data.get('user', '') or 'unknown user' }}` on `{{ data['id'] }}`"
Match the event like so in the master config file:
.. code-block:: yaml
reactor:
- 'salt/beacon/*/btmp/':
- salt://reactor/btmp.sls
.. note::
This approach uses the :py:mod:`slack execution module
<salt.modules.slack_notify>` directly on the master, and therefore requires
that the master has a slack API key in its configuration:
.. code-block:: yaml
slack:
api_key: xoxb-XXXXXXXXXXXX-XXXXXXXXXXXX-XXXXXXXXXXXXXXXXXXXXXXXX
See the :py:mod:`slack execution module <salt.modules.slack_notify>`
documentation for more information. While you can use an individual user's
API key to post to Slack, a bot user is likely better suited for this. The
:py:mod:`slack engine <salt.engines.slack>` documentation has information
on how to set up a bot user.
'''
# Import python libs
from __future__ import absolute_import, unicode_literals
import datetime
import logging
import os
import struct
# Import Salt Libs
import salt.utils.stringutils
import salt.utils.files
# Import 3rd-party libs
import salt.ext.six
# pylint: disable=import-error
from salt.ext.six.moves import map
# pylint: enable=import-error
__virtualname__ = 'btmp'
BTMP = '/var/log/btmp'
FMT = b'hi32s4s32s256shhiii4i20x'
FIELDS = [
'type',
'PID',
'line',
'inittab',
'user',
'hostname',
'exit_status',
'session',
'time',
'addr'
]
SIZE = struct.calcsize(FMT)
LOC_KEY = 'btmp.loc'
log = logging.getLogger(__name__)
# pylint: disable=import-error
try:
import dateutil.parser as dateutil_parser
_TIME_SUPPORTED = True
except ImportError:
_TIME_SUPPORTED = False
def __virtual__():
if os.path.isfile(BTMP):
return __virtualname__
return False
def _validate_time_range(trange, status, msg):
'''
Check time range
'''
# If trange is empty, just return the current status & msg
if not trange:
return status, msg
if not isinstance(trange, dict):
status = False
msg = ('The time_range parameter for '
'btmp beacon must '
'be a dictionary.')
if not all(k in trange for k in ('start', 'end')):
status = False
msg = ('The time_range parameter for '
'btmp beacon must contain '
'start & end options.')
return status, msg
def _gather_group_members(group, groups, users):
'''
Gather group members
'''
_group = __salt__['group.info'](group)
if not _group:
log.warning('Group %s does not exist, ignoring.', group)
return
for member in _group['members']:
if member not in users:
users[member] = groups[group]
def _check_time_range(time_range, now):
'''
Check time range
'''
if _TIME_SUPPORTED:
_start = dateutil_parser.parse(time_range['start'])
_end = dateutil_parser.parse(time_range['end'])
return bool(_start <= now <= _end)
else:
log.error('Dateutil is required.')
return False
def _get_loc():
'''
return the active file location
'''
if LOC_KEY in __context__:
return __context__[LOC_KEY]
def validate(config):
'''
Validate the beacon configuration
'''
vstatus = True
vmsg = 'Valid beacon configuration'
# Configuration for load beacon should be a list of dicts
if not isinstance(config, list):
vstatus = False
vmsg = ('Configuration for btmp beacon must '
'be a list.')
else:
_config = {}
list(map(_config.update, config))
if 'users' in _config:
if not isinstance(_config['users'], dict):
vstatus = False
vmsg = ('User configuration for btmp beacon must '
'be a dictionary.')
else:
for user in _config['users']:
_time_range = _config['users'][user].get('time_range', {})
vstatus, vmsg = _validate_time_range(_time_range,
vstatus,
vmsg)
if not vstatus:
return vstatus, vmsg
if 'groups' in _config:
if not isinstance(_config['groups'], dict):
vstatus = False
vmsg = ('Group configuration for btmp beacon must '
'be a dictionary.')
else:
for group in _config['groups']:
_time_range = _config['groups'][group].get('time_range', {})
vstatus, vmsg = _validate_time_range(_time_range,
vstatus,
vmsg)
if not vstatus:
return vstatus, vmsg
if 'defaults' in _config:
if not isinstance(_config['defaults'], dict):
vstatus = False
vmsg = ('Defaults configuration for btmp beacon must '
'be a dictionary.')
else:
_time_range = _config['defaults'].get('time_range', {})
vstatus, vmsg = _validate_time_range(_time_range,
vstatus,
vmsg)
if not vstatus:
return vstatus, vmsg
return vstatus, vmsg
|
saltstack/salt
|
salt/returners/slack_webhook_return.py
|
_sprinkle
|
python
|
def _sprinkle(config_str):
'''
Sprinkle with grains of salt, that is
convert 'test {id} test {host} ' types of strings
:param config_str: The string to be sprinkled
:return: The string sprinkled
'''
parts = [x for sub in config_str.split('{') for x in sub.split('}')]
for i in range(1, len(parts), 2):
parts[i] = six.text_type(__grains__.get(parts[i], ''))
return ''.join(parts)
|
Sprinkle with grains of salt, that is
convert 'test {id} test {host} ' types of strings
:param config_str: The string to be sprinkled
:return: The string sprinkled
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/slack_webhook_return.py#L121-L131
| null |
# -*- coding: utf-8 -*-
'''
Return salt data via Slack using Incoming Webhooks
:codeauthor: :email:`Carlos D. Álvaro <github@cdalvaro.io>`
The following fields can be set in the minion conf file:
.. code-block:: yaml
slack_webhook.webhook (required, the webhook id. Just the part after: 'https://hooks.slack.com/services/')
slack_webhook.success_title (optional, short title for succeeded states. By default: '{id} | Succeeded')
slack_webhook.failure_title (optional, short title for failed states. By default: '{id} | Failed')
slack_webhook.author_icon (optional, a URL that with a small 16x16px image. Must be of type: GIF, JPEG, PNG, and BMP)
slack_webhook.show_tasks (optional, show identifiers for changed and failed tasks. By default: False)
Alternative configuration values can be used by prefacing the configuration.
Any values not found in the alternative configuration will be pulled from
the default location:
.. code-block:: yaml
slack_webhook.webhook
slack_webhook.success_title
slack_webhook.failure_title
slack_webhook.author_icon
slack_webhook.show_tasks
Slack settings may also be configured as:
.. code-block:: yaml
slack_webhook:
webhook: T00000000/B00000000/XXXXXXXXXXXXXXXXXXXXXXXX
success_title: [{id}] | Success
failure_title: [{id}] | Failure
author_icon: https://platform.slack-edge.com/img/default_application_icon.png
show_tasks: true
alternative.slack_webhook:
webhook: T00000000/C00000000/YYYYYYYYYYYYYYYYYYYYYYYY
show_tasks: false
To use the Slack returner, append '--return slack_webhook' to the salt command.
.. code-block:: bash
salt '*' test.ping --return slack_webhook
To use the alternative configuration, append '--return_config alternative' to the salt command.
.. code-block:: bash
salt '*' test.ping --return slack_webhook --return_config alternative
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import Python libs
import logging
import json
# pylint: disable=import-error,no-name-in-module,redefined-builtin
import salt.ext.six.moves.http_client
from salt.ext.six.moves.urllib.parse import urlencode as _urlencode
from salt.ext import six
from salt.ext.six.moves import map
from salt.ext.six.moves import range
# pylint: enable=import-error,no-name-in-module,redefined-builtin
# Import Salt Libs
import salt.returners
import salt.utils.http
import salt.utils.yaml
log = logging.getLogger(__name__)
__virtualname__ = 'slack_webhook'
def _get_options(ret=None):
'''
Get the slack_webhook options from salt.
:param ret: Salt return dictionary
:return: A dictionary with options
'''
defaults = {
'success_title': '{id} | Succeeded',
'failure_title': '{id} | Failed',
'author_icon': '',
'show_tasks': False
}
attrs = {
'webhook': 'webhook',
'success_title': 'success_title',
'failure_title': 'failure_title',
'author_icon': 'author_icon',
'show_tasks': 'show_tasks'
}
_options = salt.returners.get_returner_options(__virtualname__,
ret,
attrs,
__salt__=__salt__,
__opts__=__opts__,
defaults=defaults)
return _options
def __virtual__():
'''
Return virtual name of the module.
:return: The virtual name of the module.
'''
return __virtualname__
def _format_task(task):
'''
Return a dictionary with the task ready for slack fileds
:param task: The name of the task
:return: A dictionary ready to be inserted in Slack fields array
'''
return {'value': task, 'short': False}
def _generate_payload(author_icon, title, report):
'''
Prepare the payload for Slack
:param author_icon: The url for the thumbnail to be displayed
:param title: The title of the message
:param report: A dictionary with the report of the Salt function
:return: The payload ready for Slack
'''
title = _sprinkle(title)
unchanged = {
'color': 'good',
'title': 'Unchanged: {unchanged}'.format(unchanged=report['unchanged'].get('counter', None))
}
changed = {
'color': 'warning',
'title': 'Changed: {changed}'.format(changed=report['changed'].get('counter', None))
}
if report['changed'].get('tasks'):
changed['fields'] = list(
map(_format_task, report['changed'].get('tasks')))
failed = {
'color': 'danger',
'title': 'Failed: {failed}'.format(failed=report['failed'].get('counter', None))
}
if report['failed'].get('tasks'):
failed['fields'] = list(
map(_format_task, report['failed'].get('tasks')))
text = 'Function: {function}\n'.format(function=report.get('function'))
if report.get('arguments'):
text += 'Function Args: {arguments}\n'.format(
arguments=str(list(map(str, report.get('arguments')))))
text += 'JID: {jid}\n'.format(jid=report.get('jid'))
text += 'Total: {total}\n'.format(total=report.get('total'))
text += 'Duration: {duration:.2f} secs'.format(
duration=float(report.get('duration')))
payload = {
'attachments': [
{
'fallback': title,
'color': "#272727",
'author_name': _sprinkle('{id}'),
'author_link': _sprinkle('{localhost}'),
'author_icon': author_icon,
'title': 'Success: {success}'.format(success=str(report.get('success'))),
'text': text
},
unchanged,
changed,
failed
]
}
return payload
def _generate_report(ret, show_tasks):
'''
Generate a report of the Salt function
:param ret: The Salt return
:param show_tasks: Flag to show the name of the changed and failed states
:return: The report
'''
returns = ret.get('return')
sorted_data = sorted(
returns.items(),
key=lambda s: s[1].get('__run_num__', 0)
)
total = 0
failed = 0
changed = 0
duration = 0.0
changed_tasks = []
failed_tasks = []
# gather stats
for state, data in sorted_data:
# state: module, stateid, name, function
_, stateid, _, _ = state.split('_|-')
task = '{filename}.sls | {taskname}'.format(
filename=str(data.get('__sls__')), taskname=stateid)
if not data.get('result', True):
failed += 1
failed_tasks.append(task)
if data.get('changes', {}):
changed += 1
changed_tasks.append(task)
total += 1
try:
duration += float(data.get('duration', 0.0))
except ValueError:
pass
unchanged = total - failed - changed
log.debug('%s total: %s', __virtualname__, total)
log.debug('%s failed: %s', __virtualname__, failed)
log.debug('%s unchanged: %s', __virtualname__, unchanged)
log.debug('%s changed: %s', __virtualname__, changed)
report = {
'id': ret.get('id'),
'success': True if failed == 0 else False,
'total': total,
'function': ret.get('fun'),
'arguments': ret.get('fun_args', []),
'jid': ret.get('jid'),
'duration': duration / 1000,
'unchanged': {
'counter': unchanged
},
'changed': {
'counter': changed,
'tasks': changed_tasks if show_tasks else []
},
'failed': {
'counter': failed,
'tasks': failed_tasks if show_tasks else []
}
}
return report
def _post_message(webhook, author_icon, title, report):
'''
Send a message to a Slack room through a webhook
:param webhook: The url of the incoming webhook
:param author_icon: The thumbnail image to be displayed on the right side of the message
:param title: The title of the message
:param report: The report of the function state
:return: Boolean if message was sent successfully
'''
payload = _generate_payload(author_icon, title, report)
data = _urlencode({
'payload': json.dumps(payload, ensure_ascii=False)
})
webhook_url = 'https://hooks.slack.com/services/{webhook}'.format(webhook=webhook)
query_result = salt.utils.http.query(webhook_url, 'POST', data=data)
if query_result['body'] == 'ok' or query_result['status'] <= 201:
return True
else:
log.error('Slack incoming webhook message post result: %s', query_result)
return {
'res': False,
'message': query_result.get('body', query_result['status'])
}
def returner(ret):
'''
Send a slack message with the data through a webhook
:param ret: The Salt return
:return: The result of the post
'''
_options = _get_options(ret)
webhook = _options.get('webhook', None)
show_tasks = _options.get('show_tasks')
author_icon = _options.get('author_icon')
if not webhook or webhook is '':
log.error('%s.webhook not defined in salt config', __virtualname__)
return
report = _generate_report(ret, show_tasks)
if report.get('success'):
title = _options.get('success_title')
else:
title = _options.get('failure_title')
slack = _post_message(webhook, author_icon, title, report)
return slack
|
saltstack/salt
|
salt/returners/slack_webhook_return.py
|
_generate_payload
|
python
|
def _generate_payload(author_icon, title, report):
'''
Prepare the payload for Slack
:param author_icon: The url for the thumbnail to be displayed
:param title: The title of the message
:param report: A dictionary with the report of the Salt function
:return: The payload ready for Slack
'''
title = _sprinkle(title)
unchanged = {
'color': 'good',
'title': 'Unchanged: {unchanged}'.format(unchanged=report['unchanged'].get('counter', None))
}
changed = {
'color': 'warning',
'title': 'Changed: {changed}'.format(changed=report['changed'].get('counter', None))
}
if report['changed'].get('tasks'):
changed['fields'] = list(
map(_format_task, report['changed'].get('tasks')))
failed = {
'color': 'danger',
'title': 'Failed: {failed}'.format(failed=report['failed'].get('counter', None))
}
if report['failed'].get('tasks'):
failed['fields'] = list(
map(_format_task, report['failed'].get('tasks')))
text = 'Function: {function}\n'.format(function=report.get('function'))
if report.get('arguments'):
text += 'Function Args: {arguments}\n'.format(
arguments=str(list(map(str, report.get('arguments')))))
text += 'JID: {jid}\n'.format(jid=report.get('jid'))
text += 'Total: {total}\n'.format(total=report.get('total'))
text += 'Duration: {duration:.2f} secs'.format(
duration=float(report.get('duration')))
payload = {
'attachments': [
{
'fallback': title,
'color': "#272727",
'author_name': _sprinkle('{id}'),
'author_link': _sprinkle('{localhost}'),
'author_icon': author_icon,
'title': 'Success: {success}'.format(success=str(report.get('success'))),
'text': text
},
unchanged,
changed,
failed
]
}
return payload
|
Prepare the payload for Slack
:param author_icon: The url for the thumbnail to be displayed
:param title: The title of the message
:param report: A dictionary with the report of the Salt function
:return: The payload ready for Slack
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/slack_webhook_return.py#L144-L205
|
[
"def _sprinkle(config_str):\n '''\n Sprinkle with grains of salt, that is\n convert 'test {id} test {host} ' types of strings\n :param config_str: The string to be sprinkled\n :return: The string sprinkled\n '''\n parts = [x for sub in config_str.split('{') for x in sub.split('}')]\n for i in range(1, len(parts), 2):\n parts[i] = six.text_type(__grains__.get(parts[i], ''))\n return ''.join(parts)\n"
] |
# -*- coding: utf-8 -*-
'''
Return salt data via Slack using Incoming Webhooks
:codeauthor: :email:`Carlos D. Álvaro <github@cdalvaro.io>`
The following fields can be set in the minion conf file:
.. code-block:: yaml
slack_webhook.webhook (required, the webhook id. Just the part after: 'https://hooks.slack.com/services/')
slack_webhook.success_title (optional, short title for succeeded states. By default: '{id} | Succeeded')
slack_webhook.failure_title (optional, short title for failed states. By default: '{id} | Failed')
slack_webhook.author_icon (optional, a URL that with a small 16x16px image. Must be of type: GIF, JPEG, PNG, and BMP)
slack_webhook.show_tasks (optional, show identifiers for changed and failed tasks. By default: False)
Alternative configuration values can be used by prefacing the configuration.
Any values not found in the alternative configuration will be pulled from
the default location:
.. code-block:: yaml
slack_webhook.webhook
slack_webhook.success_title
slack_webhook.failure_title
slack_webhook.author_icon
slack_webhook.show_tasks
Slack settings may also be configured as:
.. code-block:: yaml
slack_webhook:
webhook: T00000000/B00000000/XXXXXXXXXXXXXXXXXXXXXXXX
success_title: [{id}] | Success
failure_title: [{id}] | Failure
author_icon: https://platform.slack-edge.com/img/default_application_icon.png
show_tasks: true
alternative.slack_webhook:
webhook: T00000000/C00000000/YYYYYYYYYYYYYYYYYYYYYYYY
show_tasks: false
To use the Slack returner, append '--return slack_webhook' to the salt command.
.. code-block:: bash
salt '*' test.ping --return slack_webhook
To use the alternative configuration, append '--return_config alternative' to the salt command.
.. code-block:: bash
salt '*' test.ping --return slack_webhook --return_config alternative
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import Python libs
import logging
import json
# pylint: disable=import-error,no-name-in-module,redefined-builtin
import salt.ext.six.moves.http_client
from salt.ext.six.moves.urllib.parse import urlencode as _urlencode
from salt.ext import six
from salt.ext.six.moves import map
from salt.ext.six.moves import range
# pylint: enable=import-error,no-name-in-module,redefined-builtin
# Import Salt Libs
import salt.returners
import salt.utils.http
import salt.utils.yaml
log = logging.getLogger(__name__)
__virtualname__ = 'slack_webhook'
def _get_options(ret=None):
'''
Get the slack_webhook options from salt.
:param ret: Salt return dictionary
:return: A dictionary with options
'''
defaults = {
'success_title': '{id} | Succeeded',
'failure_title': '{id} | Failed',
'author_icon': '',
'show_tasks': False
}
attrs = {
'webhook': 'webhook',
'success_title': 'success_title',
'failure_title': 'failure_title',
'author_icon': 'author_icon',
'show_tasks': 'show_tasks'
}
_options = salt.returners.get_returner_options(__virtualname__,
ret,
attrs,
__salt__=__salt__,
__opts__=__opts__,
defaults=defaults)
return _options
def __virtual__():
'''
Return virtual name of the module.
:return: The virtual name of the module.
'''
return __virtualname__
def _sprinkle(config_str):
'''
Sprinkle with grains of salt, that is
convert 'test {id} test {host} ' types of strings
:param config_str: The string to be sprinkled
:return: The string sprinkled
'''
parts = [x for sub in config_str.split('{') for x in sub.split('}')]
for i in range(1, len(parts), 2):
parts[i] = six.text_type(__grains__.get(parts[i], ''))
return ''.join(parts)
def _format_task(task):
'''
Return a dictionary with the task ready for slack fileds
:param task: The name of the task
:return: A dictionary ready to be inserted in Slack fields array
'''
return {'value': task, 'short': False}
def _generate_report(ret, show_tasks):
'''
Generate a report of the Salt function
:param ret: The Salt return
:param show_tasks: Flag to show the name of the changed and failed states
:return: The report
'''
returns = ret.get('return')
sorted_data = sorted(
returns.items(),
key=lambda s: s[1].get('__run_num__', 0)
)
total = 0
failed = 0
changed = 0
duration = 0.0
changed_tasks = []
failed_tasks = []
# gather stats
for state, data in sorted_data:
# state: module, stateid, name, function
_, stateid, _, _ = state.split('_|-')
task = '{filename}.sls | {taskname}'.format(
filename=str(data.get('__sls__')), taskname=stateid)
if not data.get('result', True):
failed += 1
failed_tasks.append(task)
if data.get('changes', {}):
changed += 1
changed_tasks.append(task)
total += 1
try:
duration += float(data.get('duration', 0.0))
except ValueError:
pass
unchanged = total - failed - changed
log.debug('%s total: %s', __virtualname__, total)
log.debug('%s failed: %s', __virtualname__, failed)
log.debug('%s unchanged: %s', __virtualname__, unchanged)
log.debug('%s changed: %s', __virtualname__, changed)
report = {
'id': ret.get('id'),
'success': True if failed == 0 else False,
'total': total,
'function': ret.get('fun'),
'arguments': ret.get('fun_args', []),
'jid': ret.get('jid'),
'duration': duration / 1000,
'unchanged': {
'counter': unchanged
},
'changed': {
'counter': changed,
'tasks': changed_tasks if show_tasks else []
},
'failed': {
'counter': failed,
'tasks': failed_tasks if show_tasks else []
}
}
return report
def _post_message(webhook, author_icon, title, report):
'''
Send a message to a Slack room through a webhook
:param webhook: The url of the incoming webhook
:param author_icon: The thumbnail image to be displayed on the right side of the message
:param title: The title of the message
:param report: The report of the function state
:return: Boolean if message was sent successfully
'''
payload = _generate_payload(author_icon, title, report)
data = _urlencode({
'payload': json.dumps(payload, ensure_ascii=False)
})
webhook_url = 'https://hooks.slack.com/services/{webhook}'.format(webhook=webhook)
query_result = salt.utils.http.query(webhook_url, 'POST', data=data)
if query_result['body'] == 'ok' or query_result['status'] <= 201:
return True
else:
log.error('Slack incoming webhook message post result: %s', query_result)
return {
'res': False,
'message': query_result.get('body', query_result['status'])
}
def returner(ret):
'''
Send a slack message with the data through a webhook
:param ret: The Salt return
:return: The result of the post
'''
_options = _get_options(ret)
webhook = _options.get('webhook', None)
show_tasks = _options.get('show_tasks')
author_icon = _options.get('author_icon')
if not webhook or webhook is '':
log.error('%s.webhook not defined in salt config', __virtualname__)
return
report = _generate_report(ret, show_tasks)
if report.get('success'):
title = _options.get('success_title')
else:
title = _options.get('failure_title')
slack = _post_message(webhook, author_icon, title, report)
return slack
|
saltstack/salt
|
salt/returners/slack_webhook_return.py
|
_generate_report
|
python
|
def _generate_report(ret, show_tasks):
'''
Generate a report of the Salt function
:param ret: The Salt return
:param show_tasks: Flag to show the name of the changed and failed states
:return: The report
'''
returns = ret.get('return')
sorted_data = sorted(
returns.items(),
key=lambda s: s[1].get('__run_num__', 0)
)
total = 0
failed = 0
changed = 0
duration = 0.0
changed_tasks = []
failed_tasks = []
# gather stats
for state, data in sorted_data:
# state: module, stateid, name, function
_, stateid, _, _ = state.split('_|-')
task = '{filename}.sls | {taskname}'.format(
filename=str(data.get('__sls__')), taskname=stateid)
if not data.get('result', True):
failed += 1
failed_tasks.append(task)
if data.get('changes', {}):
changed += 1
changed_tasks.append(task)
total += 1
try:
duration += float(data.get('duration', 0.0))
except ValueError:
pass
unchanged = total - failed - changed
log.debug('%s total: %s', __virtualname__, total)
log.debug('%s failed: %s', __virtualname__, failed)
log.debug('%s unchanged: %s', __virtualname__, unchanged)
log.debug('%s changed: %s', __virtualname__, changed)
report = {
'id': ret.get('id'),
'success': True if failed == 0 else False,
'total': total,
'function': ret.get('fun'),
'arguments': ret.get('fun_args', []),
'jid': ret.get('jid'),
'duration': duration / 1000,
'unchanged': {
'counter': unchanged
},
'changed': {
'counter': changed,
'tasks': changed_tasks if show_tasks else []
},
'failed': {
'counter': failed,
'tasks': failed_tasks if show_tasks else []
}
}
return report
|
Generate a report of the Salt function
:param ret: The Salt return
:param show_tasks: Flag to show the name of the changed and failed states
:return: The report
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/slack_webhook_return.py#L208-L280
| null |
# -*- coding: utf-8 -*-
'''
Return salt data via Slack using Incoming Webhooks
:codeauthor: :email:`Carlos D. Álvaro <github@cdalvaro.io>`
The following fields can be set in the minion conf file:
.. code-block:: yaml
slack_webhook.webhook (required, the webhook id. Just the part after: 'https://hooks.slack.com/services/')
slack_webhook.success_title (optional, short title for succeeded states. By default: '{id} | Succeeded')
slack_webhook.failure_title (optional, short title for failed states. By default: '{id} | Failed')
slack_webhook.author_icon (optional, a URL that with a small 16x16px image. Must be of type: GIF, JPEG, PNG, and BMP)
slack_webhook.show_tasks (optional, show identifiers for changed and failed tasks. By default: False)
Alternative configuration values can be used by prefacing the configuration.
Any values not found in the alternative configuration will be pulled from
the default location:
.. code-block:: yaml
slack_webhook.webhook
slack_webhook.success_title
slack_webhook.failure_title
slack_webhook.author_icon
slack_webhook.show_tasks
Slack settings may also be configured as:
.. code-block:: yaml
slack_webhook:
webhook: T00000000/B00000000/XXXXXXXXXXXXXXXXXXXXXXXX
success_title: [{id}] | Success
failure_title: [{id}] | Failure
author_icon: https://platform.slack-edge.com/img/default_application_icon.png
show_tasks: true
alternative.slack_webhook:
webhook: T00000000/C00000000/YYYYYYYYYYYYYYYYYYYYYYYY
show_tasks: false
To use the Slack returner, append '--return slack_webhook' to the salt command.
.. code-block:: bash
salt '*' test.ping --return slack_webhook
To use the alternative configuration, append '--return_config alternative' to the salt command.
.. code-block:: bash
salt '*' test.ping --return slack_webhook --return_config alternative
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import Python libs
import logging
import json
# pylint: disable=import-error,no-name-in-module,redefined-builtin
import salt.ext.six.moves.http_client
from salt.ext.six.moves.urllib.parse import urlencode as _urlencode
from salt.ext import six
from salt.ext.six.moves import map
from salt.ext.six.moves import range
# pylint: enable=import-error,no-name-in-module,redefined-builtin
# Import Salt Libs
import salt.returners
import salt.utils.http
import salt.utils.yaml
log = logging.getLogger(__name__)
__virtualname__ = 'slack_webhook'
def _get_options(ret=None):
'''
Get the slack_webhook options from salt.
:param ret: Salt return dictionary
:return: A dictionary with options
'''
defaults = {
'success_title': '{id} | Succeeded',
'failure_title': '{id} | Failed',
'author_icon': '',
'show_tasks': False
}
attrs = {
'webhook': 'webhook',
'success_title': 'success_title',
'failure_title': 'failure_title',
'author_icon': 'author_icon',
'show_tasks': 'show_tasks'
}
_options = salt.returners.get_returner_options(__virtualname__,
ret,
attrs,
__salt__=__salt__,
__opts__=__opts__,
defaults=defaults)
return _options
def __virtual__():
'''
Return virtual name of the module.
:return: The virtual name of the module.
'''
return __virtualname__
def _sprinkle(config_str):
'''
Sprinkle with grains of salt, that is
convert 'test {id} test {host} ' types of strings
:param config_str: The string to be sprinkled
:return: The string sprinkled
'''
parts = [x for sub in config_str.split('{') for x in sub.split('}')]
for i in range(1, len(parts), 2):
parts[i] = six.text_type(__grains__.get(parts[i], ''))
return ''.join(parts)
def _format_task(task):
'''
Return a dictionary with the task ready for slack fileds
:param task: The name of the task
:return: A dictionary ready to be inserted in Slack fields array
'''
return {'value': task, 'short': False}
def _generate_payload(author_icon, title, report):
'''
Prepare the payload for Slack
:param author_icon: The url for the thumbnail to be displayed
:param title: The title of the message
:param report: A dictionary with the report of the Salt function
:return: The payload ready for Slack
'''
title = _sprinkle(title)
unchanged = {
'color': 'good',
'title': 'Unchanged: {unchanged}'.format(unchanged=report['unchanged'].get('counter', None))
}
changed = {
'color': 'warning',
'title': 'Changed: {changed}'.format(changed=report['changed'].get('counter', None))
}
if report['changed'].get('tasks'):
changed['fields'] = list(
map(_format_task, report['changed'].get('tasks')))
failed = {
'color': 'danger',
'title': 'Failed: {failed}'.format(failed=report['failed'].get('counter', None))
}
if report['failed'].get('tasks'):
failed['fields'] = list(
map(_format_task, report['failed'].get('tasks')))
text = 'Function: {function}\n'.format(function=report.get('function'))
if report.get('arguments'):
text += 'Function Args: {arguments}\n'.format(
arguments=str(list(map(str, report.get('arguments')))))
text += 'JID: {jid}\n'.format(jid=report.get('jid'))
text += 'Total: {total}\n'.format(total=report.get('total'))
text += 'Duration: {duration:.2f} secs'.format(
duration=float(report.get('duration')))
payload = {
'attachments': [
{
'fallback': title,
'color': "#272727",
'author_name': _sprinkle('{id}'),
'author_link': _sprinkle('{localhost}'),
'author_icon': author_icon,
'title': 'Success: {success}'.format(success=str(report.get('success'))),
'text': text
},
unchanged,
changed,
failed
]
}
return payload
def _post_message(webhook, author_icon, title, report):
'''
Send a message to a Slack room through a webhook
:param webhook: The url of the incoming webhook
:param author_icon: The thumbnail image to be displayed on the right side of the message
:param title: The title of the message
:param report: The report of the function state
:return: Boolean if message was sent successfully
'''
payload = _generate_payload(author_icon, title, report)
data = _urlencode({
'payload': json.dumps(payload, ensure_ascii=False)
})
webhook_url = 'https://hooks.slack.com/services/{webhook}'.format(webhook=webhook)
query_result = salt.utils.http.query(webhook_url, 'POST', data=data)
if query_result['body'] == 'ok' or query_result['status'] <= 201:
return True
else:
log.error('Slack incoming webhook message post result: %s', query_result)
return {
'res': False,
'message': query_result.get('body', query_result['status'])
}
def returner(ret):
'''
Send a slack message with the data through a webhook
:param ret: The Salt return
:return: The result of the post
'''
_options = _get_options(ret)
webhook = _options.get('webhook', None)
show_tasks = _options.get('show_tasks')
author_icon = _options.get('author_icon')
if not webhook or webhook is '':
log.error('%s.webhook not defined in salt config', __virtualname__)
return
report = _generate_report(ret, show_tasks)
if report.get('success'):
title = _options.get('success_title')
else:
title = _options.get('failure_title')
slack = _post_message(webhook, author_icon, title, report)
return slack
|
saltstack/salt
|
salt/returners/slack_webhook_return.py
|
_post_message
|
python
|
def _post_message(webhook, author_icon, title, report):
'''
Send a message to a Slack room through a webhook
:param webhook: The url of the incoming webhook
:param author_icon: The thumbnail image to be displayed on the right side of the message
:param title: The title of the message
:param report: The report of the function state
:return: Boolean if message was sent successfully
'''
payload = _generate_payload(author_icon, title, report)
data = _urlencode({
'payload': json.dumps(payload, ensure_ascii=False)
})
webhook_url = 'https://hooks.slack.com/services/{webhook}'.format(webhook=webhook)
query_result = salt.utils.http.query(webhook_url, 'POST', data=data)
if query_result['body'] == 'ok' or query_result['status'] <= 201:
return True
else:
log.error('Slack incoming webhook message post result: %s', query_result)
return {
'res': False,
'message': query_result.get('body', query_result['status'])
}
|
Send a message to a Slack room through a webhook
:param webhook: The url of the incoming webhook
:param author_icon: The thumbnail image to be displayed on the right side of the message
:param title: The title of the message
:param report: The report of the function state
:return: Boolean if message was sent successfully
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/slack_webhook_return.py#L283-L309
|
[
"def _generate_payload(author_icon, title, report):\n '''\n Prepare the payload for Slack\n :param author_icon: The url for the thumbnail to be displayed\n :param title: The title of the message\n :param report: A dictionary with the report of the Salt function\n :return: The payload ready for Slack\n '''\n\n title = _sprinkle(title)\n\n unchanged = {\n 'color': 'good',\n 'title': 'Unchanged: {unchanged}'.format(unchanged=report['unchanged'].get('counter', None))\n }\n\n changed = {\n 'color': 'warning',\n 'title': 'Changed: {changed}'.format(changed=report['changed'].get('counter', None))\n }\n\n if report['changed'].get('tasks'):\n changed['fields'] = list(\n map(_format_task, report['changed'].get('tasks')))\n\n failed = {\n 'color': 'danger',\n 'title': 'Failed: {failed}'.format(failed=report['failed'].get('counter', None))\n }\n\n if report['failed'].get('tasks'):\n failed['fields'] = list(\n map(_format_task, report['failed'].get('tasks')))\n\n text = 'Function: {function}\\n'.format(function=report.get('function'))\n if report.get('arguments'):\n text += 'Function Args: {arguments}\\n'.format(\n arguments=str(list(map(str, report.get('arguments')))))\n\n text += 'JID: {jid}\\n'.format(jid=report.get('jid'))\n text += 'Total: {total}\\n'.format(total=report.get('total'))\n text += 'Duration: {duration:.2f} secs'.format(\n duration=float(report.get('duration')))\n\n payload = {\n 'attachments': [\n {\n 'fallback': title,\n 'color': \"#272727\",\n 'author_name': _sprinkle('{id}'),\n 'author_link': _sprinkle('{localhost}'),\n 'author_icon': author_icon,\n 'title': 'Success: {success}'.format(success=str(report.get('success'))),\n 'text': text\n },\n unchanged,\n changed,\n failed\n ]\n }\n\n return payload\n"
] |
# -*- coding: utf-8 -*-
'''
Return salt data via Slack using Incoming Webhooks
:codeauthor: :email:`Carlos D. Álvaro <github@cdalvaro.io>`
The following fields can be set in the minion conf file:
.. code-block:: yaml
slack_webhook.webhook (required, the webhook id. Just the part after: 'https://hooks.slack.com/services/')
slack_webhook.success_title (optional, short title for succeeded states. By default: '{id} | Succeeded')
slack_webhook.failure_title (optional, short title for failed states. By default: '{id} | Failed')
slack_webhook.author_icon (optional, a URL that with a small 16x16px image. Must be of type: GIF, JPEG, PNG, and BMP)
slack_webhook.show_tasks (optional, show identifiers for changed and failed tasks. By default: False)
Alternative configuration values can be used by prefacing the configuration.
Any values not found in the alternative configuration will be pulled from
the default location:
.. code-block:: yaml
slack_webhook.webhook
slack_webhook.success_title
slack_webhook.failure_title
slack_webhook.author_icon
slack_webhook.show_tasks
Slack settings may also be configured as:
.. code-block:: yaml
slack_webhook:
webhook: T00000000/B00000000/XXXXXXXXXXXXXXXXXXXXXXXX
success_title: [{id}] | Success
failure_title: [{id}] | Failure
author_icon: https://platform.slack-edge.com/img/default_application_icon.png
show_tasks: true
alternative.slack_webhook:
webhook: T00000000/C00000000/YYYYYYYYYYYYYYYYYYYYYYYY
show_tasks: false
To use the Slack returner, append '--return slack_webhook' to the salt command.
.. code-block:: bash
salt '*' test.ping --return slack_webhook
To use the alternative configuration, append '--return_config alternative' to the salt command.
.. code-block:: bash
salt '*' test.ping --return slack_webhook --return_config alternative
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import Python libs
import logging
import json
# pylint: disable=import-error,no-name-in-module,redefined-builtin
import salt.ext.six.moves.http_client
from salt.ext.six.moves.urllib.parse import urlencode as _urlencode
from salt.ext import six
from salt.ext.six.moves import map
from salt.ext.six.moves import range
# pylint: enable=import-error,no-name-in-module,redefined-builtin
# Import Salt Libs
import salt.returners
import salt.utils.http
import salt.utils.yaml
log = logging.getLogger(__name__)
__virtualname__ = 'slack_webhook'
def _get_options(ret=None):
'''
Get the slack_webhook options from salt.
:param ret: Salt return dictionary
:return: A dictionary with options
'''
defaults = {
'success_title': '{id} | Succeeded',
'failure_title': '{id} | Failed',
'author_icon': '',
'show_tasks': False
}
attrs = {
'webhook': 'webhook',
'success_title': 'success_title',
'failure_title': 'failure_title',
'author_icon': 'author_icon',
'show_tasks': 'show_tasks'
}
_options = salt.returners.get_returner_options(__virtualname__,
ret,
attrs,
__salt__=__salt__,
__opts__=__opts__,
defaults=defaults)
return _options
def __virtual__():
'''
Return virtual name of the module.
:return: The virtual name of the module.
'''
return __virtualname__
def _sprinkle(config_str):
'''
Sprinkle with grains of salt, that is
convert 'test {id} test {host} ' types of strings
:param config_str: The string to be sprinkled
:return: The string sprinkled
'''
parts = [x for sub in config_str.split('{') for x in sub.split('}')]
for i in range(1, len(parts), 2):
parts[i] = six.text_type(__grains__.get(parts[i], ''))
return ''.join(parts)
def _format_task(task):
'''
Return a dictionary with the task ready for slack fileds
:param task: The name of the task
:return: A dictionary ready to be inserted in Slack fields array
'''
return {'value': task, 'short': False}
def _generate_payload(author_icon, title, report):
'''
Prepare the payload for Slack
:param author_icon: The url for the thumbnail to be displayed
:param title: The title of the message
:param report: A dictionary with the report of the Salt function
:return: The payload ready for Slack
'''
title = _sprinkle(title)
unchanged = {
'color': 'good',
'title': 'Unchanged: {unchanged}'.format(unchanged=report['unchanged'].get('counter', None))
}
changed = {
'color': 'warning',
'title': 'Changed: {changed}'.format(changed=report['changed'].get('counter', None))
}
if report['changed'].get('tasks'):
changed['fields'] = list(
map(_format_task, report['changed'].get('tasks')))
failed = {
'color': 'danger',
'title': 'Failed: {failed}'.format(failed=report['failed'].get('counter', None))
}
if report['failed'].get('tasks'):
failed['fields'] = list(
map(_format_task, report['failed'].get('tasks')))
text = 'Function: {function}\n'.format(function=report.get('function'))
if report.get('arguments'):
text += 'Function Args: {arguments}\n'.format(
arguments=str(list(map(str, report.get('arguments')))))
text += 'JID: {jid}\n'.format(jid=report.get('jid'))
text += 'Total: {total}\n'.format(total=report.get('total'))
text += 'Duration: {duration:.2f} secs'.format(
duration=float(report.get('duration')))
payload = {
'attachments': [
{
'fallback': title,
'color': "#272727",
'author_name': _sprinkle('{id}'),
'author_link': _sprinkle('{localhost}'),
'author_icon': author_icon,
'title': 'Success: {success}'.format(success=str(report.get('success'))),
'text': text
},
unchanged,
changed,
failed
]
}
return payload
def _generate_report(ret, show_tasks):
'''
Generate a report of the Salt function
:param ret: The Salt return
:param show_tasks: Flag to show the name of the changed and failed states
:return: The report
'''
returns = ret.get('return')
sorted_data = sorted(
returns.items(),
key=lambda s: s[1].get('__run_num__', 0)
)
total = 0
failed = 0
changed = 0
duration = 0.0
changed_tasks = []
failed_tasks = []
# gather stats
for state, data in sorted_data:
# state: module, stateid, name, function
_, stateid, _, _ = state.split('_|-')
task = '{filename}.sls | {taskname}'.format(
filename=str(data.get('__sls__')), taskname=stateid)
if not data.get('result', True):
failed += 1
failed_tasks.append(task)
if data.get('changes', {}):
changed += 1
changed_tasks.append(task)
total += 1
try:
duration += float(data.get('duration', 0.0))
except ValueError:
pass
unchanged = total - failed - changed
log.debug('%s total: %s', __virtualname__, total)
log.debug('%s failed: %s', __virtualname__, failed)
log.debug('%s unchanged: %s', __virtualname__, unchanged)
log.debug('%s changed: %s', __virtualname__, changed)
report = {
'id': ret.get('id'),
'success': True if failed == 0 else False,
'total': total,
'function': ret.get('fun'),
'arguments': ret.get('fun_args', []),
'jid': ret.get('jid'),
'duration': duration / 1000,
'unchanged': {
'counter': unchanged
},
'changed': {
'counter': changed,
'tasks': changed_tasks if show_tasks else []
},
'failed': {
'counter': failed,
'tasks': failed_tasks if show_tasks else []
}
}
return report
def returner(ret):
'''
Send a slack message with the data through a webhook
:param ret: The Salt return
:return: The result of the post
'''
_options = _get_options(ret)
webhook = _options.get('webhook', None)
show_tasks = _options.get('show_tasks')
author_icon = _options.get('author_icon')
if not webhook or webhook is '':
log.error('%s.webhook not defined in salt config', __virtualname__)
return
report = _generate_report(ret, show_tasks)
if report.get('success'):
title = _options.get('success_title')
else:
title = _options.get('failure_title')
slack = _post_message(webhook, author_icon, title, report)
return slack
|
saltstack/salt
|
salt/returners/slack_webhook_return.py
|
returner
|
python
|
def returner(ret):
'''
Send a slack message with the data through a webhook
:param ret: The Salt return
:return: The result of the post
'''
_options = _get_options(ret)
webhook = _options.get('webhook', None)
show_tasks = _options.get('show_tasks')
author_icon = _options.get('author_icon')
if not webhook or webhook is '':
log.error('%s.webhook not defined in salt config', __virtualname__)
return
report = _generate_report(ret, show_tasks)
if report.get('success'):
title = _options.get('success_title')
else:
title = _options.get('failure_title')
slack = _post_message(webhook, author_icon, title, report)
return slack
|
Send a slack message with the data through a webhook
:param ret: The Salt return
:return: The result of the post
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/slack_webhook_return.py#L312-L338
|
[
"def _get_options(ret=None):\n '''\n Get the slack_webhook options from salt.\n :param ret: Salt return dictionary\n :return: A dictionary with options\n '''\n\n defaults = {\n 'success_title': '{id} | Succeeded',\n 'failure_title': '{id} | Failed',\n 'author_icon': '',\n 'show_tasks': False\n }\n\n attrs = {\n 'webhook': 'webhook',\n 'success_title': 'success_title',\n 'failure_title': 'failure_title',\n 'author_icon': 'author_icon',\n 'show_tasks': 'show_tasks'\n }\n\n _options = salt.returners.get_returner_options(__virtualname__,\n ret,\n attrs,\n __salt__=__salt__,\n __opts__=__opts__,\n defaults=defaults)\n return _options\n",
"def _generate_report(ret, show_tasks):\n '''\n Generate a report of the Salt function\n :param ret: The Salt return\n :param show_tasks: Flag to show the name of the changed and failed states\n :return: The report\n '''\n\n returns = ret.get('return')\n\n sorted_data = sorted(\n returns.items(),\n key=lambda s: s[1].get('__run_num__', 0)\n )\n\n total = 0\n failed = 0\n changed = 0\n duration = 0.0\n\n changed_tasks = []\n failed_tasks = []\n\n # gather stats\n for state, data in sorted_data:\n # state: module, stateid, name, function\n _, stateid, _, _ = state.split('_|-')\n task = '{filename}.sls | {taskname}'.format(\n filename=str(data.get('__sls__')), taskname=stateid)\n\n if not data.get('result', True):\n failed += 1\n failed_tasks.append(task)\n\n if data.get('changes', {}):\n changed += 1\n changed_tasks.append(task)\n\n total += 1\n try:\n duration += float(data.get('duration', 0.0))\n except ValueError:\n pass\n\n unchanged = total - failed - changed\n\n log.debug('%s total: %s', __virtualname__, total)\n log.debug('%s failed: %s', __virtualname__, failed)\n log.debug('%s unchanged: %s', __virtualname__, unchanged)\n log.debug('%s changed: %s', __virtualname__, changed)\n\n report = {\n 'id': ret.get('id'),\n 'success': True if failed == 0 else False,\n 'total': total,\n 'function': ret.get('fun'),\n 'arguments': ret.get('fun_args', []),\n 'jid': ret.get('jid'),\n 'duration': duration / 1000,\n 'unchanged': {\n 'counter': unchanged\n },\n 'changed': {\n 'counter': changed,\n 'tasks': changed_tasks if show_tasks else []\n },\n 'failed': {\n 'counter': failed,\n 'tasks': failed_tasks if show_tasks else []\n }\n }\n\n return report\n",
"def _post_message(webhook, author_icon, title, report):\n '''\n Send a message to a Slack room through a webhook\n :param webhook: The url of the incoming webhook\n :param author_icon: The thumbnail image to be displayed on the right side of the message\n :param title: The title of the message\n :param report: The report of the function state\n :return: Boolean if message was sent successfully\n '''\n\n payload = _generate_payload(author_icon, title, report)\n\n data = _urlencode({\n 'payload': json.dumps(payload, ensure_ascii=False)\n })\n\n webhook_url = 'https://hooks.slack.com/services/{webhook}'.format(webhook=webhook)\n query_result = salt.utils.http.query(webhook_url, 'POST', data=data)\n\n if query_result['body'] == 'ok' or query_result['status'] <= 201:\n return True\n else:\n log.error('Slack incoming webhook message post result: %s', query_result)\n return {\n 'res': False,\n 'message': query_result.get('body', query_result['status'])\n }\n"
] |
# -*- coding: utf-8 -*-
'''
Return salt data via Slack using Incoming Webhooks
:codeauthor: :email:`Carlos D. Álvaro <github@cdalvaro.io>`
The following fields can be set in the minion conf file:
.. code-block:: yaml
slack_webhook.webhook (required, the webhook id. Just the part after: 'https://hooks.slack.com/services/')
slack_webhook.success_title (optional, short title for succeeded states. By default: '{id} | Succeeded')
slack_webhook.failure_title (optional, short title for failed states. By default: '{id} | Failed')
slack_webhook.author_icon (optional, a URL that with a small 16x16px image. Must be of type: GIF, JPEG, PNG, and BMP)
slack_webhook.show_tasks (optional, show identifiers for changed and failed tasks. By default: False)
Alternative configuration values can be used by prefacing the configuration.
Any values not found in the alternative configuration will be pulled from
the default location:
.. code-block:: yaml
slack_webhook.webhook
slack_webhook.success_title
slack_webhook.failure_title
slack_webhook.author_icon
slack_webhook.show_tasks
Slack settings may also be configured as:
.. code-block:: yaml
slack_webhook:
webhook: T00000000/B00000000/XXXXXXXXXXXXXXXXXXXXXXXX
success_title: [{id}] | Success
failure_title: [{id}] | Failure
author_icon: https://platform.slack-edge.com/img/default_application_icon.png
show_tasks: true
alternative.slack_webhook:
webhook: T00000000/C00000000/YYYYYYYYYYYYYYYYYYYYYYYY
show_tasks: false
To use the Slack returner, append '--return slack_webhook' to the salt command.
.. code-block:: bash
salt '*' test.ping --return slack_webhook
To use the alternative configuration, append '--return_config alternative' to the salt command.
.. code-block:: bash
salt '*' test.ping --return slack_webhook --return_config alternative
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import Python libs
import logging
import json
# pylint: disable=import-error,no-name-in-module,redefined-builtin
import salt.ext.six.moves.http_client
from salt.ext.six.moves.urllib.parse import urlencode as _urlencode
from salt.ext import six
from salt.ext.six.moves import map
from salt.ext.six.moves import range
# pylint: enable=import-error,no-name-in-module,redefined-builtin
# Import Salt Libs
import salt.returners
import salt.utils.http
import salt.utils.yaml
log = logging.getLogger(__name__)
__virtualname__ = 'slack_webhook'
def _get_options(ret=None):
'''
Get the slack_webhook options from salt.
:param ret: Salt return dictionary
:return: A dictionary with options
'''
defaults = {
'success_title': '{id} | Succeeded',
'failure_title': '{id} | Failed',
'author_icon': '',
'show_tasks': False
}
attrs = {
'webhook': 'webhook',
'success_title': 'success_title',
'failure_title': 'failure_title',
'author_icon': 'author_icon',
'show_tasks': 'show_tasks'
}
_options = salt.returners.get_returner_options(__virtualname__,
ret,
attrs,
__salt__=__salt__,
__opts__=__opts__,
defaults=defaults)
return _options
def __virtual__():
'''
Return virtual name of the module.
:return: The virtual name of the module.
'''
return __virtualname__
def _sprinkle(config_str):
'''
Sprinkle with grains of salt, that is
convert 'test {id} test {host} ' types of strings
:param config_str: The string to be sprinkled
:return: The string sprinkled
'''
parts = [x for sub in config_str.split('{') for x in sub.split('}')]
for i in range(1, len(parts), 2):
parts[i] = six.text_type(__grains__.get(parts[i], ''))
return ''.join(parts)
def _format_task(task):
'''
Return a dictionary with the task ready for slack fileds
:param task: The name of the task
:return: A dictionary ready to be inserted in Slack fields array
'''
return {'value': task, 'short': False}
def _generate_payload(author_icon, title, report):
'''
Prepare the payload for Slack
:param author_icon: The url for the thumbnail to be displayed
:param title: The title of the message
:param report: A dictionary with the report of the Salt function
:return: The payload ready for Slack
'''
title = _sprinkle(title)
unchanged = {
'color': 'good',
'title': 'Unchanged: {unchanged}'.format(unchanged=report['unchanged'].get('counter', None))
}
changed = {
'color': 'warning',
'title': 'Changed: {changed}'.format(changed=report['changed'].get('counter', None))
}
if report['changed'].get('tasks'):
changed['fields'] = list(
map(_format_task, report['changed'].get('tasks')))
failed = {
'color': 'danger',
'title': 'Failed: {failed}'.format(failed=report['failed'].get('counter', None))
}
if report['failed'].get('tasks'):
failed['fields'] = list(
map(_format_task, report['failed'].get('tasks')))
text = 'Function: {function}\n'.format(function=report.get('function'))
if report.get('arguments'):
text += 'Function Args: {arguments}\n'.format(
arguments=str(list(map(str, report.get('arguments')))))
text += 'JID: {jid}\n'.format(jid=report.get('jid'))
text += 'Total: {total}\n'.format(total=report.get('total'))
text += 'Duration: {duration:.2f} secs'.format(
duration=float(report.get('duration')))
payload = {
'attachments': [
{
'fallback': title,
'color': "#272727",
'author_name': _sprinkle('{id}'),
'author_link': _sprinkle('{localhost}'),
'author_icon': author_icon,
'title': 'Success: {success}'.format(success=str(report.get('success'))),
'text': text
},
unchanged,
changed,
failed
]
}
return payload
def _generate_report(ret, show_tasks):
'''
Generate a report of the Salt function
:param ret: The Salt return
:param show_tasks: Flag to show the name of the changed and failed states
:return: The report
'''
returns = ret.get('return')
sorted_data = sorted(
returns.items(),
key=lambda s: s[1].get('__run_num__', 0)
)
total = 0
failed = 0
changed = 0
duration = 0.0
changed_tasks = []
failed_tasks = []
# gather stats
for state, data in sorted_data:
# state: module, stateid, name, function
_, stateid, _, _ = state.split('_|-')
task = '{filename}.sls | {taskname}'.format(
filename=str(data.get('__sls__')), taskname=stateid)
if not data.get('result', True):
failed += 1
failed_tasks.append(task)
if data.get('changes', {}):
changed += 1
changed_tasks.append(task)
total += 1
try:
duration += float(data.get('duration', 0.0))
except ValueError:
pass
unchanged = total - failed - changed
log.debug('%s total: %s', __virtualname__, total)
log.debug('%s failed: %s', __virtualname__, failed)
log.debug('%s unchanged: %s', __virtualname__, unchanged)
log.debug('%s changed: %s', __virtualname__, changed)
report = {
'id': ret.get('id'),
'success': True if failed == 0 else False,
'total': total,
'function': ret.get('fun'),
'arguments': ret.get('fun_args', []),
'jid': ret.get('jid'),
'duration': duration / 1000,
'unchanged': {
'counter': unchanged
},
'changed': {
'counter': changed,
'tasks': changed_tasks if show_tasks else []
},
'failed': {
'counter': failed,
'tasks': failed_tasks if show_tasks else []
}
}
return report
def _post_message(webhook, author_icon, title, report):
'''
Send a message to a Slack room through a webhook
:param webhook: The url of the incoming webhook
:param author_icon: The thumbnail image to be displayed on the right side of the message
:param title: The title of the message
:param report: The report of the function state
:return: Boolean if message was sent successfully
'''
payload = _generate_payload(author_icon, title, report)
data = _urlencode({
'payload': json.dumps(payload, ensure_ascii=False)
})
webhook_url = 'https://hooks.slack.com/services/{webhook}'.format(webhook=webhook)
query_result = salt.utils.http.query(webhook_url, 'POST', data=data)
if query_result['body'] == 'ok' or query_result['status'] <= 201:
return True
else:
log.error('Slack incoming webhook message post result: %s', query_result)
return {
'res': False,
'message': query_result.get('body', query_result['status'])
}
|
saltstack/salt
|
salt/modules/winrepo.py
|
update_git_repos
|
python
|
def update_git_repos(clean=False):
'''
Checkout git repos containing :ref:`Windows Software Package Definitions
<windows-package-manager>`.
.. important::
This function requires `Git for Windows`_ to be installed in order to
work. When installing, make sure to select an installation option which
permits the git executable to be run from the Command Prompt.
.. _`Git for Windows`: https://git-for-windows.github.io/
clean : False
Clean repo cachedirs which are not configured under
:conf_minion:`winrepo_remotes`.
.. note::
This option only applies if either pygit2_ or GitPython_ is
installed into Salt's bundled Python.
.. warning::
This argument should not be set to ``True`` if a mix of git and
non-git repo definitions are being used, as it will result in the
non-git repo definitions being removed.
.. versionadded:: 2015.8.0
.. _GitPython: https://github.com/gitpython-developers/GitPython
.. _pygit2: https://github.com/libgit2/pygit2
CLI Example:
.. code-block:: bash
salt-call winrepo.update_git_repos
'''
if not salt.utils.path.which('git'):
raise CommandExecutionError(
'Git for Windows is not installed, or not configured to be '
'accessible from the Command Prompt'
)
return _update_git_repos(opts=__opts__, clean=clean, masterless=True)
|
Checkout git repos containing :ref:`Windows Software Package Definitions
<windows-package-manager>`.
.. important::
This function requires `Git for Windows`_ to be installed in order to
work. When installing, make sure to select an installation option which
permits the git executable to be run from the Command Prompt.
.. _`Git for Windows`: https://git-for-windows.github.io/
clean : False
Clean repo cachedirs which are not configured under
:conf_minion:`winrepo_remotes`.
.. note::
This option only applies if either pygit2_ or GitPython_ is
installed into Salt's bundled Python.
.. warning::
This argument should not be set to ``True`` if a mix of git and
non-git repo definitions are being used, as it will result in the
non-git repo definitions being removed.
.. versionadded:: 2015.8.0
.. _GitPython: https://github.com/gitpython-developers/GitPython
.. _pygit2: https://github.com/libgit2/pygit2
CLI Example:
.. code-block:: bash
salt-call winrepo.update_git_repos
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/winrepo.py#L81-L122
| null |
# -*- coding: utf-8 -*-
r'''
Module to manage Windows software repo on a Standalone Minion
``file_client: local`` must be set in the minion config file.
For documentation on Salt's Windows Repo feature, see :ref:`here
<windows-package-manager>`.
'''
# Import python libs
from __future__ import absolute_import, unicode_literals, print_function
import logging
import os
# Import salt libs
import salt.output
import salt.utils.functools
import salt.utils.path
import salt.utils.platform
import salt.loader
import salt.template
from salt.exceptions import CommandExecutionError, SaltRenderError
# All the "unused" imports here are needed for the imported winrepo runner code
# pylint: disable=unused-import
from salt.runners.winrepo import (
genrepo as _genrepo,
update_git_repos as _update_git_repos,
PER_REMOTE_OVERRIDES,
PER_REMOTE_ONLY,
GLOBAL_ONLY
)
from salt.ext import six
import salt.utils.gitfs
import salt.utils.msgpack
# pylint: enable=unused-import
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'winrepo'
def __virtual__():
'''
Set the winrepo module if the OS is Windows
'''
if salt.utils.platform.is_windows():
global _genrepo, _update_git_repos
_genrepo = salt.utils.functools.namespaced_function(_genrepo, globals())
_update_git_repos = \
salt.utils.functools.namespaced_function(_update_git_repos, globals())
return __virtualname__
return (False, 'This module only works on Windows.')
def _get_local_repo_dir(saltenv='base'):
winrepo_source_dir = __opts__['winrepo_source_dir']
dirs = []
dirs.append(salt.syspaths.CACHE_DIR)
dirs.extend(['minion', 'files'])
dirs.append(saltenv)
dirs.extend(winrepo_source_dir[7:].strip('/').split('/'))
return os.sep.join(dirs)
def genrepo():
r'''
Generate winrepo_cachefile based on sls files in the winrepo_dir
CLI Example:
.. code-block:: bash
salt-call winrepo.genrepo
'''
return _genrepo(opts=__opts__, fire_event=False)
def show_sls(name, saltenv='base'):
r'''
.. versionadded:: 2015.8.0
Display the rendered software definition from a specific sls file in the
local winrepo cache. This will parse all Jinja. Run pkg.refresh_db to pull
the latest software definitions from the master.
.. note::
This function does not ask a master for an sls file to render. Instead
it directly processes the file specified in `name`
Args:
name str: The name/path of the package you want to view. This can be the
full path to a file on the minion file system or a file on the local
minion cache.
saltenv str: The default environment is ``base``
Returns:
dict: Returns a dictionary containing the rendered data structure
.. note::
To use a file from the minion cache start from the local winrepo root
(``C:\salt\var\cache\salt\minion\files\base\win\repo-ng``). If you have
``.sls`` files organized in subdirectories you'll have to denote them
with ``.``. For example, if you have a ``test`` directory in the winrepo
root with a ``gvim.sls`` file inside, would target that file like so:
``test.gvim``. Directories can be targeted as well as long as they
contain an ``init.sls`` inside. For example, if you have a ``node``
directory with an ``init.sls`` inside, target that like so: ``node``.
CLI Example:
.. code-block:: bash
salt '*' winrepo.show_sls gvim
salt '*' winrepo.show_sls test.npp
salt '*' winrepo.show_sls C:\test\gvim.sls
'''
# Passed a filename
if os.path.exists(name):
sls_file = name
# Use a winrepo path
else:
# Get the location of the local repo
repo = _get_local_repo_dir(saltenv)
# Add the sls file name to the path
repo = repo.split('\\')
definition = name.split('.')
repo.extend(definition)
# Check for the sls file by name
sls_file = '{0}.sls'.format(os.sep.join(repo))
if not os.path.exists(sls_file):
# Maybe it's a directory with an init.sls
sls_file = '{0}\\init.sls'.format(os.sep.join(repo))
if not os.path.exists(sls_file):
# It's neither, return
return 'Software definition {0} not found'.format(name)
# Load the renderer
renderers = salt.loader.render(__opts__, __salt__)
config = {}
# Run the file through the renderer
try:
config = salt.template.compile_template(
sls_file,
renderers,
__opts__['renderer'],
__opts__['renderer_blacklist'],
__opts__['renderer_whitelist'])
# Return the error if any
except SaltRenderError as exc:
log.debug('Failed to compile %s.', sls_file)
log.debug('Error: %s.', exc)
config['Message'] = 'Failed to compile {0}'.format(sls_file)
config['Error'] = '{0}'.format(exc)
return config
|
saltstack/salt
|
salt/modules/winrepo.py
|
show_sls
|
python
|
def show_sls(name, saltenv='base'):
r'''
.. versionadded:: 2015.8.0
Display the rendered software definition from a specific sls file in the
local winrepo cache. This will parse all Jinja. Run pkg.refresh_db to pull
the latest software definitions from the master.
.. note::
This function does not ask a master for an sls file to render. Instead
it directly processes the file specified in `name`
Args:
name str: The name/path of the package you want to view. This can be the
full path to a file on the minion file system or a file on the local
minion cache.
saltenv str: The default environment is ``base``
Returns:
dict: Returns a dictionary containing the rendered data structure
.. note::
To use a file from the minion cache start from the local winrepo root
(``C:\salt\var\cache\salt\minion\files\base\win\repo-ng``). If you have
``.sls`` files organized in subdirectories you'll have to denote them
with ``.``. For example, if you have a ``test`` directory in the winrepo
root with a ``gvim.sls`` file inside, would target that file like so:
``test.gvim``. Directories can be targeted as well as long as they
contain an ``init.sls`` inside. For example, if you have a ``node``
directory with an ``init.sls`` inside, target that like so: ``node``.
CLI Example:
.. code-block:: bash
salt '*' winrepo.show_sls gvim
salt '*' winrepo.show_sls test.npp
salt '*' winrepo.show_sls C:\test\gvim.sls
'''
# Passed a filename
if os.path.exists(name):
sls_file = name
# Use a winrepo path
else:
# Get the location of the local repo
repo = _get_local_repo_dir(saltenv)
# Add the sls file name to the path
repo = repo.split('\\')
definition = name.split('.')
repo.extend(definition)
# Check for the sls file by name
sls_file = '{0}.sls'.format(os.sep.join(repo))
if not os.path.exists(sls_file):
# Maybe it's a directory with an init.sls
sls_file = '{0}\\init.sls'.format(os.sep.join(repo))
if not os.path.exists(sls_file):
# It's neither, return
return 'Software definition {0} not found'.format(name)
# Load the renderer
renderers = salt.loader.render(__opts__, __salt__)
config = {}
# Run the file through the renderer
try:
config = salt.template.compile_template(
sls_file,
renderers,
__opts__['renderer'],
__opts__['renderer_blacklist'],
__opts__['renderer_whitelist'])
# Return the error if any
except SaltRenderError as exc:
log.debug('Failed to compile %s.', sls_file)
log.debug('Error: %s.', exc)
config['Message'] = 'Failed to compile {0}'.format(sls_file)
config['Error'] = '{0}'.format(exc)
return config
|
r'''
.. versionadded:: 2015.8.0
Display the rendered software definition from a specific sls file in the
local winrepo cache. This will parse all Jinja. Run pkg.refresh_db to pull
the latest software definitions from the master.
.. note::
This function does not ask a master for an sls file to render. Instead
it directly processes the file specified in `name`
Args:
name str: The name/path of the package you want to view. This can be the
full path to a file on the minion file system or a file on the local
minion cache.
saltenv str: The default environment is ``base``
Returns:
dict: Returns a dictionary containing the rendered data structure
.. note::
To use a file from the minion cache start from the local winrepo root
(``C:\salt\var\cache\salt\minion\files\base\win\repo-ng``). If you have
``.sls`` files organized in subdirectories you'll have to denote them
with ``.``. For example, if you have a ``test`` directory in the winrepo
root with a ``gvim.sls`` file inside, would target that file like so:
``test.gvim``. Directories can be targeted as well as long as they
contain an ``init.sls`` inside. For example, if you have a ``node``
directory with an ``init.sls`` inside, target that like so: ``node``.
CLI Example:
.. code-block:: bash
salt '*' winrepo.show_sls gvim
salt '*' winrepo.show_sls test.npp
salt '*' winrepo.show_sls C:\test\gvim.sls
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/winrepo.py#L125-L210
|
[
"def compile_template(template,\n renderers,\n default,\n blacklist,\n whitelist,\n saltenv='base',\n sls='',\n input_data='',\n **kwargs):\n '''\n Take the path to a template and return the high data structure\n derived from the template.\n\n Helpers:\n\n :param mask_value:\n Mask value for debugging purposes (prevent sensitive information etc)\n example: \"mask_value=\"pass*\". All \"passwd\", \"password\", \"pass\" will\n be masked (as text).\n '''\n\n # if any error occurs, we return an empty dictionary\n ret = {}\n\n log.debug('compile template: %s', template)\n\n if 'env' in kwargs:\n # \"env\" is not supported; Use \"saltenv\".\n kwargs.pop('env')\n\n if template != ':string:':\n # Template was specified incorrectly\n if not isinstance(template, six.string_types):\n log.error('Template was specified incorrectly: %s', template)\n return ret\n # Template does not exist\n if not os.path.isfile(template):\n log.error('Template does not exist: %s', template)\n return ret\n # Template is an empty file\n if salt.utils.files.is_empty(template):\n log.debug('Template is an empty file: %s', template)\n return ret\n\n with codecs.open(template, encoding=SLS_ENCODING) as ifile:\n # data input to the first render function in the pipe\n input_data = ifile.read()\n if not input_data.strip():\n # Template is nothing but whitespace\n log.error('Template is nothing but whitespace: %s', template)\n return ret\n\n # Get the list of render funcs in the render pipe line.\n render_pipe = template_shebang(template, renderers, default, blacklist, whitelist, input_data)\n\n windows_newline = '\\r\\n' in input_data\n\n input_data = StringIO(input_data)\n for render, argline in render_pipe:\n if salt.utils.stringio.is_readable(input_data):\n input_data.seek(0) # pylint: disable=no-member\n render_kwargs = dict(renderers=renderers, tmplpath=template)\n render_kwargs.update(kwargs)\n if argline:\n render_kwargs['argline'] = argline\n start = time.time()\n ret = render(input_data, saltenv, sls, **render_kwargs)\n log.profile(\n 'Time (in seconds) to render \\'%s\\' using \\'%s\\' renderer: %s',\n template,\n render.__module__.split('.')[-1],\n time.time() - start\n )\n if ret is None:\n # The file is empty or is being written elsewhere\n time.sleep(0.01)\n ret = render(input_data, saltenv, sls, **render_kwargs)\n input_data = ret\n if log.isEnabledFor(logging.GARBAGE): # pylint: disable=no-member\n # If ret is not a StringIO (which means it was rendered using\n # yaml, mako, or another engine which renders to a data\n # structure) we don't want to log this.\n if salt.utils.stringio.is_readable(ret):\n log.debug('Rendered data from file: %s:\\n%s', template,\n salt.utils.sanitizers.mask_args_value(salt.utils.data.decode(ret.read()),\n kwargs.get('mask_value'))) # pylint: disable=no-member\n ret.seek(0) # pylint: disable=no-member\n\n # Preserve newlines from original template\n if windows_newline:\n if salt.utils.stringio.is_readable(ret):\n is_stringio = True\n contents = ret.read()\n else:\n is_stringio = False\n contents = ret\n\n if isinstance(contents, six.string_types):\n if '\\r\\n' not in contents:\n contents = contents.replace('\\n', '\\r\\n')\n ret = StringIO(contents) if is_stringio else contents\n else:\n if is_stringio:\n ret.seek(0)\n return ret\n",
"def _get_local_repo_dir(saltenv='base'):\n winrepo_source_dir = __opts__['winrepo_source_dir']\n dirs = []\n dirs.append(salt.syspaths.CACHE_DIR)\n dirs.extend(['minion', 'files'])\n dirs.append(saltenv)\n dirs.extend(winrepo_source_dir[7:].strip('/').split('/'))\n return os.sep.join(dirs)\n"
] |
# -*- coding: utf-8 -*-
r'''
Module to manage Windows software repo on a Standalone Minion
``file_client: local`` must be set in the minion config file.
For documentation on Salt's Windows Repo feature, see :ref:`here
<windows-package-manager>`.
'''
# Import python libs
from __future__ import absolute_import, unicode_literals, print_function
import logging
import os
# Import salt libs
import salt.output
import salt.utils.functools
import salt.utils.path
import salt.utils.platform
import salt.loader
import salt.template
from salt.exceptions import CommandExecutionError, SaltRenderError
# All the "unused" imports here are needed for the imported winrepo runner code
# pylint: disable=unused-import
from salt.runners.winrepo import (
genrepo as _genrepo,
update_git_repos as _update_git_repos,
PER_REMOTE_OVERRIDES,
PER_REMOTE_ONLY,
GLOBAL_ONLY
)
from salt.ext import six
import salt.utils.gitfs
import salt.utils.msgpack
# pylint: enable=unused-import
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'winrepo'
def __virtual__():
'''
Set the winrepo module if the OS is Windows
'''
if salt.utils.platform.is_windows():
global _genrepo, _update_git_repos
_genrepo = salt.utils.functools.namespaced_function(_genrepo, globals())
_update_git_repos = \
salt.utils.functools.namespaced_function(_update_git_repos, globals())
return __virtualname__
return (False, 'This module only works on Windows.')
def _get_local_repo_dir(saltenv='base'):
winrepo_source_dir = __opts__['winrepo_source_dir']
dirs = []
dirs.append(salt.syspaths.CACHE_DIR)
dirs.extend(['minion', 'files'])
dirs.append(saltenv)
dirs.extend(winrepo_source_dir[7:].strip('/').split('/'))
return os.sep.join(dirs)
def genrepo():
r'''
Generate winrepo_cachefile based on sls files in the winrepo_dir
CLI Example:
.. code-block:: bash
salt-call winrepo.genrepo
'''
return _genrepo(opts=__opts__, fire_event=False)
def update_git_repos(clean=False):
'''
Checkout git repos containing :ref:`Windows Software Package Definitions
<windows-package-manager>`.
.. important::
This function requires `Git for Windows`_ to be installed in order to
work. When installing, make sure to select an installation option which
permits the git executable to be run from the Command Prompt.
.. _`Git for Windows`: https://git-for-windows.github.io/
clean : False
Clean repo cachedirs which are not configured under
:conf_minion:`winrepo_remotes`.
.. note::
This option only applies if either pygit2_ or GitPython_ is
installed into Salt's bundled Python.
.. warning::
This argument should not be set to ``True`` if a mix of git and
non-git repo definitions are being used, as it will result in the
non-git repo definitions being removed.
.. versionadded:: 2015.8.0
.. _GitPython: https://github.com/gitpython-developers/GitPython
.. _pygit2: https://github.com/libgit2/pygit2
CLI Example:
.. code-block:: bash
salt-call winrepo.update_git_repos
'''
if not salt.utils.path.which('git'):
raise CommandExecutionError(
'Git for Windows is not installed, or not configured to be '
'accessible from the Command Prompt'
)
return _update_git_repos(opts=__opts__, clean=clean, masterless=True)
|
saltstack/salt
|
salt/modules/lxc.py
|
version
|
python
|
def version():
'''
Return the actual lxc client version
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.version
'''
k = 'lxc.version'
if not __context__.get(k, None):
cversion = __salt__['cmd.run_all']('lxc-info --version')
if not cversion['retcode']:
ver = _LooseVersion(cversion['stdout'])
if ver < _LooseVersion('1.0'):
raise CommandExecutionError('LXC should be at least 1.0')
__context__[k] = "{0}".format(ver)
return __context__.get(k, None)
|
Return the actual lxc client version
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.version
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/lxc.py#L111-L132
| null |
# -*- coding: utf-8 -*-
'''
Control Linux Containers via Salt
:depends: lxc package for distribution
lxc >= 1.0 (even beta alpha) is required
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import datetime
import copy
import string
import textwrap
import difflib
import logging
import tempfile
import os
import pipes
import time
import shutil
import re
import random
# Import salt libs
import salt.utils.args
import salt.utils.cloud
import salt.utils.data
import salt.utils.dictupdate
import salt.utils.files
import salt.utils.functools
import salt.utils.hashutils
import salt.utils.network
import salt.utils.odict
import salt.utils.path
import salt.utils.stringutils
from salt.exceptions import CommandExecutionError, SaltInvocationError
import salt.config
from salt.utils.versions import LooseVersion as _LooseVersion
# Import 3rd-party libs
from salt.ext import six
# pylint: disable=import-error,no-name-in-module
from salt.ext.six.moves import range # pylint: disable=redefined-builtin
from salt.ext.six.moves.urllib.parse import urlparse as _urlparse
# pylint: enable=import-error,no-name-in-module
# Set up logging
log = logging.getLogger(__name__)
# Don't shadow built-in's.
__func_alias__ = {
'list_': 'list',
'ls_': 'ls'
}
__virtualname__ = 'lxc'
DEFAULT_NIC = 'eth0'
DEFAULT_BR = 'br0'
SEED_MARKER = '/lxc.initial_seed'
EXEC_DRIVER = 'lxc-attach'
DEFAULT_PATH = '/var/lib/lxc'
_marker = object()
def __virtual__():
if salt.utils.path.which('lxc-start'):
return __virtualname__
# To speed up the whole thing, we decided to not use the
# subshell way and assume things are in place for lxc
# Discussion made by @kiorky and @thatch45
# lxc-version presence is not sufficient, in lxc1.0 alpha
# (precise backports), we have it and it is sufficient
# for the module to execute.
# elif salt.utils.path.which('lxc-version'):
# passed = False
# try:
# passed = subprocess.check_output(
# 'lxc-version').split(':')[1].strip() >= '1.0'
# except Exception:
# pass
# if not passed:
# log.warning('Support for lxc < 1.0 may be incomplete.')
# return 'lxc'
# return False
#
return (False, 'The lxc execution module cannot be loaded: the lxc-start binary is not in the path.')
def get_root_path(path):
'''
Get the configured lxc root for containers
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.get_root_path
'''
if not path:
path = __opts__.get('lxc.root_path', DEFAULT_PATH)
return path
def _clear_context():
'''
Clear any lxc variables set in __context__
'''
for var in [x for x in __context__ if x.startswith('lxc.')]:
log.trace('Clearing __context__[\'%s\']', var)
__context__.pop(var, None)
def _ip_sort(ip):
'''Ip sorting'''
idx = '001'
if ip == '127.0.0.1':
idx = '200'
if ip == '::1':
idx = '201'
elif '::' in ip:
idx = '100'
return '{0}___{1}'.format(idx, ip)
def search_lxc_bridges():
'''
Search which bridges are potentially available as LXC bridges
CLI Example:
.. code-block:: bash
salt '*' lxc.search_lxc_bridges
'''
bridges = __context__.get('lxc.bridges', None)
# either match not yet called or no bridges were found
# to handle the case where lxc was not installed on the first
# call
if not bridges:
bridges = set()
running_bridges = set()
bridges.add(DEFAULT_BR)
try:
output = __salt__['cmd.run_all']('brctl show')
for line in output['stdout'].splitlines()[1:]:
if not line.startswith(' '):
running_bridges.add(line.split()[0].strip())
except (SaltInvocationError, CommandExecutionError):
pass
for ifc, ip in six.iteritems(
__grains__.get('ip_interfaces', {})
):
if ifc in running_bridges:
bridges.add(ifc)
elif os.path.exists(
'/sys/devices/virtual/net/{0}/bridge'.format(ifc)
):
bridges.add(ifc)
bridges = list(bridges)
# if we found interfaces that have lxc in their names
# we filter them as being the potential lxc bridges
# we also try to default on br0 on other cases
def sort_bridges(a):
pref = 'z'
if 'lxc' in a:
pref = 'a'
elif 'br0' == a:
pref = 'c'
return '{0}_{1}'.format(pref, a)
bridges.sort(key=sort_bridges)
__context__['lxc.bridges'] = bridges
return bridges
def search_lxc_bridge():
'''
Search the first bridge which is potentially available as LXC bridge
CLI Example:
.. code-block:: bash
salt '*' lxc.search_lxc_bridge
'''
return search_lxc_bridges()[0]
def _get_salt_config(config, **kwargs):
if not config:
config = kwargs.get('minion', {})
if not config:
config = {}
config.setdefault('master',
kwargs.get('master',
__opts__.get('master',
__opts__['id'])))
config.setdefault(
'master_port',
kwargs.get('master_port',
__opts__.get('master_port',
__opts__.get('ret_port',
__opts__.get('4506')))))
if not config['master']:
config = {}
return config
def cloud_init_interface(name, vm_=None, **kwargs):
'''
Interface between salt.cloud.lxc driver and lxc.init
``vm_`` is a mapping of vm opts in the salt.cloud format
as documented for the lxc driver.
This can be used either:
- from the salt cloud driver
- because you find the argument to give easier here
than using directly lxc.init
.. warning::
BE REALLY CAREFUL CHANGING DEFAULTS !!!
IT'S A RETRO COMPATIBLE INTERFACE WITH
THE SALT CLOUD DRIVER (ask kiorky).
name
name of the lxc container to create
pub_key
public key to preseed the minion with.
Can be the keycontent or a filepath
priv_key
private key to preseed the minion with.
Can be the keycontent or a filepath
path
path to the container parent directory (default: /var/lib/lxc)
.. versionadded:: 2015.8.0
profile
:ref:`profile <tutorial-lxc-profiles-container>` selection
network_profile
:ref:`network profile <tutorial-lxc-profiles-network>` selection
nic_opts
per interface settings compatibles with
network profile (ipv4/ipv6/link/gateway/mac/netmask)
eg::
- {'eth0': {'mac': '00:16:3e:01:29:40',
'gateway': None, (default)
'link': 'br0', (default)
'gateway': None, (default)
'netmask': '', (default)
'ip': '22.1.4.25'}}
unconditional_install
given to lxc.bootstrap (see relative doc)
force_install
given to lxc.bootstrap (see relative doc)
config
any extra argument for the salt minion config
dnsservers
list of DNS servers to set inside the container
dns_via_dhcp
do not set the dns servers, let them be set by the dhcp.
autostart
autostart the container at boot time
password
administrative password for the container
bootstrap_delay
delay before launching bootstrap script at Container init
.. warning::
Legacy but still supported options:
from_container
which container we use as a template
when running lxc.clone
image
which template do we use when we
are using lxc.create. This is the default
mode unless you specify something in from_container
backing
which backing store to use.
Values can be: overlayfs, dir(default), lvm, zfs, brtfs
fstype
When using a blockdevice level backing store,
which filesystem to use on
size
When using a blockdevice level backing store,
which size for the filesystem to use on
snapshot
Use snapshot when cloning the container source
vgname
if using LVM: vgname
lvname
if using LVM: lvname
thinpool:
if using LVM: thinpool
ip
ip for the primary nic
mac
mac address for the primary nic
netmask
netmask for the primary nic (24)
= ``vm_.get('netmask', '24')``
bridge
bridge for the primary nic (lxcbr0)
gateway
network gateway for the container
additional_ips
additional ips which will be wired on the main bridge (br0)
which is connected to internet.
Be aware that you may use manual virtual mac addresses
providen by you provider (online, ovh, etc).
This is a list of mappings {ip: '', mac: '', netmask:''}
Set gateway to None and an interface with a gateway
to escape from another interface that eth0.
eg::
- {'mac': '00:16:3e:01:29:40',
'gateway': None, (default)
'link': 'br0', (default)
'netmask': '', (default)
'ip': '22.1.4.25'}
users
administrative users for the container
default: [root] and [root, ubuntu] on ubuntu
default_nic
name of the first interface, you should
really not override this
CLI Example:
.. code-block:: bash
salt '*' lxc.cloud_init_interface foo
'''
if vm_ is None:
vm_ = {}
vm_ = copy.deepcopy(vm_)
vm_ = salt.utils.dictupdate.update(vm_, kwargs)
profile_data = copy.deepcopy(
vm_.get('lxc_profile',
vm_.get('profile', {})))
if not isinstance(profile_data, (dict, six.string_types)):
profile_data = {}
profile = get_container_profile(profile_data)
def _cloud_get(k, default=None):
return vm_.get(k, profile.get(k, default))
if name is None:
name = vm_['name']
# if we are on ubuntu, default to ubuntu
default_template = ''
if __grains__.get('os', '') in ['Ubuntu']:
default_template = 'ubuntu'
image = _cloud_get('image')
if not image:
_cloud_get('template', default_template)
backing = _cloud_get('backing', 'dir')
if image:
profile['template'] = image
vgname = _cloud_get('vgname', None)
if vgname:
profile['vgname'] = vgname
if backing:
profile['backing'] = backing
snapshot = _cloud_get('snapshot', False)
autostart = bool(_cloud_get('autostart', True))
dnsservers = _cloud_get('dnsservers', [])
dns_via_dhcp = _cloud_get('dns_via_dhcp', True)
password = _cloud_get('password', 's3cr3t')
password_encrypted = _cloud_get('password_encrypted', False)
fstype = _cloud_get('fstype', None)
lvname = _cloud_get('lvname', None)
thinpool = _cloud_get('thinpool', None)
pub_key = _cloud_get('pub_key', None)
priv_key = _cloud_get('priv_key', None)
size = _cloud_get('size', '20G')
script = _cloud_get('script', None)
script_args = _cloud_get('script_args', None)
users = _cloud_get('users', None)
if users is None:
users = []
ssh_username = _cloud_get('ssh_username', None)
if ssh_username and (ssh_username not in users):
users.append(ssh_username)
network_profile = _cloud_get('network_profile', None)
nic_opts = kwargs.get('nic_opts', None)
netmask = _cloud_get('netmask', '24')
path = _cloud_get('path', None)
bridge = _cloud_get('bridge', None)
gateway = _cloud_get('gateway', None)
unconditional_install = _cloud_get('unconditional_install', False)
force_install = _cloud_get('force_install', True)
config = _get_salt_config(_cloud_get('config', {}), **vm_)
default_nic = _cloud_get('default_nic', DEFAULT_NIC)
# do the interface with lxc.init mainly via nic_opts
# to avoid extra and confusing extra use cases.
if not isinstance(nic_opts, dict):
nic_opts = salt.utils.odict.OrderedDict()
# have a reference to the default nic
eth0 = nic_opts.setdefault(default_nic,
salt.utils.odict.OrderedDict())
# lxc config is based of ifc order, be sure to use odicts.
if not isinstance(nic_opts, salt.utils.odict.OrderedDict):
bnic_opts = salt.utils.odict.OrderedDict()
bnic_opts.update(nic_opts)
nic_opts = bnic_opts
gw = None
# legacy salt.cloud scheme for network interfaces settings support
bridge = _cloud_get('bridge', None)
ip = _cloud_get('ip', None)
mac = _cloud_get('mac', None)
if ip:
fullip = ip
if netmask:
fullip += '/{0}'.format(netmask)
eth0['ipv4'] = fullip
if mac is not None:
eth0['mac'] = mac
for ix, iopts in enumerate(_cloud_get("additional_ips", [])):
ifh = "eth{0}".format(ix+1)
ethx = nic_opts.setdefault(ifh, {})
if gw is None:
gw = iopts.get('gateway', ethx.get('gateway', None))
if gw:
# only one and only one default gateway is allowed !
eth0.pop('gateway', None)
gateway = None
# even if the gateway if on default "eth0" nic
# and we popped it will work
# as we reinject or set it here.
ethx['gateway'] = gw
elink = iopts.get('link', ethx.get('link', None))
if elink:
ethx['link'] = elink
# allow dhcp
aip = iopts.get('ipv4', iopts.get('ip', None))
if aip:
ethx['ipv4'] = aip
nm = iopts.get('netmask', '')
if nm:
ethx['ipv4'] += '/{0}'.format(nm)
for i in ('mac', 'hwaddr'):
if i in iopts:
ethx['mac'] = iopts[i]
break
if 'mac' not in ethx:
ethx['mac'] = salt.utils.network.gen_mac()
# last round checking for unique gateway and such
gw = None
for ethx in [a for a in nic_opts]:
ndata = nic_opts[ethx]
if gw:
ndata.pop('gateway', None)
if 'gateway' in ndata:
gw = ndata['gateway']
gateway = None
# only use a default bridge / gateway if we configured them
# via the legacy salt cloud configuration style.
# On other cases, we should rely on settings provided by the new
# salt lxc network profile style configuration which can
# be also be overridden or a per interface basis via the nic_opts dict.
if bridge:
eth0['link'] = bridge
if gateway:
eth0['gateway'] = gateway
#
lxc_init_interface = {}
lxc_init_interface['name'] = name
lxc_init_interface['config'] = config
lxc_init_interface['memory'] = _cloud_get('memory', 0) # nolimit
lxc_init_interface['pub_key'] = pub_key
lxc_init_interface['priv_key'] = priv_key
lxc_init_interface['nic_opts'] = nic_opts
for clone_from in ['clone_from', 'clone', 'from_container']:
# clone_from should default to None if not available
lxc_init_interface['clone_from'] = _cloud_get(clone_from, None)
if lxc_init_interface['clone_from'] is not None:
break
lxc_init_interface['profile'] = profile
lxc_init_interface['snapshot'] = snapshot
lxc_init_interface['dnsservers'] = dnsservers
lxc_init_interface['fstype'] = fstype
lxc_init_interface['path'] = path
lxc_init_interface['vgname'] = vgname
lxc_init_interface['size'] = size
lxc_init_interface['lvname'] = lvname
lxc_init_interface['thinpool'] = thinpool
lxc_init_interface['force_install'] = force_install
lxc_init_interface['unconditional_install'] = (
unconditional_install
)
lxc_init_interface['bootstrap_url'] = script
lxc_init_interface['bootstrap_args'] = script_args
lxc_init_interface['bootstrap_shell'] = _cloud_get('bootstrap_shell', 'sh')
lxc_init_interface['bootstrap_delay'] = _cloud_get('bootstrap_delay', None)
lxc_init_interface['autostart'] = autostart
lxc_init_interface['users'] = users
lxc_init_interface['password'] = password
lxc_init_interface['password_encrypted'] = password_encrypted
# be sure not to let objects goes inside the return
# as this return will be msgpacked for use in the runner !
lxc_init_interface['network_profile'] = network_profile
for i in ['cpu', 'cpuset', 'cpushare']:
if _cloud_get(i, None):
try:
lxc_init_interface[i] = vm_[i]
except KeyError:
lxc_init_interface[i] = profile[i]
return lxc_init_interface
def _get_profile(key, name, **kwargs):
if isinstance(name, dict):
profilename = name.pop('name', None)
return _get_profile(key, profilename, **name)
if name is None:
profile_match = {}
else:
profile_match = \
__salt__['config.get'](
'lxc.{1}:{0}'.format(name, key),
default=None,
merge='recurse'
)
if profile_match is None:
# No matching profile, make the profile an empty dict so that
# overrides can be applied below.
profile_match = {}
if not isinstance(profile_match, dict):
raise CommandExecutionError('lxc.{0} must be a dictionary'.format(key))
# Overlay the kwargs to override matched profile data
overrides = salt.utils.args.clean_kwargs(**copy.deepcopy(kwargs))
profile_match = salt.utils.dictupdate.update(
copy.deepcopy(profile_match),
overrides
)
return profile_match
def get_container_profile(name=None, **kwargs):
'''
.. versionadded:: 2015.5.0
Gather a pre-configured set of container configuration parameters. If no
arguments are passed, an empty profile is returned.
Profiles can be defined in the minion or master config files, or in pillar
or grains, and are loaded using :mod:`config.get
<salt.modules.config.get>`. The key under which LXC profiles must be
configured is ``lxc.container_profile.profile_name``. An example container
profile would be as follows:
.. code-block:: yaml
lxc.container_profile:
ubuntu:
template: ubuntu
backing: lvm
vgname: lxc
size: 1G
Parameters set in a profile can be overridden by passing additional
container creation arguments (such as the ones passed to :mod:`lxc.create
<salt.modules.lxc.create>`) to this function.
A profile can be defined either as the name of the profile, or a dictionary
of variable names and values. See the :ref:`LXC Tutorial
<tutorial-lxc-profiles>` for more information on how to use LXC profiles.
CLI Example:
.. code-block:: bash
salt-call lxc.get_container_profile centos
salt-call lxc.get_container_profile ubuntu template=ubuntu backing=overlayfs
'''
profile = _get_profile('container_profile', name, **kwargs)
return profile
def get_network_profile(name=None, **kwargs):
'''
.. versionadded:: 2015.5.0
Gather a pre-configured set of network configuration parameters. If no
arguments are passed, the following default profile is returned:
.. code-block:: python
{'eth0': {'link': 'br0', 'type': 'veth', 'flags': 'up'}}
Profiles can be defined in the minion or master config files, or in pillar
or grains, and are loaded using :mod:`config.get
<salt.modules.config.get>`. The key under which LXC profiles must be
configured is ``lxc.network_profile``. An example network profile would be
as follows:
.. code-block:: yaml
lxc.network_profile.centos:
eth0:
link: br0
type: veth
flags: up
To disable networking entirely:
.. code-block:: yaml
lxc.network_profile.centos:
eth0:
disable: true
Parameters set in a profile can be overridden by passing additional
arguments to this function.
A profile can be passed either as the name of the profile, or a
dictionary of variable names and values. See the :ref:`LXC Tutorial
<tutorial-lxc-profiles>` for more information on how to use network
profiles.
.. warning::
The ``ipv4``, ``ipv6``, ``gateway``, and ``link`` (bridge) settings in
network profiles will only work if the container doesn't redefine the
network configuration (for example in
``/etc/sysconfig/network-scripts/ifcfg-<interface_name>`` on
RHEL/CentOS, or ``/etc/network/interfaces`` on Debian/Ubuntu/etc.)
CLI Example:
.. code-block:: bash
salt-call lxc.get_network_profile default
'''
profile = _get_profile('network_profile', name, **kwargs)
return profile
def _rand_cpu_str(cpu):
'''
Return a random subset of cpus for the cpuset config
'''
cpu = int(cpu)
avail = __salt__['status.nproc']()
if cpu < avail:
return '0-{0}'.format(avail)
to_set = set()
while len(to_set) < cpu:
choice = random.randint(0, avail - 1)
if choice not in to_set:
to_set.add(six.text_type(choice))
return ','.join(sorted(to_set))
def _network_conf(conf_tuples=None, **kwargs):
'''
Network configuration defaults
network_profile
as for containers, we can either call this function
either with a network_profile dict or network profile name
in the kwargs
nic_opts
overrides or extra nics in the form {nic_name: {set: tings}
'''
nic = kwargs.get('network_profile', None)
ret = []
nic_opts = kwargs.get('nic_opts', {})
if nic_opts is None:
# coming from elsewhere
nic_opts = {}
if not conf_tuples:
conf_tuples = []
old = _get_veths(conf_tuples)
if not old:
old = {}
# if we have a profile name, get the profile and load the network settings
# this will obviously by default look for a profile called "eth0"
# or by what is defined in nic_opts
# and complete each nic settings by sane defaults
if nic and isinstance(nic, (six.string_types, dict)):
nicp = get_network_profile(nic)
else:
nicp = {}
if DEFAULT_NIC not in nicp:
nicp[DEFAULT_NIC] = {}
kwargs = copy.deepcopy(kwargs)
gateway = kwargs.pop('gateway', None)
bridge = kwargs.get('bridge', None)
if nic_opts:
for dev, args in six.iteritems(nic_opts):
ethx = nicp.setdefault(dev, {})
try:
ethx = salt.utils.dictupdate.update(ethx, args)
except AttributeError:
raise SaltInvocationError('Invalid nic_opts configuration')
ifs = [a for a in nicp]
ifs += [a for a in old if a not in nicp]
ifs.sort()
gateway_set = False
for dev in ifs:
args = nicp.get(dev, {})
opts = nic_opts.get(dev, {}) if nic_opts else {}
old_if = old.get(dev, {})
disable = opts.get('disable', args.get('disable', False))
if disable:
continue
mac = opts.get('mac',
opts.get('hwaddr',
args.get('mac',
args.get('hwaddr', ''))))
type_ = opts.get('type', args.get('type', ''))
flags = opts.get('flags', args.get('flags', ''))
link = opts.get('link', args.get('link', ''))
ipv4 = opts.get('ipv4', args.get('ipv4', ''))
ipv6 = opts.get('ipv6', args.get('ipv6', ''))
infos = salt.utils.odict.OrderedDict([
('lxc.network.type', {
'test': not type_,
'value': type_,
'old': old_if.get('lxc.network.type'),
'default': 'veth'}),
('lxc.network.name', {
'test': False,
'value': dev,
'old': dev,
'default': dev}),
('lxc.network.flags', {
'test': not flags,
'value': flags,
'old': old_if.get('lxc.network.flags'),
'default': 'up'}),
('lxc.network.link', {
'test': not link,
'value': link,
'old': old_if.get('lxc.network.link'),
'default': search_lxc_bridge()}),
('lxc.network.hwaddr', {
'test': not mac,
'value': mac,
'old': old_if.get('lxc.network.hwaddr'),
'default': salt.utils.network.gen_mac()}),
('lxc.network.ipv4', {
'test': not ipv4,
'value': ipv4,
'old': old_if.get('lxc.network.ipv4', ''),
'default': None}),
('lxc.network.ipv6', {
'test': not ipv6,
'value': ipv6,
'old': old_if.get('lxc.network.ipv6', ''),
'default': None})])
# for each parameter, if not explicitly set, the
# config value present in the LXC configuration should
# take precedence over the profile configuration
for info in list(infos.keys()):
bundle = infos[info]
if bundle['test']:
if bundle['old']:
bundle['value'] = bundle['old']
elif bundle['default']:
bundle['value'] = bundle['default']
for info, data in six.iteritems(infos):
if data['value']:
ret.append({info: data['value']})
for key, val in six.iteritems(args):
if key == 'link' and bridge:
val = bridge
val = opts.get(key, val)
if key in [
'type', 'flags', 'name',
'gateway', 'mac', 'link', 'ipv4', 'ipv6'
]:
continue
ret.append({'lxc.network.{0}'.format(key): val})
# gateway (in automode) must be appended following network conf !
if not gateway:
gateway = args.get('gateway', None)
if gateway is not None and not gateway_set:
ret.append({'lxc.network.ipv4.gateway': gateway})
# only one network gateway ;)
gateway_set = True
# normally, this won't happen
# set the gateway if specified even if we did
# not managed the network underlying
if gateway is not None and not gateway_set:
ret.append({'lxc.network.ipv4.gateway': gateway})
# only one network gateway ;)
gateway_set = True
new = _get_veths(ret)
# verify that we did not loose the mac settings
for iface in [a for a in new]:
ndata = new[iface]
nmac = ndata.get('lxc.network.hwaddr', '')
ntype = ndata.get('lxc.network.type', '')
omac, otype = '', ''
if iface in old:
odata = old[iface]
omac = odata.get('lxc.network.hwaddr', '')
otype = odata.get('lxc.network.type', '')
# default for network type is setted here
# attention not to change the network type
# without a good and explicit reason to.
if otype and not ntype:
ntype = otype
if not ntype:
ntype = 'veth'
new[iface]['lxc.network.type'] = ntype
if omac and not nmac:
new[iface]['lxc.network.hwaddr'] = omac
ret = []
for val in six.itervalues(new):
for row in val:
ret.append(salt.utils.odict.OrderedDict([(row, val[row])]))
# on old versions of lxc, still support the gateway auto mode
# if we didn't explicitly say no to
# (lxc.network.ipv4.gateway: auto)
if _LooseVersion(version()) <= _LooseVersion('1.0.7') and \
True not in ['lxc.network.ipv4.gateway' in a for a in ret] and \
True in ['lxc.network.ipv4' in a for a in ret]:
ret.append({'lxc.network.ipv4.gateway': 'auto'})
return ret
def _get_lxc_default_data(**kwargs):
kwargs = copy.deepcopy(kwargs)
ret = {}
for k in ['utsname', 'rootfs']:
val = kwargs.get(k, None)
if val is not None:
ret['lxc.{0}'.format(k)] = val
autostart = kwargs.get('autostart')
# autostart can have made in kwargs, but with the None
# value which is invalid, we need an explicit boolean
# autostart = on is the default.
if autostart is None:
autostart = True
# we will set the regular lxc marker to restart container at
# machine (re)boot only if we did not explicitly ask
# not to touch to the autostart settings via
# autostart == 'keep'
if autostart != 'keep':
if autostart:
ret['lxc.start.auto'] = '1'
else:
ret['lxc.start.auto'] = '0'
memory = kwargs.get('memory')
if memory is not None:
# converting the config value from MB to bytes
ret['lxc.cgroup.memory.limit_in_bytes'] = memory * 1024 * 1024
cpuset = kwargs.get('cpuset')
if cpuset:
ret['lxc.cgroup.cpuset.cpus'] = cpuset
cpushare = kwargs.get('cpushare')
cpu = kwargs.get('cpu')
if cpushare:
ret['lxc.cgroup.cpu.shares'] = cpushare
if cpu and not cpuset:
ret['lxc.cgroup.cpuset.cpus'] = _rand_cpu_str(cpu)
return ret
def _config_list(conf_tuples=None, only_net=False, **kwargs):
'''
Return a list of dicts from the salt level configurations
conf_tuples
_LXCConfig compatible list of entries which can contain
- string line
- tuple (lxc config param,value)
- dict of one entry: {lxc config param: value)
only_net
by default we add to the tuples a reflection of both
the real config if avalaible and a certain amount of
default values like the cpu parameters, the memory
and etc.
On the other hand, we also no matter the case reflect
the network configuration computed from the actual config if
available and given values.
if no_default_loads is set, we will only
reflect the network configuration back to the conf tuples
list
'''
# explicit cast
only_net = bool(only_net)
if not conf_tuples:
conf_tuples = []
kwargs = copy.deepcopy(kwargs)
ret = []
if not only_net:
default_data = _get_lxc_default_data(**kwargs)
for k, val in six.iteritems(default_data):
ret.append({k: val})
net_datas = _network_conf(conf_tuples=conf_tuples, **kwargs)
ret.extend(net_datas)
return ret
def _get_veths(net_data):
'''
Parse the nic setup inside lxc conf tuples back to a dictionary indexed by
network interface
'''
if isinstance(net_data, dict):
net_data = list(net_data.items())
nics = salt.utils.odict.OrderedDict()
current_nic = salt.utils.odict.OrderedDict()
no_names = True
for item in net_data:
if item and isinstance(item, dict):
item = list(item.items())[0]
# skip LXC configuration comment lines, and play only with tuples conf
elif isinstance(item, six.string_types):
# deal with reflection of commented lxc configs
sitem = item.strip()
if sitem.startswith('#') or not sitem:
continue
elif '=' in item:
item = tuple([a.strip() for a in item.split('=', 1)])
if item[0] == 'lxc.network.type':
current_nic = salt.utils.odict.OrderedDict()
if item[0] == 'lxc.network.name':
no_names = False
nics[item[1].strip()] = current_nic
current_nic[item[0].strip()] = item[1].strip()
# if not ethernet card name has been collected, assuming we collected
# data for eth0
if no_names and current_nic:
nics[DEFAULT_NIC] = current_nic
return nics
class _LXCConfig(object):
'''
LXC configuration data
'''
pattern = re.compile(r'^(\S+)(\s*)(=)(\s*)(.*)')
non_interpretable_pattern = re.compile(r'^((#.*)|(\s*))$')
def __init__(self, **kwargs):
kwargs = copy.deepcopy(kwargs)
self.name = kwargs.pop('name', None)
path = get_root_path(kwargs.get('path', None))
self.data = []
if self.name:
self.path = os.path.join(path, self.name, 'config')
if os.path.isfile(self.path):
with salt.utils.files.fopen(self.path) as fhr:
for line in salt.utils.data.decode(fhr.readlines()):
match = self.pattern.findall((line.strip()))
if match:
self.data.append((match[0][0], match[0][-1]))
match = self.non_interpretable_pattern.findall(
(line.strip()))
if match:
self.data.append(('', match[0][0]))
else:
self.path = None
def _replace(key, val):
if val:
self._filter_data(key)
self.data.append((key, val))
default_data = _get_lxc_default_data(**kwargs)
for key, val in six.iteritems(default_data):
_replace(key, val)
old_net = self._filter_data('lxc.network')
net_datas = _network_conf(conf_tuples=old_net, **kwargs)
if net_datas:
for row in net_datas:
self.data.extend(list(row.items()))
# be sure to reset harmful settings
for idx in ['lxc.cgroup.memory.limit_in_bytes']:
if not default_data.get(idx):
self._filter_data(idx)
def as_string(self):
chunks = ('{0[0]}{1}{0[1]}'.format(item, (' = ' if item[0] else '')) for item in self.data)
return '\n'.join(chunks) + '\n'
def write(self):
if self.path:
content = self.as_string()
# 2 step rendering to be sure not to open/wipe the config
# before as_string succeeds.
with salt.utils.files.fopen(self.path, 'w') as fic:
fic.write(salt.utils.stringutils.to_str(content))
fic.flush()
def tempfile(self):
# this might look like the function name is shadowing the
# module, but it's not since the method belongs to the class
ntf = tempfile.NamedTemporaryFile()
ntf.write(self.as_string())
ntf.flush()
return ntf
def _filter_data(self, pattern):
'''
Removes parameters which match the pattern from the config data
'''
removed = []
filtered = []
for param in self.data:
if not param[0].startswith(pattern):
filtered.append(param)
else:
removed.append(param)
self.data = filtered
return removed
def _get_base(**kwargs):
'''
If the needed base does not exist, then create it, if it does exist
create nothing and return the name of the base lxc container so
it can be cloned.
'''
profile = get_container_profile(copy.deepcopy(kwargs.get('profile')))
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, _marker)
profile_match = profile.pop(key, default)
# let kwarg overrides be the preferred choice
if kw_overrides_match is _marker:
return profile_match
return kw_overrides_match
template = select('template')
image = select('image')
vgname = select('vgname')
path = kwargs.get('path', None)
# remove the above three variables from kwargs, if they exist, to avoid
# duplicates if create() is invoked below.
for param in ('path', 'image', 'vgname', 'template'):
kwargs.pop(param, None)
if image:
proto = _urlparse(image).scheme
img_tar = __salt__['cp.cache_file'](image)
img_name = os.path.basename(img_tar)
hash_ = salt.utils.hashutils.get_hash(
img_tar,
__salt__['config.get']('hash_type'))
name = '__base_{0}_{1}_{2}'.format(proto, img_name, hash_)
if not exists(name, path=path):
create(name, template=template, image=image,
path=path, vgname=vgname, **kwargs)
if vgname:
rootfs = os.path.join('/dev', vgname, name)
edit_conf(info(name, path=path)['config'],
out_format='commented', **{'lxc.rootfs': rootfs})
return name
elif template:
name = '__base_{0}'.format(template)
if not exists(name, path=path):
create(name, template=template, image=image, path=path,
vgname=vgname, **kwargs)
if vgname:
rootfs = os.path.join('/dev', vgname, name)
edit_conf(info(name, path=path)['config'],
out_format='commented', **{'lxc.rootfs': rootfs})
return name
return ''
def init(name,
config=None,
cpuset=None,
cpushare=None,
memory=None,
profile=None,
network_profile=None,
nic_opts=None,
cpu=None,
autostart=True,
password=None,
password_encrypted=None,
users=None,
dnsservers=None,
searchdomains=None,
bridge=None,
gateway=None,
pub_key=None,
priv_key=None,
force_install=False,
unconditional_install=False,
bootstrap_delay=None,
bootstrap_args=None,
bootstrap_shell=None,
bootstrap_url=None,
**kwargs):
'''
Initialize a new container.
This is a partial idempotent function as if it is already provisioned, we
will reset a bit the lxc configuration file but much of the hard work will
be escaped as markers will prevent re-execution of harmful tasks.
name
Name of the container
image
A tar archive to use as the rootfs for the container. Conflicts with
the ``template`` argument.
cpus
Select a random number of cpu cores and assign it to the cpuset, if the
cpuset option is set then this option will be ignored
cpuset
Explicitly define the cpus this container will be bound to
cpushare
cgroups cpu shares
autostart
autostart container on reboot
memory
cgroups memory limit, in MB
.. versionchanged:: 2015.5.0
If no value is passed, no limit is set. In earlier Salt versions,
not passing this value causes a 1024MB memory limit to be set, and
it was necessary to pass ``memory=0`` to set no limit.
gateway
the ipv4 gateway to use
the default does nothing more than lxcutils does
bridge
the bridge to use
the default does nothing more than lxcutils does
network_profile
Network profile to use for the container
.. versionadded:: 2015.5.0
nic_opts
Extra options for network interfaces, will override
``{"eth0": {"hwaddr": "aa:bb:cc:dd:ee:ff", "ipv4": "10.1.1.1", "ipv6": "2001:db8::ff00:42:8329"}}``
or
``{"eth0": {"hwaddr": "aa:bb:cc:dd:ee:ff", "ipv4": "10.1.1.1/24", "ipv6": "2001:db8::ff00:42:8329"}}``
users
Users for which the password defined in the ``password`` param should
be set. Can be passed as a comma separated list or a python list.
Defaults to just the ``root`` user.
password
Set the initial password for the users defined in the ``users``
parameter
password_encrypted : False
Set to ``True`` to denote a password hash instead of a plaintext
password
.. versionadded:: 2015.5.0
profile
A LXC profile (defined in config or pillar).
This can be either a real profile mapping or a string
to retrieve it in configuration
start
Start the newly-created container
dnsservers
list of dns servers to set in the container, default [] (no setting)
seed
Seed the container with the minion config. Default: ``True``
install
If salt-minion is not already installed, install it. Default: ``True``
config
Optional config parameters. By default, the id is set to
the name of the container.
master
salt master (default to minion's master)
master_port
salt master port (default to minion's master port)
pub_key
Explicit public key to preseed the minion with (optional).
This can be either a filepath or a string representing the key
priv_key
Explicit private key to preseed the minion with (optional).
This can be either a filepath or a string representing the key
approve_key
If explicit preseeding is not used;
Attempt to request key approval from the master. Default: ``True``
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
clone_from
Original from which to use a clone operation to create the container.
Default: ``None``
bootstrap_delay
Delay in seconds between end of container creation and bootstrapping.
Useful when waiting for container to obtain a DHCP lease.
.. versionadded:: 2015.5.0
bootstrap_url
See lxc.bootstrap
bootstrap_shell
See lxc.bootstrap
bootstrap_args
See lxc.bootstrap
force_install
Force installation even if salt-minion is detected,
this is the way to run vendor bootstrap scripts even
if a salt minion is already present in the container
unconditional_install
Run the script even if the container seems seeded
CLI Example:
.. code-block:: bash
salt 'minion' lxc.init name [cpuset=cgroups_cpuset] \\
[cpushare=cgroups_cpushare] [memory=cgroups_memory] \\
[nic=nic_profile] [profile=lxc_profile] \\
[nic_opts=nic_opts] [start=(True|False)] \\
[seed=(True|False)] [install=(True|False)] \\
[config=minion_config] [approve_key=(True|False) \\
[clone_from=original] [autostart=True] \\
[priv_key=/path_or_content] [pub_key=/path_or_content] \\
[bridge=lxcbr0] [gateway=10.0.3.1] \\
[dnsservers[dns1,dns2]] \\
[users=[foo]] [password='secret'] \\
[password_encrypted=(True|False)]
'''
ret = {'name': name,
'changes': {}}
profile = get_container_profile(copy.deepcopy(profile))
if not network_profile:
network_profile = profile.get('network_profile')
if not network_profile:
network_profile = DEFAULT_NIC
# Changes is a pointer to changes_dict['init']. This method is used so that
# we can have a list of changes as they are made, providing an ordered list
# of things that were changed.
changes_dict = {'init': []}
changes = changes_dict.get('init')
if users is None:
users = []
dusers = ['root']
for user in dusers:
if user not in users:
users.append(user)
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, _marker)
profile_match = profile.pop(key, default)
# let kwarg overrides be the preferred choice
if kw_overrides_match is _marker:
return profile_match
return kw_overrides_match
path = select('path')
bpath = get_root_path(path)
state_pre = state(name, path=path)
tvg = select('vgname')
vgname = tvg if tvg else __salt__['config.get']('lxc.vgname')
start_ = select('start', True)
autostart = select('autostart', autostart)
seed = select('seed', True)
install = select('install', True)
seed_cmd = select('seed_cmd')
salt_config = _get_salt_config(config, **kwargs)
approve_key = select('approve_key', True)
clone_from = select('clone_from')
# If using a volume group then set up to make snapshot cow clones
if vgname and not clone_from:
try:
kwargs['vgname'] = vgname
clone_from = _get_base(profile=profile, **kwargs)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = exc.strerror
if changes:
ret['changes'] = changes_dict
return ret
if not kwargs.get('snapshot') is False:
kwargs['snapshot'] = True
does_exist = exists(name, path=path)
to_reboot = False
remove_seed_marker = False
if does_exist:
pass
elif clone_from:
remove_seed_marker = True
try:
clone(name, clone_from, profile=profile, **kwargs)
changes.append({'create': 'Container cloned'})
except (SaltInvocationError, CommandExecutionError) as exc:
if 'already exists' in exc.strerror:
changes.append({'create': 'Container already exists'})
else:
ret['result'] = False
ret['comment'] = exc.strerror
if changes:
ret['changes'] = changes_dict
return ret
cfg = _LXCConfig(name=name, network_profile=network_profile,
nic_opts=nic_opts, bridge=bridge, path=path,
gateway=gateway, autostart=autostart,
cpuset=cpuset, cpushare=cpushare, memory=memory)
old_chunks = read_conf(cfg.path, out_format='commented')
cfg.write()
chunks = read_conf(cfg.path, out_format='commented')
if old_chunks != chunks:
to_reboot = True
else:
remove_seed_marker = True
cfg = _LXCConfig(network_profile=network_profile,
nic_opts=nic_opts, cpuset=cpuset, path=path,
bridge=bridge, gateway=gateway,
autostart=autostart,
cpushare=cpushare, memory=memory)
with cfg.tempfile() as cfile:
try:
create(name, config=cfile.name, profile=profile, **kwargs)
changes.append({'create': 'Container created'})
except (SaltInvocationError, CommandExecutionError) as exc:
if 'already exists' in exc.strerror:
changes.append({'create': 'Container already exists'})
else:
ret['comment'] = exc.strerror
if changes:
ret['changes'] = changes_dict
return ret
cpath = os.path.join(bpath, name, 'config')
old_chunks = []
if os.path.exists(cpath):
old_chunks = read_conf(cpath, out_format='commented')
new_cfg = _config_list(conf_tuples=old_chunks,
cpu=cpu,
network_profile=network_profile,
nic_opts=nic_opts, bridge=bridge,
cpuset=cpuset, cpushare=cpushare,
memory=memory)
if new_cfg:
edit_conf(cpath, out_format='commented', lxc_config=new_cfg)
chunks = read_conf(cpath, out_format='commented')
if old_chunks != chunks:
to_reboot = True
# last time to be sure any of our property is correctly applied
cfg = _LXCConfig(name=name, network_profile=network_profile,
nic_opts=nic_opts, bridge=bridge, path=path,
gateway=gateway, autostart=autostart,
cpuset=cpuset, cpushare=cpushare, memory=memory)
old_chunks = []
if os.path.exists(cfg.path):
old_chunks = read_conf(cfg.path, out_format='commented')
cfg.write()
chunks = read_conf(cfg.path, out_format='commented')
if old_chunks != chunks:
changes.append({'config': 'Container configuration updated'})
to_reboot = True
if to_reboot:
try:
stop(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
if changes:
ret['changes'] = changes_dict
return ret
if not does_exist or (does_exist and state(name, path=path) != 'running'):
try:
start(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
if changes:
ret['changes'] = changes_dict
return ret
if remove_seed_marker:
run(name,
'rm -f \'{0}\''.format(SEED_MARKER),
path=path,
chroot_fallback=False,
python_shell=False)
# set the default user/password, only the first time
if ret.get('result', True) and password:
gid = '/.lxc.initial_pass'
gids = [gid,
'/lxc.initial_pass',
'/.lxc.{0}.initial_pass'.format(name)]
if not any(retcode(name,
'test -e "{0}"'.format(x),
chroot_fallback=True,
path=path,
ignore_retcode=True) == 0
for x in gids):
# think to touch the default user generated by default templates
# which has a really unsecure passwords...
# root is defined as a member earlier in the code
for default_user in ['ubuntu']:
if (
default_user not in users and
retcode(name,
'id {0}'.format(default_user),
python_shell=False,
path=path,
chroot_fallback=True,
ignore_retcode=True) == 0
):
users.append(default_user)
for user in users:
try:
cret = set_password(name,
users=[user],
path=path,
password=password,
encrypted=password_encrypted)
except (SaltInvocationError, CommandExecutionError) as exc:
msg = '{0}: Failed to set password'.format(
user) + exc.strerror
# only hardfail in unrecoverable situation:
# root cannot be setted up
if user == 'root':
ret['comment'] = msg
ret['result'] = False
else:
log.debug(msg)
if ret.get('result', True):
changes.append({'password': 'Password(s) updated'})
if retcode(name,
('sh -c \'touch "{0}"; test -e "{0}"\''
.format(gid)),
path=path,
chroot_fallback=True,
ignore_retcode=True) != 0:
ret['comment'] = 'Failed to set password marker'
changes[-1]['password'] += '. ' + ret['comment'] + '.'
ret['result'] = False
# set dns servers if any, only the first time
if ret.get('result', True) and dnsservers:
# retro compatibility, test also old markers
gid = '/.lxc.initial_dns'
gids = [gid,
'/lxc.initial_dns',
'/lxc.{0}.initial_dns'.format(name)]
if not any(retcode(name,
'test -e "{0}"'.format(x),
chroot_fallback=True,
path=path,
ignore_retcode=True) == 0
for x in gids):
try:
set_dns(name,
path=path,
dnsservers=dnsservers,
searchdomains=searchdomains)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Failed to set DNS: ' + exc.strerror
ret['result'] = False
else:
changes.append({'dns': 'DNS updated'})
if retcode(name,
('sh -c \'touch "{0}"; test -e "{0}"\''
.format(gid)),
chroot_fallback=True,
path=path,
ignore_retcode=True) != 0:
ret['comment'] = 'Failed to set DNS marker'
changes[-1]['dns'] += '. ' + ret['comment'] + '.'
ret['result'] = False
# retro compatibility, test also old markers
if remove_seed_marker:
run(name,
'rm -f \'{0}\''.format(SEED_MARKER),
path=path,
python_shell=False)
gid = '/.lxc.initial_seed'
gids = [gid, '/lxc.initial_seed']
if (
any(retcode(name,
'test -e {0}'.format(x),
path=path,
chroot_fallback=True,
ignore_retcode=True) == 0
for x in gids) or not ret.get('result', True)
):
pass
elif seed or seed_cmd:
if seed:
try:
result = bootstrap(
name, config=salt_config, path=path,
approve_key=approve_key,
pub_key=pub_key, priv_key=priv_key,
install=install,
force_install=force_install,
unconditional_install=unconditional_install,
bootstrap_delay=bootstrap_delay,
bootstrap_url=bootstrap_url,
bootstrap_shell=bootstrap_shell,
bootstrap_args=bootstrap_args)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Bootstrap failed: ' + exc.strerror
ret['result'] = False
else:
if not result:
ret['comment'] = ('Bootstrap failed, see minion log for '
'more information')
ret['result'] = False
else:
changes.append(
{'bootstrap': 'Container successfully bootstrapped'}
)
elif seed_cmd:
try:
result = __salt__[seed_cmd](info(name, path=path)['rootfs'],
name,
salt_config)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = ('Bootstrap via seed_cmd \'{0}\' failed: {1}'
.format(seed_cmd, exc.strerror))
ret['result'] = False
else:
if not result:
ret['comment'] = ('Bootstrap via seed_cmd \'{0}\' failed, '
'see minion log for more information '
.format(seed_cmd))
ret['result'] = False
else:
changes.append(
{'bootstrap': 'Container successfully bootstrapped '
'using seed_cmd \'{0}\''
.format(seed_cmd)}
)
if ret.get('result', True) and not start_:
try:
stop(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
ret['result'] = False
state_post = state(name, path=path)
if state_pre != state_post:
changes.append({'state': {'old': state_pre, 'new': state_post}})
if ret.get('result', True):
ret['comment'] = ('Container \'{0}\' successfully initialized'
.format(name))
ret['result'] = True
if changes:
ret['changes'] = changes_dict
return ret
def cloud_init(name, vm_=None, **kwargs):
'''
Thin wrapper to lxc.init to be used from the saltcloud lxc driver
name
Name of the container
may be None and then guessed from saltcloud mapping
`vm_`
saltcloud mapping defaults for the vm
CLI Example:
.. code-block:: bash
salt '*' lxc.cloud_init foo
'''
init_interface = cloud_init_interface(name, vm_, **kwargs)
name = init_interface.pop('name', name)
return init(name, **init_interface)
def images(dist=None):
'''
.. versionadded:: 2015.5.0
List the available images for LXC's ``download`` template.
dist : None
Filter results to a single Linux distribution
CLI Examples:
.. code-block:: bash
salt myminion lxc.images
salt myminion lxc.images dist=centos
'''
out = __salt__['cmd.run_stdout'](
'lxc-create -n __imgcheck -t download -- --list',
ignore_retcode=True
)
if 'DIST' not in out:
raise CommandExecutionError(
'Unable to run the \'download\' template script. Is it installed?'
)
ret = {}
passed_header = False
for line in out.splitlines():
try:
distro, release, arch, variant, build_time = line.split()
except ValueError:
continue
if not passed_header:
if distro == 'DIST':
passed_header = True
continue
dist_list = ret.setdefault(distro, [])
dist_list.append({
'release': release,
'arch': arch,
'variant': variant,
'build_time': build_time,
})
if dist is not None:
return dict([(dist, ret.get(dist, []))])
return ret
def templates():
'''
.. versionadded:: 2015.5.0
List the available LXC template scripts installed on the minion
CLI Examples:
.. code-block:: bash
salt myminion lxc.templates
'''
try:
template_scripts = os.listdir('/usr/share/lxc/templates')
except OSError:
return []
else:
return [x[4:] for x in template_scripts if x.startswith('lxc-')]
def _after_ignition_network_profile(cmd,
ret,
name,
network_profile,
path,
nic_opts):
_clear_context()
if ret['retcode'] == 0 and exists(name, path=path):
if network_profile:
network_changes = apply_network_profile(name,
network_profile,
path=path,
nic_opts=nic_opts)
if network_changes:
log.info(
'Network changes from applying network profile \'%s\' '
'to newly-created container \'%s\':\n%s',
network_profile, name, network_changes
)
c_state = state(name, path=path)
return {'result': True,
'state': {'old': None, 'new': c_state}}
else:
if exists(name, path=path):
# destroy the container if it was partially created
cmd = 'lxc-destroy'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0}'.format(name)
__salt__['cmd.retcode'](cmd, python_shell=False)
raise CommandExecutionError(
'Container could not be created with cmd \'{0}\': {1}'
.format(cmd, ret['stderr'])
)
def create(name,
config=None,
profile=None,
network_profile=None,
nic_opts=None,
**kwargs):
'''
Create a new container.
name
Name of the container
config
The config file to use for the container. Defaults to system-wide
config (usually in /etc/lxc/lxc.conf).
profile
Profile to use in container creation (see
:mod:`lxc.get_container_profile
<salt.modules.lxc.get_container_profile>`). Values in a profile will be
overridden by the **Container Creation Arguments** listed below.
network_profile
Network profile to use for container
.. versionadded:: 2015.5.0
**Container Creation Arguments**
template
The template to use. For example, ``ubuntu`` or ``fedora``.
For a full list of available templates, check out
the :mod:`lxc.templates <salt.modules.lxc.templates>` function.
Conflicts with the ``image`` argument.
.. note::
The ``download`` template requires the following three parameters
to be defined in ``options``:
* **dist** - The name of the distribution
* **release** - Release name/version
* **arch** - Architecture of the container
The available images can be listed using the :mod:`lxc.images
<salt.modules.lxc.images>` function.
options
Template-specific options to pass to the lxc-create command. These
correspond to the long options (ones beginning with two dashes) that
the template script accepts. For example:
.. code-block:: bash
options='{"dist": "centos", "release": "6", "arch": "amd64"}'
For available template options, refer to the lxc template scripts
which are ususally located under ``/usr/share/lxc/templates``,
or run ``lxc-create -t <template> -h``.
image
A tar archive to use as the rootfs for the container. Conflicts with
the ``template`` argument.
backing
The type of storage to use. Set to ``lvm`` to use an LVM group.
Defaults to filesystem within /var/lib/lxc.
fstype
Filesystem type to use on LVM logical volume
size : 1G
Size of the volume to create. Only applicable if ``backing=lvm``.
vgname : lxc
Name of the LVM volume group in which to create the volume for this
container. Only applicable if ``backing=lvm``.
lvname
Name of the LVM logical volume in which to create the volume for this
container. Only applicable if ``backing=lvm``.
thinpool
Name of a pool volume that will be used for thin-provisioning this
container. Only applicable if ``backing=lvm``.
nic_opts
give extra opts overriding network profile values
path
parent path for the container creation (default: /var/lib/lxc)
zfsroot
Name of the ZFS root in which to create the volume for this container.
Only applicable if ``backing=zfs``. (default: tank/lxc)
.. versionadded:: 2015.8.0
'''
# Required params for 'download' template
download_template_deps = ('dist', 'release', 'arch')
cmd = 'lxc-create -n {0}'.format(name)
profile = get_container_profile(copy.deepcopy(profile))
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, None)
profile_match = profile.pop(key, default)
# Return the profile match if the the kwarg match was None, as the
# lxc.present state will pass these kwargs set to None by default.
if kw_overrides_match is None:
return profile_match
return kw_overrides_match
path = select('path')
if exists(name, path=path):
raise CommandExecutionError(
'Container \'{0}\' already exists'.format(name)
)
tvg = select('vgname')
vgname = tvg if tvg else __salt__['config.get']('lxc.vgname')
# The 'template' and 'image' params conflict
template = select('template')
image = select('image')
if template and image:
raise SaltInvocationError(
'Only one of \'template\' and \'image\' is permitted'
)
elif not any((template, image, profile)):
raise SaltInvocationError(
'At least one of \'template\', \'image\', and \'profile\' is '
'required'
)
options = select('options') or {}
backing = select('backing')
if vgname and not backing:
backing = 'lvm'
lvname = select('lvname')
thinpool = select('thinpool')
fstype = select('fstype')
size = select('size', '1G')
zfsroot = select('zfsroot')
if backing in ('dir', 'overlayfs', 'btrfs', 'zfs'):
fstype = None
size = None
# some backends won't support some parameters
if backing in ('aufs', 'dir', 'overlayfs', 'btrfs'):
lvname = vgname = thinpool = None
if image:
img_tar = __salt__['cp.cache_file'](image)
template = os.path.join(
os.path.dirname(salt.__file__),
'templates',
'lxc',
'salt_tarball')
options['imgtar'] = img_tar
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
if not os.path.exists(path):
os.makedirs(path)
if config:
cmd += ' -f {0}'.format(config)
if template:
cmd += ' -t {0}'.format(template)
if backing:
backing = backing.lower()
cmd += ' -B {0}'.format(backing)
if backing in ('zfs',):
if zfsroot:
cmd += ' --zfsroot {0}'.format(zfsroot)
if backing in ('lvm',):
if lvname:
cmd += ' --lvname {0}'.format(lvname)
if vgname:
cmd += ' --vgname {0}'.format(vgname)
if thinpool:
cmd += ' --thinpool {0}'.format(thinpool)
if backing not in ('dir', 'overlayfs'):
if fstype:
cmd += ' --fstype {0}'.format(fstype)
if size:
cmd += ' --fssize {0}'.format(size)
if options:
if template == 'download':
missing_deps = [x for x in download_template_deps
if x not in options]
if missing_deps:
raise SaltInvocationError(
'Missing params in \'options\' dict: {0}'
.format(', '.join(missing_deps))
)
cmd += ' --'
for key, val in six.iteritems(options):
cmd += ' --{0} {1}'.format(key, val)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
# please do not merge extra conflicting stuff
# inside those two line (ret =, return)
return _after_ignition_network_profile(cmd,
ret,
name,
network_profile,
path,
nic_opts)
def clone(name,
orig,
profile=None,
network_profile=None,
nic_opts=None,
**kwargs):
'''
Create a new container as a clone of another container
name
Name of the container
orig
Name of the original container to be cloned
profile
Profile to use in container cloning (see
:mod:`lxc.get_container_profile
<salt.modules.lxc.get_container_profile>`). Values in a profile will be
overridden by the **Container Cloning Arguments** listed below.
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
**Container Cloning Arguments**
snapshot
Use Copy On Write snapshots (LVM)
size : 1G
Size of the volume to create. Only applicable if ``backing=lvm``.
backing
The type of storage to use. Set to ``lvm`` to use an LVM group.
Defaults to filesystem within /var/lib/lxc.
network_profile
Network profile to use for container
.. versionadded:: 2015.8.0
nic_opts
give extra opts overriding network profile values
.. versionadded:: 2015.8.0
CLI Examples:
.. code-block:: bash
salt '*' lxc.clone myclone orig=orig_container
salt '*' lxc.clone myclone orig=orig_container snapshot=True
'''
profile = get_container_profile(copy.deepcopy(profile))
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, None)
profile_match = profile.pop(key, default)
# let kwarg overrides be the preferred choice
if kw_overrides_match is None:
return profile_match
return kw_overrides_match
path = select('path')
if exists(name, path=path):
raise CommandExecutionError(
'Container \'{0}\' already exists'.format(name)
)
_ensure_exists(orig, path=path)
if state(orig, path=path) != 'stopped':
raise CommandExecutionError(
'Container \'{0}\' must be stopped to be cloned'.format(orig)
)
backing = select('backing')
snapshot = select('snapshot')
if backing in ('dir',):
snapshot = False
if not snapshot:
snapshot = ''
else:
snapshot = '-s'
size = select('size', '1G')
if backing in ('dir', 'overlayfs', 'btrfs'):
size = None
# LXC commands and options changed in 2.0 - CF issue #34086 for details
if _LooseVersion(version()) >= _LooseVersion('2.0'):
# https://linuxcontainers.org/lxc/manpages//man1/lxc-copy.1.html
cmd = 'lxc-copy'
cmd += ' {0} -n {1} -N {2}'.format(snapshot, orig, name)
else:
# https://linuxcontainers.org/lxc/manpages//man1/lxc-clone.1.html
cmd = 'lxc-clone'
cmd += ' {0} -o {1} -n {2}'.format(snapshot, orig, name)
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
if not os.path.exists(path):
os.makedirs(path)
if backing:
backing = backing.lower()
cmd += ' -B {0}'.format(backing)
if backing not in ('dir', 'overlayfs'):
if size:
cmd += ' -L {0}'.format(size)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
# please do not merge extra conflicting stuff
# inside those two line (ret =, return)
return _after_ignition_network_profile(cmd,
ret,
name,
network_profile,
path,
nic_opts)
def ls_(active=None, cache=True, path=None):
'''
Return a list of the containers available on the minion
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
active
If ``True``, return only active (i.e. running) containers
.. versionadded:: 2015.5.0
CLI Example:
.. code-block:: bash
salt '*' lxc.ls
salt '*' lxc.ls active=True
'''
contextvar = 'lxc.ls{0}'.format(path)
if active:
contextvar += '.active'
if cache and (contextvar in __context__):
return __context__[contextvar]
else:
ret = []
cmd = 'lxc-ls'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
if active:
cmd += ' --active'
output = __salt__['cmd.run_stdout'](cmd, python_shell=False)
for line in output.splitlines():
ret.extend(line.split())
__context__[contextvar] = ret
return ret
def list_(extra=False, limit=None, path=None):
'''
List containers classified by state
extra
Also get per-container specific info. This will change the return data.
Instead of returning a list of containers, a dictionary of containers
and each container's output from :mod:`lxc.info
<salt.modules.lxc.info>`.
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
limit
Return output matching a specific state (**frozen**, **running**, or
**stopped**).
.. versionadded:: 2015.5.0
CLI Examples:
.. code-block:: bash
salt '*' lxc.list
salt '*' lxc.list extra=True
salt '*' lxc.list limit=running
'''
ctnrs = ls_(path=path)
if extra:
stopped = {}
frozen = {}
running = {}
else:
stopped = []
frozen = []
running = []
ret = {'running': running,
'stopped': stopped,
'frozen': frozen}
for container in ctnrs:
cmd = 'lxc-info'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0}'.format(container)
c_info = __salt__['cmd.run'](
cmd,
python_shell=False,
output_loglevel='debug'
)
c_state = None
for line in c_info.splitlines():
stat = line.split(':')
if stat[0] in ('State', 'state'):
c_state = stat[1].strip()
break
if not c_state or (limit is not None and c_state.lower() != limit):
continue
if extra:
infos = info(container, path=path)
method = 'update'
value = {container: infos}
else:
method = 'append'
value = container
if c_state == 'STOPPED':
getattr(stopped, method)(value)
continue
if c_state == 'FROZEN':
getattr(frozen, method)(value)
continue
if c_state == 'RUNNING':
getattr(running, method)(value)
continue
if limit is not None:
return ret.get(limit, {} if extra else [])
return ret
def _change_state(cmd,
name,
expected,
stdin=_marker,
stdout=_marker,
stderr=_marker,
with_communicate=_marker,
use_vt=_marker,
path=None):
pre = state(name, path=path)
if pre == expected:
return {'result': True,
'state': {'old': expected, 'new': expected},
'comment': 'Container \'{0}\' already {1}'
.format(name, expected)}
if cmd == 'lxc-destroy':
# Kill the container first
scmd = 'lxc-stop'
if path:
scmd += ' -P {0}'.format(pipes.quote(path))
scmd += ' -k -n {0}'.format(name)
__salt__['cmd.run'](scmd,
python_shell=False)
if path and ' -P ' not in cmd:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0}'.format(name)
# certain lxc commands need to be taken with care (lxc-start)
# as te command itself mess with double forks; we must not
# communicate with it, but just wait for the exit status
pkwargs = {'python_shell': False,
'redirect_stderr': True,
'with_communicate': with_communicate,
'use_vt': use_vt,
'stdin': stdin,
'stdout': stdout}
for i in [a for a in pkwargs]:
val = pkwargs[i]
if val is _marker:
pkwargs.pop(i, None)
_cmdout = __salt__['cmd.run_all'](cmd, **pkwargs)
if _cmdout['retcode'] != 0:
raise CommandExecutionError(
'Error changing state for container \'{0}\' using command '
'\'{1}\': {2}'.format(name, cmd, _cmdout['stdout'])
)
if expected is not None:
# some commands do not wait, so we will
rcmd = 'lxc-wait'
if path:
rcmd += ' -P {0}'.format(pipes.quote(path))
rcmd += ' -n {0} -s {1}'.format(name, expected.upper())
__salt__['cmd.run'](rcmd, python_shell=False, timeout=30)
_clear_context()
post = state(name, path=path)
ret = {'result': post == expected,
'state': {'old': pre, 'new': post}}
return ret
def _ensure_exists(name, path=None):
'''
Raise an exception if the container does not exist
'''
if not exists(name, path=path):
raise CommandExecutionError(
'Container \'{0}\' does not exist'.format(name)
)
def _ensure_running(name, no_start=False, path=None):
'''
If the container is not currently running, start it. This function returns
the state that the container was in before changing
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
'''
_ensure_exists(name, path=path)
pre = state(name, path=path)
if pre == 'running':
# This will be a no-op but running the function will give us a pretty
# return dict.
return start(name, path=path)
elif pre == 'stopped':
if no_start:
raise CommandExecutionError(
'Container \'{0}\' is not running'.format(name)
)
return start(name, path=path)
elif pre == 'frozen':
if no_start:
raise CommandExecutionError(
'Container \'{0}\' is not running'.format(name)
)
return unfreeze(name, path=path)
def restart(name, path=None, lxc_config=None, force=False):
'''
.. versionadded:: 2015.5.0
Restart the named container. If the container was not running, the
container will merely be started.
name
The name of the container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
lxc_config
path to a lxc config file
config file will be guessed from container name otherwise
.. versionadded:: 2015.8.0
force : False
If ``True``, the container will be force-stopped instead of gracefully
shut down
CLI Example:
.. code-block:: bash
salt myminion lxc.restart name
'''
_ensure_exists(name, path=path)
orig_state = state(name, path=path)
if orig_state != 'stopped':
stop(name, kill=force, path=path)
ret = start(name, path=path, lxc_config=lxc_config)
ret['state']['old'] = orig_state
if orig_state != 'stopped':
ret['restarted'] = True
return ret
def start(name, **kwargs):
'''
Start the named container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
lxc_config
path to a lxc config file
config file will be guessed from container name otherwise
.. versionadded:: 2015.8.0
use_vt
run the command through VT
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.start name
'''
path = kwargs.get('path', None)
cpath = get_root_path(path)
lxc_config = kwargs.get('lxc_config', None)
cmd = 'lxc-start'
if not lxc_config:
lxc_config = os.path.join(cpath, name, 'config')
# we try to start, even without config, if global opts are there
if os.path.exists(lxc_config):
cmd += ' -f {0}'.format(pipes.quote(lxc_config))
cmd += ' -d'
_ensure_exists(name, path=path)
if state(name, path=path) == 'frozen':
raise CommandExecutionError(
'Container \'{0}\' is frozen, use lxc.unfreeze'.format(name)
)
# lxc-start daemonize itself violently, we must not communicate with it
use_vt = kwargs.get('use_vt', None)
with_communicate = kwargs.get('with_communicate', False)
return _change_state(cmd, name, 'running',
stdout=None,
stderr=None,
stdin=None,
with_communicate=with_communicate,
path=path,
use_vt=use_vt)
def stop(name, kill=False, path=None, use_vt=None):
'''
Stop the named container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
kill: False
Do not wait for the container to stop, kill all tasks in the container.
Older LXC versions will stop containers like this irrespective of this
argument.
.. versionchanged:: 2015.5.0
Default value changed to ``False``
use_vt
run the command through VT
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.stop name
'''
_ensure_exists(name, path=path)
orig_state = state(name, path=path)
if orig_state == 'frozen' and not kill:
# Gracefully stopping a frozen container is slower than unfreezing and
# then stopping it (at least in my testing), so if we're not
# force-stopping the container, unfreeze it first.
unfreeze(name, path=path)
cmd = 'lxc-stop'
if kill:
cmd += ' -k'
ret = _change_state(cmd, name, 'stopped', use_vt=use_vt, path=path)
ret['state']['old'] = orig_state
return ret
def freeze(name, **kwargs):
'''
Freeze the named container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
start : False
If ``True`` and the container is stopped, the container will be started
before attempting to freeze.
.. versionadded:: 2015.5.0
use_vt
run the command through VT
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.freeze name
'''
use_vt = kwargs.get('use_vt', None)
path = kwargs.get('path', None)
_ensure_exists(name, path=path)
orig_state = state(name, path=path)
start_ = kwargs.get('start', False)
if orig_state == 'stopped':
if not start_:
raise CommandExecutionError(
'Container \'{0}\' is stopped'.format(name)
)
start(name, path=path)
cmd = 'lxc-freeze'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
ret = _change_state(cmd, name, 'frozen', use_vt=use_vt, path=path)
if orig_state == 'stopped' and start_:
ret['state']['old'] = orig_state
ret['started'] = True
ret['state']['new'] = state(name, path=path)
return ret
def unfreeze(name, path=None, use_vt=None):
'''
Unfreeze the named container.
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
use_vt
run the command through VT
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.unfreeze name
'''
_ensure_exists(name, path=path)
if state(name, path=path) == 'stopped':
raise CommandExecutionError(
'Container \'{0}\' is stopped'.format(name)
)
cmd = 'lxc-unfreeze'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
return _change_state(cmd, name, 'running', path=path, use_vt=use_vt)
def destroy(name, stop=False, path=None):
'''
Destroy the named container.
.. warning::
Destroys all data associated with the container.
path
path to the container parent directory (default: /var/lib/lxc)
.. versionadded:: 2015.8.0
stop : False
If ``True``, the container will be destroyed even if it is
running/frozen.
.. versionchanged:: 2015.5.0
Default value changed to ``False``. This more closely matches the
behavior of ``lxc-destroy(1)``, and also makes it less likely that
an accidental command will destroy a running container that was
being used for important things.
CLI Examples:
.. code-block:: bash
salt '*' lxc.destroy foo
salt '*' lxc.destroy foo stop=True
'''
_ensure_exists(name, path=path)
if not stop and state(name, path=path) != 'stopped':
raise CommandExecutionError(
'Container \'{0}\' is not stopped'.format(name)
)
return _change_state('lxc-destroy', name, None, path=path)
# Compatibility between LXC and nspawn
remove = salt.utils.functools.alias_function(destroy, 'remove')
def exists(name, path=None):
'''
Returns whether the named container exists.
path
path to the container parent directory (default: /var/lib/lxc)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.exists name
'''
_exists = name in ls_(path=path)
# container may be just created but we did cached earlier the
# lxc-ls results
if not _exists:
_exists = name in ls_(cache=False, path=path)
return _exists
def state(name, path=None):
'''
Returns the state of a container.
path
path to the container parent directory (default: /var/lib/lxc)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.state name
'''
# Don't use _ensure_exists() here, it will mess with _change_state()
cachekey = 'lxc.state.{0}{1}'.format(name, path)
try:
return __context__[cachekey]
except KeyError:
if not exists(name, path=path):
__context__[cachekey] = None
else:
cmd = 'lxc-info'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0}'.format(name)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
if ret['retcode'] != 0:
_clear_context()
raise CommandExecutionError(
'Unable to get state of container \'{0}\''.format(name)
)
c_infos = ret['stdout'].splitlines()
c_state = None
for c_info in c_infos:
stat = c_info.split(':')
if stat[0].lower() == 'state':
c_state = stat[1].strip().lower()
break
__context__[cachekey] = c_state
return __context__[cachekey]
def get_parameter(name, parameter, path=None):
'''
Returns the value of a cgroup parameter for a container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.get_parameter container_name memory.limit_in_bytes
'''
_ensure_exists(name, path=path)
cmd = 'lxc-cgroup'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0} {1}'.format(name, parameter)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
if ret['retcode'] != 0:
raise CommandExecutionError(
'Unable to retrieve value for \'{0}\''.format(parameter)
)
return ret['stdout'].strip()
def set_parameter(name, parameter, value, path=None):
'''
Set the value of a cgroup parameter for a container.
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.set_parameter name parameter value
'''
if not exists(name, path=path):
return None
cmd = 'lxc-cgroup'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0} {1} {2}'.format(name, parameter, value)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
if ret['retcode'] != 0:
return False
else:
return True
def info(name, path=None):
'''
Returns information about a container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.info name
'''
cachekey = 'lxc.info.{0}{1}'.format(name, path)
try:
return __context__[cachekey]
except KeyError:
_ensure_exists(name, path=path)
cpath = get_root_path(path)
try:
conf_file = os.path.join(cpath, name, 'config')
except AttributeError:
conf_file = os.path.join(cpath, six.text_type(name), 'config')
if not os.path.isfile(conf_file):
raise CommandExecutionError(
'LXC config file {0} does not exist'.format(conf_file)
)
ret = {}
config = []
with salt.utils.files.fopen(conf_file) as fp_:
for line in fp_:
line = salt.utils.stringutils.to_unicode(line)
comps = [x.strip() for x in
line.split('#', 1)[0].strip().split('=', 1)]
if len(comps) == 2:
config.append(tuple(comps))
ifaces = []
current = None
for key, val in config:
if key == 'lxc.network.type':
current = {'type': val}
ifaces.append(current)
elif not current:
continue
elif key.startswith('lxc.network.'):
current[key.replace('lxc.network.', '', 1)] = val
if ifaces:
ret['nics'] = ifaces
ret['rootfs'] = next(
(x[1] for x in config if x[0] == 'lxc.rootfs'),
None
)
ret['state'] = state(name, path=path)
ret['ips'] = []
ret['public_ips'] = []
ret['private_ips'] = []
ret['public_ipv4_ips'] = []
ret['public_ipv6_ips'] = []
ret['private_ipv4_ips'] = []
ret['private_ipv6_ips'] = []
ret['ipv4_ips'] = []
ret['ipv6_ips'] = []
ret['size'] = None
ret['config'] = conf_file
if ret['state'] == 'running':
try:
limit = int(get_parameter(name, 'memory.limit_in_bytes'))
except (CommandExecutionError, TypeError, ValueError):
limit = 0
try:
usage = int(get_parameter(name, 'memory.usage_in_bytes'))
except (CommandExecutionError, TypeError, ValueError):
usage = 0
free = limit - usage
ret['memory_limit'] = limit
ret['memory_free'] = free
size = run_stdout(name, 'df /', path=path, python_shell=False)
# The size is the 2nd column of the last line
ret['size'] = size.splitlines()[-1].split()[1]
# First try iproute2
ip_cmd = run_all(
name, 'ip link show', path=path, python_shell=False)
if ip_cmd['retcode'] == 0:
ip_data = ip_cmd['stdout']
ip_cmd = run_all(
name, 'ip addr show', path=path, python_shell=False)
ip_data += '\n' + ip_cmd['stdout']
ip_data = salt.utils.network._interfaces_ip(ip_data)
else:
# That didn't work, try ifconfig
ip_cmd = run_all(
name, 'ifconfig', path=path, python_shell=False)
if ip_cmd['retcode'] == 0:
ip_data = \
salt.utils.network._interfaces_ifconfig(
ip_cmd['stdout'])
else:
# Neither was successful, give up
log.warning(
'Unable to run ip or ifconfig in container \'%s\'', name
)
ip_data = {}
ret['ipv4_ips'] = salt.utils.network.ip_addrs(
include_loopback=True,
interface_data=ip_data
)
ret['ipv6_ips'] = salt.utils.network.ip_addrs6(
include_loopback=True,
interface_data=ip_data
)
ret['ips'] = ret['ipv4_ips'] + ret['ipv6_ips']
for address in ret['ipv4_ips']:
if address == '127.0.0.1':
ret['private_ips'].append(address)
ret['private_ipv4_ips'].append(address)
elif salt.utils.cloud.is_public_ip(address):
ret['public_ips'].append(address)
ret['public_ipv4_ips'].append(address)
else:
ret['private_ips'].append(address)
ret['private_ipv4_ips'].append(address)
for address in ret['ipv6_ips']:
if address == '::1' or address.startswith('fe80'):
ret['private_ips'].append(address)
ret['private_ipv6_ips'].append(address)
else:
ret['public_ips'].append(address)
ret['public_ipv6_ips'].append(address)
for key in [x for x in ret if x == 'ips' or x.endswith('ips')]:
ret[key].sort(key=_ip_sort)
__context__[cachekey] = ret
return __context__[cachekey]
def set_password(name, users, password, encrypted=True, path=None):
'''
.. versionchanged:: 2015.5.0
Function renamed from ``set_pass`` to ``set_password``. Additionally,
this function now supports (and defaults to using) a password hash
instead of a plaintext password.
Set the password of one or more system users inside containers
users
Comma-separated list (or python list) of users to change password
password
Password to set for the specified user(s)
encrypted : True
If true, ``password`` must be a password hash. Set to ``False`` to set
a plaintext password (not recommended).
.. versionadded:: 2015.5.0
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.set_pass container-name root '$6$uJ2uAyLU$KoI67t8As/0fXtJOPcHKGXmUpcoYUcVR2K6x93walnShTCQvjRwq25yIkiCBOqgbfdKQSFnAo28/ek6716vEV1'
salt '*' lxc.set_pass container-name root foo encrypted=False
'''
def _bad_user_input():
raise SaltInvocationError('Invalid input for \'users\' parameter')
if not isinstance(users, list):
try:
users = users.split(',')
except AttributeError:
_bad_user_input()
if not users:
_bad_user_input()
failed_users = []
for user in users:
result = retcode(name,
'chpasswd{0}'.format(' -e' if encrypted else ''),
stdin=':'.join((user, password)),
python_shell=False,
path=path,
chroot_fallback=True,
output_loglevel='quiet')
if result != 0:
failed_users.append(user)
if failed_users:
raise CommandExecutionError(
'Password change failed for the following user(s): {0}'
.format(', '.join(failed_users))
)
return True
set_pass = salt.utils.functools.alias_function(set_password, 'set_pass')
def update_lxc_conf(name, lxc_conf, lxc_conf_unset, path=None):
'''
Edit LXC configuration options
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.update_lxc_conf ubuntu \\
lxc_conf="[{'network.ipv4.ip':'10.0.3.5'}]" \\
lxc_conf_unset="['lxc.utsname']"
'''
_ensure_exists(name, path=path)
cpath = get_root_path(path)
lxc_conf_p = os.path.join(cpath, name, 'config')
if not os.path.exists(lxc_conf_p):
raise SaltInvocationError(
'Configuration file {0} does not exist'.format(lxc_conf_p)
)
changes = {'edited': [], 'added': [], 'removed': []}
ret = {'changes': changes, 'result': True, 'comment': ''}
# do not use salt.utils.files.fopen !
with salt.utils.files.fopen(lxc_conf_p, 'r') as fic:
filtered_lxc_conf = []
for row in lxc_conf:
if not row:
continue
for conf in row:
filtered_lxc_conf.append((conf.strip(),
row[conf].strip()))
ret['comment'] = 'lxc.conf is up to date'
lines = []
orig_config = salt.utils.stringutils.to_unicode(fic.read())
for line in orig_config.splitlines():
if line.startswith('#') or not line.strip():
lines.append([line, ''])
else:
line = line.split('=')
index = line.pop(0)
val = (index.strip(), '='.join(line).strip())
if val not in lines:
lines.append(val)
for key, item in filtered_lxc_conf:
matched = False
for idx, line in enumerate(lines[:]):
if line[0] == key:
matched = True
lines[idx] = (key, item)
if '='.join(line[1:]).strip() != item.strip():
changes['edited'].append(
({line[0]: line[1:]}, {key: item}))
break
if not matched:
if (key, item) not in lines:
lines.append((key, item))
changes['added'].append({key: item})
dest_lxc_conf = []
# filter unset
if lxc_conf_unset:
for line in lines:
for opt in lxc_conf_unset:
if (
not line[0].startswith(opt) and
line not in dest_lxc_conf
):
dest_lxc_conf.append(line)
else:
changes['removed'].append(opt)
else:
dest_lxc_conf = lines
conf = ''
for key, val in dest_lxc_conf:
if not val:
conf += '{0}\n'.format(key)
else:
conf += '{0} = {1}\n'.format(key.strip(), val.strip())
conf_changed = conf != orig_config
chrono = datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S')
if conf_changed:
# DO NOT USE salt.utils.files.fopen here, i got (kiorky)
# problems with lxc configs which were wiped !
with salt.utils.files.fopen('{0}.{1}'.format(lxc_conf_p, chrono), 'w') as wfic:
wfic.write(salt.utils.stringutils.to_str(conf))
with salt.utils.files.fopen(lxc_conf_p, 'w') as wfic:
wfic.write(salt.utils.stringutils.to_str(conf))
ret['comment'] = 'Updated'
ret['result'] = True
if not any(changes[x] for x in changes):
# Ensure an empty changes dict if nothing was modified
ret['changes'] = {}
return ret
def set_dns(name, dnsservers=None, searchdomains=None, path=None):
'''
.. versionchanged:: 2015.5.0
The ``dnsservers`` and ``searchdomains`` parameters can now be passed
as a comma-separated list.
Update /etc/resolv.confo
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.set_dns ubuntu "['8.8.8.8', '4.4.4.4']"
'''
if dnsservers is None:
dnsservers = ['8.8.8.8', '4.4.4.4']
elif not isinstance(dnsservers, list):
try:
dnsservers = dnsservers.split(',')
except AttributeError:
raise SaltInvocationError(
'Invalid input for \'dnsservers\' parameter'
)
if searchdomains is None:
searchdomains = []
elif not isinstance(searchdomains, list):
try:
searchdomains = searchdomains.split(',')
except AttributeError:
raise SaltInvocationError(
'Invalid input for \'searchdomains\' parameter'
)
dns = ['nameserver {0}'.format(x) for x in dnsservers]
dns.extend(['search {0}'.format(x) for x in searchdomains])
dns = '\n'.join(dns) + '\n'
# we may be using resolvconf in the container
# We need to handle that case with care:
# - we create the resolv.conf runtime directory (the
# linked directory) as anyway it will be shadowed when the real
# runned tmpfs mountpoint will be mounted.
# ( /etc/resolv.conf -> ../run/resolvconf/resolv.conf)
# Indeed, it can save us in any other case (running, eg, in a
# bare chroot when repairing or preparing the container for
# operation.
# - We also teach resolvconf to use the aforementioned dns.
# - We finally also set /etc/resolv.conf in all cases
rstr = __salt__['test.random_hash']()
# no tmp here, apparmor won't let us execute !
script = '/sbin/{0}_dns.sh'.format(rstr)
DNS_SCRIPT = "\n".join([
# 'set -x',
'#!/usr/bin/env bash',
'if [ -h /etc/resolv.conf ];then',
' if [ "x$(readlink /etc/resolv.conf)"'
' = "x../run/resolvconf/resolv.conf" ];then',
' if [ ! -d /run/resolvconf/ ];then',
' mkdir -p /run/resolvconf',
' fi',
' cat > /etc/resolvconf/resolv.conf.d/head <<EOF',
dns,
'EOF',
'',
' fi',
'fi',
'cat > /etc/resolv.conf <<EOF',
dns,
'EOF',
''])
result = run_all(
name, 'tee {0}'.format(script), path=path,
stdin=DNS_SCRIPT, python_shell=True)
if result['retcode'] == 0:
result = run_all(
name, 'sh -c "chmod +x {0};{0}"'.format(script),
path=path, python_shell=True)
# blindly delete the setter file
run_all(name,
'sh -c \'if [ -f "{0}" ];then rm -f "{0}";fi\''.format(script),
path=path, python_shell=True)
if result['retcode'] != 0:
error = ('Unable to write to /etc/resolv.conf in container \'{0}\''
.format(name))
if result['stderr']:
error += ': {0}'.format(result['stderr'])
raise CommandExecutionError(error)
return True
def running_systemd(name, cache=True, path=None):
'''
Determine if systemD is running
path
path to the container parent
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.running_systemd ubuntu
'''
k = 'lxc.systemd.test.{0}{1}'.format(name, path)
ret = __context__.get(k, None)
if ret is None or not cache:
rstr = __salt__['test.random_hash']()
# no tmp here, apparmor won't let us execute !
script = '/sbin/{0}_testsystemd.sh'.format(rstr)
# ubuntu already had since trusty some bits of systemd but was
# still using upstart ...
# we need to be a bit more careful that just testing that systemd
# is present
_script = textwrap.dedent(
'''\
#!/usr/bin/env bash
set -x
if ! command -v systemctl 1>/dev/null 2>/dev/null;then exit 2;fi
for i in \\
/run/systemd/journal/dev-log\\
/run/systemd/journal/flushed\\
/run/systemd/journal/kernel-seqnum\\
/run/systemd/journal/socket\\
/run/systemd/journal/stdout\\
/var/run/systemd/journal/dev-log\\
/var/run/systemd/journal/flushed\\
/var/run/systemd/journal/kernel-seqnum\\
/var/run/systemd/journal/socket\\
/var/run/systemd/journal/stdout\\
;do\\
if test -e ${i};then exit 0;fi
done
if test -d /var/systemd/system;then exit 0;fi
exit 2
''')
result = run_all(
name, 'tee {0}'.format(script), path=path,
stdin=_script, python_shell=True)
if result['retcode'] == 0:
result = run_all(name,
'sh -c "chmod +x {0};{0}"'''.format(script),
path=path,
python_shell=True)
else:
raise CommandExecutionError(
'lxc {0} failed to copy initd tester'.format(name))
run_all(name,
'sh -c \'if [ -f "{0}" ];then rm -f "{0}";fi\''
''.format(script),
path=path,
ignore_retcode=True,
python_shell=True)
if result['retcode'] != 0:
error = ('Unable to determine if the container \'{0}\''
' was running systemd, assmuming it is not.'
''.format(name))
if result['stderr']:
error += ': {0}'.format(result['stderr'])
# only cache result if we got a known exit code
if result['retcode'] in (0, 2):
__context__[k] = ret = not result['retcode']
return ret
def systemd_running_state(name, path=None):
'''
Get the operational state of a systemd based container
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.systemd_running_state ubuntu
'''
try:
ret = run_all(name,
'systemctl is-system-running',
path=path,
ignore_retcode=True)['stdout']
except CommandExecutionError:
ret = ''
return ret
def test_sd_started_state(name, path=None):
'''
Test if a systemd container is fully started
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.test_sd_started_state ubuntu
'''
qstate = systemd_running_state(name, path=path)
if qstate in ('initializing', 'starting'):
return False
elif qstate == '':
return None
else:
return True
def test_bare_started_state(name, path=None):
'''
Test if a non systemd container is fully started
For now, it consists only to test if the container is attachable
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.test_bare_started_state ubuntu
'''
try:
ret = run_all(
name, 'ls', path=path, ignore_retcode=True
)['retcode'] == 0
except (CommandExecutionError,):
ret = None
return ret
def wait_started(name, path=None, timeout=300):
'''
Check that the system has fully inited
This is actually very important for systemD based containers
see https://github.com/saltstack/salt/issues/23847
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.wait_started ubuntu
'''
if not exists(name, path=path):
raise CommandExecutionError(
'Container {0} does does exists'.format(name))
if not state(name, path=path) == 'running':
raise CommandExecutionError(
'Container {0} is not running'.format(name))
ret = False
if running_systemd(name, path=path):
test_started = test_sd_started_state
logger = log.error
else:
test_started = test_bare_started_state
logger = log.debug
now = time.time()
expire = now + timeout
now = time.time()
started = test_started(name, path=path)
while time.time() < expire and not started:
time.sleep(0.3)
started = test_started(name, path=path)
if started is None:
logger(
'Assuming %s is started, although we failed to detect that'
' is fully started correctly', name)
ret = True
else:
ret = started
return ret
def _needs_install(name, path=None):
ret = 0
has_minion = retcode(name,
'which salt-minion',
path=path,
ignore_retcode=True)
# we assume that installing is when no minion is running
# but testing the executable presence is not enougth for custom
# installs where the bootstrap can do much more than installing
# the bare salt binaries.
if has_minion:
processes = run_stdout(name, "ps aux", path=path)
if 'salt-minion' not in processes:
ret = 1
else:
retcode(name, 'salt-call --local service.stop salt-minion')
else:
ret = 1
return ret
def bootstrap(name,
config=None,
approve_key=True,
install=True,
pub_key=None,
priv_key=None,
bootstrap_url=None,
force_install=False,
unconditional_install=False,
path=None,
bootstrap_delay=None,
bootstrap_args=None,
bootstrap_shell=None):
'''
Install and configure salt in a container.
config
Minion configuration options. By default, the ``master`` option is set
to the target host's master.
approve_key
Request a pre-approval of the generated minion key. Requires
that the salt-master be configured to either auto-accept all keys or
expect a signing request from the target host. Default: ``True``
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
pub_key
Explicit public key to pressed the minion with (optional).
This can be either a filepath or a string representing the key
priv_key
Explicit private key to pressed the minion with (optional).
This can be either a filepath or a string representing the key
bootstrap_delay
Delay in seconds between end of container creation and bootstrapping.
Useful when waiting for container to obtain a DHCP lease.
.. versionadded:: 2015.5.0
bootstrap_url
url, content or filepath to the salt bootstrap script
bootstrap_args
salt bootstrap script arguments
bootstrap_shell
shell to execute the script into
install
Whether to attempt a full installation of salt-minion if needed.
force_install
Force installation even if salt-minion is detected,
this is the way to run vendor bootstrap scripts even
if a salt minion is already present in the container
unconditional_install
Run the script even if the container seems seeded
CLI Examples:
.. code-block:: bash
salt 'minion' lxc.bootstrap container_name [config=config_data] \\
[approve_key=(True|False)] [install=(True|False)]
'''
wait_started(name, path=path)
if bootstrap_delay is not None:
try:
log.info('LXC %s: bootstrap_delay: %s', name, bootstrap_delay)
time.sleep(bootstrap_delay)
except TypeError:
# Bad input, but assume since a value was passed that
# a delay was desired, and sleep for 5 seconds
time.sleep(5)
c_info = info(name, path=path)
if not c_info:
return None
# default set here as we cannot set them
# in def as it can come from a chain of procedures.
if bootstrap_args:
# custom bootstrap args can be totally customized, and user could
# have inserted the placeholder for the config directory.
# For example, some salt bootstrap script do not use at all -c
if '{0}' not in bootstrap_args:
bootstrap_args += ' -c {0}'
else:
bootstrap_args = '-c {0}'
if not bootstrap_shell:
bootstrap_shell = 'sh'
orig_state = _ensure_running(name, path=path)
if not orig_state:
return orig_state
if not force_install:
needs_install = _needs_install(name, path=path)
else:
needs_install = True
seeded = retcode(name,
'test -e \'{0}\''.format(SEED_MARKER),
path=path,
chroot_fallback=True,
ignore_retcode=True) == 0
tmp = tempfile.mkdtemp()
if seeded and not unconditional_install:
ret = True
else:
ret = False
cfg_files = __salt__['seed.mkconfig'](
config, tmp=tmp, id_=name, approve_key=approve_key,
pub_key=pub_key, priv_key=priv_key)
if needs_install or force_install or unconditional_install:
if install:
rstr = __salt__['test.random_hash']()
configdir = '/var/tmp/.c_{0}'.format(rstr)
cmd = 'install -m 0700 -d {0}'.format(configdir)
if run_all(
name, cmd, path=path, python_shell=False
)['retcode'] != 0:
log.error('tmpdir %s creation failed %s', configdir, cmd)
return False
bs_ = __salt__['config.gather_bootstrap_script'](
bootstrap=bootstrap_url)
script = '/sbin/{0}_bootstrap.sh'.format(rstr)
copy_to(name, bs_, script, path=path)
result = run_all(name,
'sh -c "chmod +x {0}"'.format(script),
path=path,
python_shell=True)
copy_to(name, cfg_files['config'],
os.path.join(configdir, 'minion'),
path=path)
copy_to(name, cfg_files['privkey'],
os.path.join(configdir, 'minion.pem'),
path=path)
copy_to(name, cfg_files['pubkey'],
os.path.join(configdir, 'minion.pub'),
path=path)
bootstrap_args = bootstrap_args.format(configdir)
cmd = ('{0} {2} {1}'
.format(bootstrap_shell,
bootstrap_args.replace("'", "''"),
script))
# log ASAP the forged bootstrap command which can be wrapped
# out of the output in case of unexpected problem
log.info('Running %s in LXC container \'%s\'', cmd, name)
ret = retcode(name, cmd, output_loglevel='info',
path=path, use_vt=True) == 0
run_all(name,
'sh -c \'if [ -f "{0}" ];then rm -f "{0}";fi\''
''.format(script),
path=path,
ignore_retcode=True,
python_shell=True)
else:
ret = False
else:
minion_config = salt.config.minion_config(cfg_files['config'])
pki_dir = minion_config['pki_dir']
copy_to(name,
cfg_files['config'],
'/etc/salt/minion',
path=path)
copy_to(name,
cfg_files['privkey'],
os.path.join(pki_dir, 'minion.pem'),
path=path)
copy_to(name,
cfg_files['pubkey'],
os.path.join(pki_dir, 'minion.pub'),
path=path)
run(name,
'salt-call --local service.enable salt-minion',
path=path,
python_shell=False)
ret = True
shutil.rmtree(tmp)
if orig_state == 'stopped':
stop(name, path=path)
elif orig_state == 'frozen':
freeze(name, path=path)
# mark seeded upon successful install
if ret:
run(name,
'touch \'{0}\''.format(SEED_MARKER),
path=path,
python_shell=False)
return ret
def attachable(name, path=None):
'''
Return True if the named container can be attached to via the lxc-attach
command
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt 'minion' lxc.attachable ubuntu
'''
cachekey = 'lxc.attachable{0}{1}'.format(name, path)
try:
return __context__[cachekey]
except KeyError:
_ensure_exists(name, path=path)
# Can't use run() here because it uses attachable() and would
# endlessly recurse, resulting in a traceback
log.debug('Checking if LXC container %s is attachable', name)
cmd = 'lxc-attach'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' --clear-env -n {0} -- /usr/bin/env'.format(name)
result = __salt__['cmd.retcode'](cmd,
python_shell=False,
output_loglevel='quiet',
ignore_retcode=True) == 0
__context__[cachekey] = result
return __context__[cachekey]
def _run(name,
cmd,
output=None,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=None,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
Common logic for lxc.run functions
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
'''
orig_state = state(name, path=path)
try:
if attachable(name, path=path):
ret = __salt__['container_resource.run'](
name,
cmd,
path=path,
container_type=__virtualname__,
exec_driver=EXEC_DRIVER,
output=output,
no_start=no_start,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
ignore_retcode=ignore_retcode,
use_vt=use_vt,
keep_env=keep_env)
else:
if not chroot_fallback:
raise CommandExecutionError(
'{0} is not attachable.'.format(name))
rootfs = info(name, path=path).get('rootfs')
# Set context var to make cmd.run_chroot run cmd.run instead of
# cmd.run_all.
__context__['cmd.run_chroot.func'] = __salt__['cmd.run']
ret = __salt__['cmd.run_chroot'](rootfs,
cmd,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
ignore_retcode=ignore_retcode)
except Exception:
raise
finally:
# Make sure we honor preserve_state, even if there was an exception
new_state = state(name, path=path)
if preserve_state:
if orig_state == 'stopped' and new_state != 'stopped':
stop(name, path=path)
elif orig_state == 'frozen' and new_state != 'frozen':
freeze(name, start=True, path=path)
if output in (None, 'all'):
return ret
else:
return ret[output]
def run(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.8.0
Run :mod:`cmd.run <salt.modules.cmdmod.run>` within a container
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed in stderr if the command being run
does not exist. If no output is returned using this function, try using
:mod:`lxc.run_stderr <salt.modules.lxc.run_stderr>` or
:mod:`lxc.run_all <salt.modules.lxc.run_all>`.
name
Name of the container in which to run the command
cmd
Command to run
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console. Assumes
``output=all``.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
CLI Example:
.. code-block:: bash
salt myminion lxc.run mycontainer 'ifconfig -a'
'''
return _run(name,
cmd,
path=path,
output=None,
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def run_stdout(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.5.0
Run :mod:`cmd.run_stdout <salt.modules.cmdmod.run_stdout>` within a container
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed in stderr if the command being run
does not exist. If no output is returned using this function, try using
:mod:`lxc.run_stderr <salt.modules.lxc.run_stderr>` or
:mod:`lxc.run_all <salt.modules.lxc.run_all>`.
name
Name of the container in which to run the command
cmd
Command to run
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console
``output=all``.
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
CLI Example:
.. code-block:: bash
salt myminion lxc.run_stdout mycontainer 'ifconfig -a'
'''
return _run(name,
cmd,
path=path,
output='stdout',
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def run_stderr(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.5.0
Run :mod:`cmd.run_stderr <salt.modules.cmdmod.run_stderr>` within a container
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed if the command being run does not
exist.
name
Name of the container in which to run the command
cmd
Command to run
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console
``output=all``.
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
CLI Example:
.. code-block:: bash
salt myminion lxc.run_stderr mycontainer 'ip addr show'
'''
return _run(name,
cmd,
path=path,
output='stderr',
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def retcode(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.5.0
Run :mod:`cmd.retcode <salt.modules.cmdmod.retcode>` within a container
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed in stderr if the command being run
does not exist. If the retcode is nonzero and not what was expected,
try using :mod:`lxc.run_stderr <salt.modules.lxc.run_stderr>`
or :mod:`lxc.run_all <salt.modules.lxc.run_all>`.
name
Name of the container in which to run the command
cmd
Command to run
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console
``output=all``.
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
CLI Example:
.. code-block:: bash
salt myminion lxc.retcode mycontainer 'ip addr show'
'''
return _run(name,
cmd,
output='retcode',
path=path,
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def run_all(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.5.0
Run :mod:`cmd.run_all <salt.modules.cmdmod.run_all>` within a container
.. note::
While the command is run within the container, it is initiated from the
host. Therefore, the PID in the return dict is from the host, not from
the container.
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed in stderr if the command being run
does not exist.
name
Name of the container in which to run the command
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
cmd
Command to run
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console
``output=all``.
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
CLI Example:
.. code-block:: bash
salt myminion lxc.run_all mycontainer 'ip addr show'
'''
return _run(name,
cmd,
output='all',
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
path=path,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def _get_md5(name, path):
'''
Get the MD5 checksum of a file from a container
'''
output = run_stdout(name, 'md5sum "{0}"'.format(path),
chroot_fallback=True,
ignore_retcode=True)
try:
return output.split()[0]
except IndexError:
# Destination file does not exist or could not be accessed
return None
def copy_to(name, source, dest, overwrite=False, makedirs=False, path=None):
'''
.. versionchanged:: 2015.8.0
Function renamed from ``lxc.cp`` to ``lxc.copy_to`` for consistency
with other container types. ``lxc.cp`` will continue to work, however.
For versions 2015.2.x and earlier, use ``lxc.cp``.
Copy a file or directory from the host into a container
name
Container name
source
File to be copied to the container
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
dest
Destination on the container. Must be an absolute path.
.. versionchanged:: 2015.5.0
If the destination is a directory, the file will be copied into
that directory.
overwrite : False
Unless this option is set to ``True``, then if a file exists at the
location specified by the ``dest`` argument, an error will be raised.
.. versionadded:: 2015.8.0
makedirs : False
Create the parent directory on the container if it does not already
exist.
.. versionadded:: 2015.5.0
CLI Example:
.. code-block:: bash
salt 'minion' lxc.copy_to /tmp/foo /root/foo
salt 'minion' lxc.cp /tmp/foo /root/foo
'''
_ensure_running(name, no_start=True, path=path)
return __salt__['container_resource.copy_to'](
name,
source,
dest,
container_type=__virtualname__,
path=path,
exec_driver=EXEC_DRIVER,
overwrite=overwrite,
makedirs=makedirs)
cp = salt.utils.functools.alias_function(copy_to, 'cp')
def read_conf(conf_file, out_format='simple'):
'''
Read in an LXC configuration file. By default returns a simple, unsorted
dict, but can also return a more detailed structure including blank lines
and comments.
out_format:
set to 'simple' if you need the old and unsupported behavior.
This won't support the multiple lxc values (eg: multiple network nics)
CLI Examples:
.. code-block:: bash
salt 'minion' lxc.read_conf /etc/lxc/mycontainer.conf
salt 'minion' lxc.read_conf /etc/lxc/mycontainer.conf out_format=commented
'''
ret_commented = []
ret_simple = {}
with salt.utils.files.fopen(conf_file, 'r') as fp_:
for line in salt.utils.data.decode(fp_.readlines()):
if '=' not in line:
ret_commented.append(line)
continue
comps = line.split('=')
value = '='.join(comps[1:]).strip()
comment = None
if value.strip().startswith('#'):
vcomps = value.strip().split('#')
value = vcomps[1].strip()
comment = '#'.join(vcomps[1:]).strip()
ret_commented.append({comps[0].strip(): {
'value': value,
'comment': comment,
}})
else:
ret_commented.append({comps[0].strip(): value})
ret_simple[comps[0].strip()] = value
if out_format == 'simple':
return ret_simple
return ret_commented
def write_conf(conf_file, conf):
'''
Write out an LXC configuration file
This is normally only used internally. The format of the data structure
must match that which is returned from ``lxc.read_conf()``, with
``out_format`` set to ``commented``.
An example might look like:
.. code-block:: python
[
{'lxc.utsname': '$CONTAINER_NAME'},
'# This is a commented line\\n',
'\\n',
{'lxc.mount': '$CONTAINER_FSTAB'},
{'lxc.rootfs': {'comment': 'This is another test',
'value': 'This is another test'}},
'\\n',
{'lxc.network.type': 'veth'},
{'lxc.network.flags': 'up'},
{'lxc.network.link': 'br0'},
{'lxc.network.mac': '$CONTAINER_MACADDR'},
{'lxc.network.ipv4': '$CONTAINER_IPADDR'},
{'lxc.network.name': '$CONTAINER_DEVICENAME'},
]
CLI Example:
.. code-block:: bash
salt 'minion' lxc.write_conf /etc/lxc/mycontainer.conf \\
out_format=commented
'''
if not isinstance(conf, list):
raise SaltInvocationError('Configuration must be passed as a list')
# construct the content prior to write to the file
# to avoid half written configs
content = ''
for line in conf:
if isinstance(line, (six.text_type, six.string_types)):
content += line
elif isinstance(line, dict):
for key in list(line.keys()):
out_line = None
if isinstance(
line[key],
(six.text_type, six.string_types, six.integer_types, float)
):
out_line = ' = '.join((key, "{0}".format(line[key])))
elif isinstance(line[key], dict):
out_line = ' = '.join((key, line[key]['value']))
if 'comment' in line[key]:
out_line = ' # '.join((out_line, line[key]['comment']))
if out_line:
content += out_line
content += '\n'
with salt.utils.files.fopen(conf_file, 'w') as fp_:
fp_.write(salt.utils.stringutils.to_str(content))
return {}
def edit_conf(conf_file,
out_format='simple',
read_only=False,
lxc_config=None,
**kwargs):
'''
Edit an LXC configuration file. If a setting is already present inside the
file, its value will be replaced. If it does not exist, it will be appended
to the end of the file. Comments and blank lines will be kept in-tact if
they already exist in the file.
out_format:
Set to simple if you need backward compatibility (multiple items for a
simple key is not supported)
read_only:
return only the edited configuration without applying it
to the underlying lxc configuration file
lxc_config:
List of dict containning lxc configuration items
For network configuration, you also need to add the device it belongs
to, otherwise it will default to eth0.
Also, any change to a network parameter will result in the whole
network reconfiguration to avoid mismatchs, be aware of that !
After the file is edited, its contents will be returned. By default, it
will be returned in ``simple`` format, meaning an unordered dict (which
may not represent the actual file order). Passing in an ``out_format`` of
``commented`` will return a data structure which accurately represents the
order and content of the file.
CLI Example:
.. code-block:: bash
salt 'minion' lxc.edit_conf /etc/lxc/mycontainer.conf \\
out_format=commented lxc.network.type=veth
salt 'minion' lxc.edit_conf /etc/lxc/mycontainer.conf \\
out_format=commented \\
lxc_config="[{'lxc.network.name': 'eth0', \\
'lxc.network.ipv4': '1.2.3.4'},
{'lxc.network.name': 'eth2', \\
'lxc.network.ipv4': '1.2.3.5',\\
'lxc.network.gateway': '1.2.3.1'}]"
'''
data = []
try:
conf = read_conf(conf_file, out_format=out_format)
except Exception:
conf = []
if not lxc_config:
lxc_config = []
lxc_config = copy.deepcopy(lxc_config)
# search if we want to access net config
# in that case, we will replace all the net configuration
net_config = []
for lxc_kws in lxc_config + [kwargs]:
net_params = {}
for kwarg in [a for a in lxc_kws]:
if kwarg.startswith('__'):
continue
if kwarg.startswith('lxc.network.'):
net_params[kwarg] = lxc_kws[kwarg]
lxc_kws.pop(kwarg, None)
if net_params:
net_config.append(net_params)
nic_opts = salt.utils.odict.OrderedDict()
for params in net_config:
dev = params.get('lxc.network.name', DEFAULT_NIC)
dev_opts = nic_opts.setdefault(dev, salt.utils.odict.OrderedDict())
for param in params:
opt = param.replace('lxc.network.', '')
opt = {'hwaddr': 'mac'}.get(opt, opt)
dev_opts[opt] = params[param]
net_changes = []
if nic_opts:
net_changes = _config_list(conf, only_net=True,
**{'network_profile': DEFAULT_NIC,
'nic_opts': nic_opts})
if net_changes:
lxc_config.extend(net_changes)
for line in conf:
if not isinstance(line, dict):
data.append(line)
continue
else:
for key in list(line.keys()):
val = line[key]
if net_changes and key.startswith('lxc.network.'):
continue
found = False
for ix in range(len(lxc_config)):
kw = lxc_config[ix]
if key in kw:
found = True
data.append({key: kw[key]})
del kw[key]
if not found:
data.append({key: val})
for lxc_kws in lxc_config:
for kwarg in lxc_kws:
data.append({kwarg: lxc_kws[kwarg]})
if read_only:
return data
write_conf(conf_file, data)
return read_conf(conf_file, out_format)
def reboot(name, path=None):
'''
Reboot a container.
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Examples:
.. code-block:: bash
salt 'minion' lxc.reboot myvm
'''
ret = {'result': True,
'changes': {},
'comment': '{0} rebooted'.format(name)}
does_exist = exists(name, path=path)
if does_exist and (state(name, path=path) == 'running'):
try:
stop(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
ret['result'] = False
return ret
if does_exist and (state(name, path=path) != 'running'):
try:
start(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
ret['result'] = False
return ret
ret['changes'][name] = 'rebooted'
return ret
def reconfigure(name,
cpu=None,
cpuset=None,
cpushare=None,
memory=None,
profile=None,
network_profile=None,
nic_opts=None,
bridge=None,
gateway=None,
autostart=None,
utsname=None,
rootfs=None,
path=None,
**kwargs):
'''
Reconfigure a container.
This only applies to a few property
name
Name of the container.
utsname
utsname of the container.
.. versionadded:: 2016.3.0
rootfs
rootfs of the container.
.. versionadded:: 2016.3.0
cpu
Select a random number of cpu cores and assign it to the cpuset, if the
cpuset option is set then this option will be ignored
cpuset
Explicitly define the cpus this container will be bound to
cpushare
cgroups cpu shares.
autostart
autostart container on reboot
memory
cgroups memory limit, in MB.
(0 for nolimit, None for old default 1024MB)
gateway
the ipv4 gateway to use
the default does nothing more than lxcutils does
bridge
the bridge to use
the default does nothing more than lxcutils does
nic
Network interfaces profile (defined in config or pillar).
nic_opts
Extra options for network interfaces, will override
``{"eth0": {"mac": "aa:bb:cc:dd:ee:ff", "ipv4": "10.1.1.1", "ipv6": "2001:db8::ff00:42:8329"}}``
or
``{"eth0": {"mac": "aa:bb:cc:dd:ee:ff", "ipv4": "10.1.1.1/24", "ipv6": "2001:db8::ff00:42:8329"}}``
path
path to the container parent
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt-call -lall mc_lxc_fork.reconfigure foobar nic_opts="{'eth1': {'mac': '00:16:3e:dd:ee:44'}}" memory=4
'''
changes = {}
cpath = get_root_path(path)
path = os.path.join(cpath, name, 'config')
ret = {'name': name,
'comment': 'config for {0} up to date'.format(name),
'result': True,
'changes': changes}
profile = get_container_profile(copy.deepcopy(profile))
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, _marker)
profile_match = profile.pop(key, default)
# let kwarg overrides be the preferred choice
if kw_overrides_match is _marker:
return profile_match
return kw_overrides_match
if nic_opts is not None and not network_profile:
network_profile = DEFAULT_NIC
if autostart is not None:
autostart = select('autostart', autostart)
else:
autostart = 'keep'
if not utsname:
utsname = select('utsname', utsname)
if os.path.exists(path):
old_chunks = read_conf(path, out_format='commented')
make_kw = salt.utils.odict.OrderedDict([
('utsname', utsname),
('rootfs', rootfs),
('autostart', autostart),
('cpu', cpu),
('gateway', gateway),
('cpuset', cpuset),
('cpushare', cpushare),
('network_profile', network_profile),
('nic_opts', nic_opts),
('bridge', bridge)])
# match 0 and none as memory = 0 in lxc config is harmful
if memory:
make_kw['memory'] = memory
kw = salt.utils.odict.OrderedDict()
for key, val in six.iteritems(make_kw):
if val is not None:
kw[key] = val
new_cfg = _config_list(conf_tuples=old_chunks, **kw)
if new_cfg:
edit_conf(path, out_format='commented', lxc_config=new_cfg)
chunks = read_conf(path, out_format='commented')
if old_chunks != chunks:
ret['comment'] = '{0} lxc config updated'.format(name)
if state(name, path=path) == 'running':
cret = reboot(name, path=path)
ret['result'] = cret['result']
return ret
def apply_network_profile(name, network_profile, nic_opts=None, path=None):
'''
.. versionadded:: 2015.5.0
Apply a network profile to a container
network_profile
profile name or default values (dict)
nic_opts
values to override in defaults (dict)
indexed by nic card names
path
path to the container parent
.. versionadded:: 2015.8.0
CLI Examples:
.. code-block:: bash
salt 'minion' lxc.apply_network_profile web1 centos
salt 'minion' lxc.apply_network_profile web1 centos \\
nic_opts="{'eth0': {'mac': 'xx:xx:xx:xx:xx:xx'}}"
salt 'minion' lxc.apply_network_profile web1 \\
"{'eth0': {'mac': 'xx:xx:xx:xx:xx:yy'}}"
nic_opts="{'eth0': {'mac': 'xx:xx:xx:xx:xx:xx'}}"
The special case to disable use of ethernet nics:
.. code-block:: bash
salt 'minion' lxc.apply_network_profile web1 centos \\
"{eth0: {disable: true}}"
'''
cpath = get_root_path(path)
cfgpath = os.path.join(cpath, name, 'config')
before = []
with salt.utils.files.fopen(cfgpath, 'r') as fp_:
for line in fp_:
before.append(line)
lxcconfig = _LXCConfig(name=name, path=path)
old_net = lxcconfig._filter_data('lxc.network')
network_params = {}
for param in _network_conf(
conf_tuples=old_net,
network_profile=network_profile, nic_opts=nic_opts
):
network_params.update(param)
if network_params:
edit_conf(cfgpath, out_format='commented', **network_params)
after = []
with salt.utils.files.fopen(cfgpath, 'r') as fp_:
for line in fp_:
after.append(line)
diff = ''
for line in difflib.unified_diff(before,
after,
fromfile='before',
tofile='after'):
diff += line
return diff
def get_pid(name, path=None):
'''
Returns a container pid.
Throw an exception if the container isn't running.
CLI Example:
.. code-block:: bash
salt '*' lxc.get_pid name
'''
if name not in list_(limit='running', path=path):
raise CommandExecutionError('Container {0} is not running, can\'t determine PID'.format(name))
info = __salt__['cmd.run']('lxc-info -n {0}'.format(name)).split("\n")
pid = [line.split(':')[1].strip() for line in info if re.match(r'\s*PID', line)][0]
return pid
def add_veth(name, interface_name, bridge=None, path=None):
'''
Add a veth to a container.
Note : this function doesn't update the container config, just add the interface at runtime
name
Name of the container
interface_name
Name of the interface in the container
bridge
Name of the bridge to attach the interface to (facultative)
CLI Examples:
.. code-block:: bash
salt '*' lxc.add_veth container_name eth1 br1
salt '*' lxc.add_veth container_name eth1
'''
# Get container init PID
pid = get_pid(name, path=path)
# Generate a ramdom string for veth and ensure that is isn't present on the system
while True:
random_veth = 'veth'+''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(6))
if random_veth not in __salt__['network.interfaces']().keys():
break
# Check prerequisites
if not __salt__['file.directory_exists']('/var/run/'):
raise CommandExecutionError('Directory /var/run required for lxc.add_veth doesn\'t exists')
if not __salt__['file.file_exists']('/proc/{0}/ns/net'.format(pid)):
raise CommandExecutionError('Proc file for container {0} network namespace doesn\'t exists'.format(name))
if not __salt__['file.directory_exists']('/var/run/netns'):
__salt__['file.mkdir']('/var/run/netns')
# Ensure that the symlink is up to date (change on container restart)
if __salt__['file.is_link']('/var/run/netns/{0}'.format(name)):
__salt__['file.remove']('/var/run/netns/{0}'.format(name))
__salt__['file.symlink']('/proc/{0}/ns/net'.format(pid), '/var/run/netns/{0}'.format(name))
# Ensure that interface doesn't exists
interface_exists = 0 == __salt__['cmd.retcode']('ip netns exec {netns} ip address list {interface}'.format(
netns=name,
interface=interface_name
))
if interface_exists:
raise CommandExecutionError('Interface {interface} already exists in {container}'.format(
interface=interface_name,
container=name
))
# Create veth and bring it up
if __salt__['cmd.retcode']('ip link add name {veth} type veth peer name {veth}_c'.format(veth=random_veth)) != 0:
raise CommandExecutionError('Error while creating the veth pair {0}'.format(random_veth))
if __salt__['cmd.retcode']('ip link set dev {0} up'.format(random_veth)) != 0:
raise CommandExecutionError('Error while bringing up host-side veth {0}'.format(random_veth))
# Attach it to the container
attached = 0 == __salt__['cmd.retcode']('ip link set dev {veth}_c netns {container} name {interface_name}'.format(
veth=random_veth,
container=name,
interface_name=interface_name
))
if not attached:
raise CommandExecutionError('Error while attaching the veth {veth} to container {container}'.format(
veth=random_veth,
container=name
))
__salt__['file.remove']('/var/run/netns/{0}'.format(name))
if bridge is not None:
__salt__['bridge.addif'](bridge, random_veth)
|
saltstack/salt
|
salt/modules/lxc.py
|
_clear_context
|
python
|
def _clear_context():
'''
Clear any lxc variables set in __context__
'''
for var in [x for x in __context__ if x.startswith('lxc.')]:
log.trace('Clearing __context__[\'%s\']', var)
__context__.pop(var, None)
|
Clear any lxc variables set in __context__
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/lxc.py#L135-L141
| null |
# -*- coding: utf-8 -*-
'''
Control Linux Containers via Salt
:depends: lxc package for distribution
lxc >= 1.0 (even beta alpha) is required
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import datetime
import copy
import string
import textwrap
import difflib
import logging
import tempfile
import os
import pipes
import time
import shutil
import re
import random
# Import salt libs
import salt.utils.args
import salt.utils.cloud
import salt.utils.data
import salt.utils.dictupdate
import salt.utils.files
import salt.utils.functools
import salt.utils.hashutils
import salt.utils.network
import salt.utils.odict
import salt.utils.path
import salt.utils.stringutils
from salt.exceptions import CommandExecutionError, SaltInvocationError
import salt.config
from salt.utils.versions import LooseVersion as _LooseVersion
# Import 3rd-party libs
from salt.ext import six
# pylint: disable=import-error,no-name-in-module
from salt.ext.six.moves import range # pylint: disable=redefined-builtin
from salt.ext.six.moves.urllib.parse import urlparse as _urlparse
# pylint: enable=import-error,no-name-in-module
# Set up logging
log = logging.getLogger(__name__)
# Don't shadow built-in's.
__func_alias__ = {
'list_': 'list',
'ls_': 'ls'
}
__virtualname__ = 'lxc'
DEFAULT_NIC = 'eth0'
DEFAULT_BR = 'br0'
SEED_MARKER = '/lxc.initial_seed'
EXEC_DRIVER = 'lxc-attach'
DEFAULT_PATH = '/var/lib/lxc'
_marker = object()
def __virtual__():
if salt.utils.path.which('lxc-start'):
return __virtualname__
# To speed up the whole thing, we decided to not use the
# subshell way and assume things are in place for lxc
# Discussion made by @kiorky and @thatch45
# lxc-version presence is not sufficient, in lxc1.0 alpha
# (precise backports), we have it and it is sufficient
# for the module to execute.
# elif salt.utils.path.which('lxc-version'):
# passed = False
# try:
# passed = subprocess.check_output(
# 'lxc-version').split(':')[1].strip() >= '1.0'
# except Exception:
# pass
# if not passed:
# log.warning('Support for lxc < 1.0 may be incomplete.')
# return 'lxc'
# return False
#
return (False, 'The lxc execution module cannot be loaded: the lxc-start binary is not in the path.')
def get_root_path(path):
'''
Get the configured lxc root for containers
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.get_root_path
'''
if not path:
path = __opts__.get('lxc.root_path', DEFAULT_PATH)
return path
def version():
'''
Return the actual lxc client version
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.version
'''
k = 'lxc.version'
if not __context__.get(k, None):
cversion = __salt__['cmd.run_all']('lxc-info --version')
if not cversion['retcode']:
ver = _LooseVersion(cversion['stdout'])
if ver < _LooseVersion('1.0'):
raise CommandExecutionError('LXC should be at least 1.0')
__context__[k] = "{0}".format(ver)
return __context__.get(k, None)
def _ip_sort(ip):
'''Ip sorting'''
idx = '001'
if ip == '127.0.0.1':
idx = '200'
if ip == '::1':
idx = '201'
elif '::' in ip:
idx = '100'
return '{0}___{1}'.format(idx, ip)
def search_lxc_bridges():
'''
Search which bridges are potentially available as LXC bridges
CLI Example:
.. code-block:: bash
salt '*' lxc.search_lxc_bridges
'''
bridges = __context__.get('lxc.bridges', None)
# either match not yet called or no bridges were found
# to handle the case where lxc was not installed on the first
# call
if not bridges:
bridges = set()
running_bridges = set()
bridges.add(DEFAULT_BR)
try:
output = __salt__['cmd.run_all']('brctl show')
for line in output['stdout'].splitlines()[1:]:
if not line.startswith(' '):
running_bridges.add(line.split()[0].strip())
except (SaltInvocationError, CommandExecutionError):
pass
for ifc, ip in six.iteritems(
__grains__.get('ip_interfaces', {})
):
if ifc in running_bridges:
bridges.add(ifc)
elif os.path.exists(
'/sys/devices/virtual/net/{0}/bridge'.format(ifc)
):
bridges.add(ifc)
bridges = list(bridges)
# if we found interfaces that have lxc in their names
# we filter them as being the potential lxc bridges
# we also try to default on br0 on other cases
def sort_bridges(a):
pref = 'z'
if 'lxc' in a:
pref = 'a'
elif 'br0' == a:
pref = 'c'
return '{0}_{1}'.format(pref, a)
bridges.sort(key=sort_bridges)
__context__['lxc.bridges'] = bridges
return bridges
def search_lxc_bridge():
'''
Search the first bridge which is potentially available as LXC bridge
CLI Example:
.. code-block:: bash
salt '*' lxc.search_lxc_bridge
'''
return search_lxc_bridges()[0]
def _get_salt_config(config, **kwargs):
if not config:
config = kwargs.get('minion', {})
if not config:
config = {}
config.setdefault('master',
kwargs.get('master',
__opts__.get('master',
__opts__['id'])))
config.setdefault(
'master_port',
kwargs.get('master_port',
__opts__.get('master_port',
__opts__.get('ret_port',
__opts__.get('4506')))))
if not config['master']:
config = {}
return config
def cloud_init_interface(name, vm_=None, **kwargs):
'''
Interface between salt.cloud.lxc driver and lxc.init
``vm_`` is a mapping of vm opts in the salt.cloud format
as documented for the lxc driver.
This can be used either:
- from the salt cloud driver
- because you find the argument to give easier here
than using directly lxc.init
.. warning::
BE REALLY CAREFUL CHANGING DEFAULTS !!!
IT'S A RETRO COMPATIBLE INTERFACE WITH
THE SALT CLOUD DRIVER (ask kiorky).
name
name of the lxc container to create
pub_key
public key to preseed the minion with.
Can be the keycontent or a filepath
priv_key
private key to preseed the minion with.
Can be the keycontent or a filepath
path
path to the container parent directory (default: /var/lib/lxc)
.. versionadded:: 2015.8.0
profile
:ref:`profile <tutorial-lxc-profiles-container>` selection
network_profile
:ref:`network profile <tutorial-lxc-profiles-network>` selection
nic_opts
per interface settings compatibles with
network profile (ipv4/ipv6/link/gateway/mac/netmask)
eg::
- {'eth0': {'mac': '00:16:3e:01:29:40',
'gateway': None, (default)
'link': 'br0', (default)
'gateway': None, (default)
'netmask': '', (default)
'ip': '22.1.4.25'}}
unconditional_install
given to lxc.bootstrap (see relative doc)
force_install
given to lxc.bootstrap (see relative doc)
config
any extra argument for the salt minion config
dnsservers
list of DNS servers to set inside the container
dns_via_dhcp
do not set the dns servers, let them be set by the dhcp.
autostart
autostart the container at boot time
password
administrative password for the container
bootstrap_delay
delay before launching bootstrap script at Container init
.. warning::
Legacy but still supported options:
from_container
which container we use as a template
when running lxc.clone
image
which template do we use when we
are using lxc.create. This is the default
mode unless you specify something in from_container
backing
which backing store to use.
Values can be: overlayfs, dir(default), lvm, zfs, brtfs
fstype
When using a blockdevice level backing store,
which filesystem to use on
size
When using a blockdevice level backing store,
which size for the filesystem to use on
snapshot
Use snapshot when cloning the container source
vgname
if using LVM: vgname
lvname
if using LVM: lvname
thinpool:
if using LVM: thinpool
ip
ip for the primary nic
mac
mac address for the primary nic
netmask
netmask for the primary nic (24)
= ``vm_.get('netmask', '24')``
bridge
bridge for the primary nic (lxcbr0)
gateway
network gateway for the container
additional_ips
additional ips which will be wired on the main bridge (br0)
which is connected to internet.
Be aware that you may use manual virtual mac addresses
providen by you provider (online, ovh, etc).
This is a list of mappings {ip: '', mac: '', netmask:''}
Set gateway to None and an interface with a gateway
to escape from another interface that eth0.
eg::
- {'mac': '00:16:3e:01:29:40',
'gateway': None, (default)
'link': 'br0', (default)
'netmask': '', (default)
'ip': '22.1.4.25'}
users
administrative users for the container
default: [root] and [root, ubuntu] on ubuntu
default_nic
name of the first interface, you should
really not override this
CLI Example:
.. code-block:: bash
salt '*' lxc.cloud_init_interface foo
'''
if vm_ is None:
vm_ = {}
vm_ = copy.deepcopy(vm_)
vm_ = salt.utils.dictupdate.update(vm_, kwargs)
profile_data = copy.deepcopy(
vm_.get('lxc_profile',
vm_.get('profile', {})))
if not isinstance(profile_data, (dict, six.string_types)):
profile_data = {}
profile = get_container_profile(profile_data)
def _cloud_get(k, default=None):
return vm_.get(k, profile.get(k, default))
if name is None:
name = vm_['name']
# if we are on ubuntu, default to ubuntu
default_template = ''
if __grains__.get('os', '') in ['Ubuntu']:
default_template = 'ubuntu'
image = _cloud_get('image')
if not image:
_cloud_get('template', default_template)
backing = _cloud_get('backing', 'dir')
if image:
profile['template'] = image
vgname = _cloud_get('vgname', None)
if vgname:
profile['vgname'] = vgname
if backing:
profile['backing'] = backing
snapshot = _cloud_get('snapshot', False)
autostart = bool(_cloud_get('autostart', True))
dnsservers = _cloud_get('dnsservers', [])
dns_via_dhcp = _cloud_get('dns_via_dhcp', True)
password = _cloud_get('password', 's3cr3t')
password_encrypted = _cloud_get('password_encrypted', False)
fstype = _cloud_get('fstype', None)
lvname = _cloud_get('lvname', None)
thinpool = _cloud_get('thinpool', None)
pub_key = _cloud_get('pub_key', None)
priv_key = _cloud_get('priv_key', None)
size = _cloud_get('size', '20G')
script = _cloud_get('script', None)
script_args = _cloud_get('script_args', None)
users = _cloud_get('users', None)
if users is None:
users = []
ssh_username = _cloud_get('ssh_username', None)
if ssh_username and (ssh_username not in users):
users.append(ssh_username)
network_profile = _cloud_get('network_profile', None)
nic_opts = kwargs.get('nic_opts', None)
netmask = _cloud_get('netmask', '24')
path = _cloud_get('path', None)
bridge = _cloud_get('bridge', None)
gateway = _cloud_get('gateway', None)
unconditional_install = _cloud_get('unconditional_install', False)
force_install = _cloud_get('force_install', True)
config = _get_salt_config(_cloud_get('config', {}), **vm_)
default_nic = _cloud_get('default_nic', DEFAULT_NIC)
# do the interface with lxc.init mainly via nic_opts
# to avoid extra and confusing extra use cases.
if not isinstance(nic_opts, dict):
nic_opts = salt.utils.odict.OrderedDict()
# have a reference to the default nic
eth0 = nic_opts.setdefault(default_nic,
salt.utils.odict.OrderedDict())
# lxc config is based of ifc order, be sure to use odicts.
if not isinstance(nic_opts, salt.utils.odict.OrderedDict):
bnic_opts = salt.utils.odict.OrderedDict()
bnic_opts.update(nic_opts)
nic_opts = bnic_opts
gw = None
# legacy salt.cloud scheme for network interfaces settings support
bridge = _cloud_get('bridge', None)
ip = _cloud_get('ip', None)
mac = _cloud_get('mac', None)
if ip:
fullip = ip
if netmask:
fullip += '/{0}'.format(netmask)
eth0['ipv4'] = fullip
if mac is not None:
eth0['mac'] = mac
for ix, iopts in enumerate(_cloud_get("additional_ips", [])):
ifh = "eth{0}".format(ix+1)
ethx = nic_opts.setdefault(ifh, {})
if gw is None:
gw = iopts.get('gateway', ethx.get('gateway', None))
if gw:
# only one and only one default gateway is allowed !
eth0.pop('gateway', None)
gateway = None
# even if the gateway if on default "eth0" nic
# and we popped it will work
# as we reinject or set it here.
ethx['gateway'] = gw
elink = iopts.get('link', ethx.get('link', None))
if elink:
ethx['link'] = elink
# allow dhcp
aip = iopts.get('ipv4', iopts.get('ip', None))
if aip:
ethx['ipv4'] = aip
nm = iopts.get('netmask', '')
if nm:
ethx['ipv4'] += '/{0}'.format(nm)
for i in ('mac', 'hwaddr'):
if i in iopts:
ethx['mac'] = iopts[i]
break
if 'mac' not in ethx:
ethx['mac'] = salt.utils.network.gen_mac()
# last round checking for unique gateway and such
gw = None
for ethx in [a for a in nic_opts]:
ndata = nic_opts[ethx]
if gw:
ndata.pop('gateway', None)
if 'gateway' in ndata:
gw = ndata['gateway']
gateway = None
# only use a default bridge / gateway if we configured them
# via the legacy salt cloud configuration style.
# On other cases, we should rely on settings provided by the new
# salt lxc network profile style configuration which can
# be also be overridden or a per interface basis via the nic_opts dict.
if bridge:
eth0['link'] = bridge
if gateway:
eth0['gateway'] = gateway
#
lxc_init_interface = {}
lxc_init_interface['name'] = name
lxc_init_interface['config'] = config
lxc_init_interface['memory'] = _cloud_get('memory', 0) # nolimit
lxc_init_interface['pub_key'] = pub_key
lxc_init_interface['priv_key'] = priv_key
lxc_init_interface['nic_opts'] = nic_opts
for clone_from in ['clone_from', 'clone', 'from_container']:
# clone_from should default to None if not available
lxc_init_interface['clone_from'] = _cloud_get(clone_from, None)
if lxc_init_interface['clone_from'] is not None:
break
lxc_init_interface['profile'] = profile
lxc_init_interface['snapshot'] = snapshot
lxc_init_interface['dnsservers'] = dnsservers
lxc_init_interface['fstype'] = fstype
lxc_init_interface['path'] = path
lxc_init_interface['vgname'] = vgname
lxc_init_interface['size'] = size
lxc_init_interface['lvname'] = lvname
lxc_init_interface['thinpool'] = thinpool
lxc_init_interface['force_install'] = force_install
lxc_init_interface['unconditional_install'] = (
unconditional_install
)
lxc_init_interface['bootstrap_url'] = script
lxc_init_interface['bootstrap_args'] = script_args
lxc_init_interface['bootstrap_shell'] = _cloud_get('bootstrap_shell', 'sh')
lxc_init_interface['bootstrap_delay'] = _cloud_get('bootstrap_delay', None)
lxc_init_interface['autostart'] = autostart
lxc_init_interface['users'] = users
lxc_init_interface['password'] = password
lxc_init_interface['password_encrypted'] = password_encrypted
# be sure not to let objects goes inside the return
# as this return will be msgpacked for use in the runner !
lxc_init_interface['network_profile'] = network_profile
for i in ['cpu', 'cpuset', 'cpushare']:
if _cloud_get(i, None):
try:
lxc_init_interface[i] = vm_[i]
except KeyError:
lxc_init_interface[i] = profile[i]
return lxc_init_interface
def _get_profile(key, name, **kwargs):
if isinstance(name, dict):
profilename = name.pop('name', None)
return _get_profile(key, profilename, **name)
if name is None:
profile_match = {}
else:
profile_match = \
__salt__['config.get'](
'lxc.{1}:{0}'.format(name, key),
default=None,
merge='recurse'
)
if profile_match is None:
# No matching profile, make the profile an empty dict so that
# overrides can be applied below.
profile_match = {}
if not isinstance(profile_match, dict):
raise CommandExecutionError('lxc.{0} must be a dictionary'.format(key))
# Overlay the kwargs to override matched profile data
overrides = salt.utils.args.clean_kwargs(**copy.deepcopy(kwargs))
profile_match = salt.utils.dictupdate.update(
copy.deepcopy(profile_match),
overrides
)
return profile_match
def get_container_profile(name=None, **kwargs):
'''
.. versionadded:: 2015.5.0
Gather a pre-configured set of container configuration parameters. If no
arguments are passed, an empty profile is returned.
Profiles can be defined in the minion or master config files, or in pillar
or grains, and are loaded using :mod:`config.get
<salt.modules.config.get>`. The key under which LXC profiles must be
configured is ``lxc.container_profile.profile_name``. An example container
profile would be as follows:
.. code-block:: yaml
lxc.container_profile:
ubuntu:
template: ubuntu
backing: lvm
vgname: lxc
size: 1G
Parameters set in a profile can be overridden by passing additional
container creation arguments (such as the ones passed to :mod:`lxc.create
<salt.modules.lxc.create>`) to this function.
A profile can be defined either as the name of the profile, or a dictionary
of variable names and values. See the :ref:`LXC Tutorial
<tutorial-lxc-profiles>` for more information on how to use LXC profiles.
CLI Example:
.. code-block:: bash
salt-call lxc.get_container_profile centos
salt-call lxc.get_container_profile ubuntu template=ubuntu backing=overlayfs
'''
profile = _get_profile('container_profile', name, **kwargs)
return profile
def get_network_profile(name=None, **kwargs):
'''
.. versionadded:: 2015.5.0
Gather a pre-configured set of network configuration parameters. If no
arguments are passed, the following default profile is returned:
.. code-block:: python
{'eth0': {'link': 'br0', 'type': 'veth', 'flags': 'up'}}
Profiles can be defined in the minion or master config files, or in pillar
or grains, and are loaded using :mod:`config.get
<salt.modules.config.get>`. The key under which LXC profiles must be
configured is ``lxc.network_profile``. An example network profile would be
as follows:
.. code-block:: yaml
lxc.network_profile.centos:
eth0:
link: br0
type: veth
flags: up
To disable networking entirely:
.. code-block:: yaml
lxc.network_profile.centos:
eth0:
disable: true
Parameters set in a profile can be overridden by passing additional
arguments to this function.
A profile can be passed either as the name of the profile, or a
dictionary of variable names and values. See the :ref:`LXC Tutorial
<tutorial-lxc-profiles>` for more information on how to use network
profiles.
.. warning::
The ``ipv4``, ``ipv6``, ``gateway``, and ``link`` (bridge) settings in
network profiles will only work if the container doesn't redefine the
network configuration (for example in
``/etc/sysconfig/network-scripts/ifcfg-<interface_name>`` on
RHEL/CentOS, or ``/etc/network/interfaces`` on Debian/Ubuntu/etc.)
CLI Example:
.. code-block:: bash
salt-call lxc.get_network_profile default
'''
profile = _get_profile('network_profile', name, **kwargs)
return profile
def _rand_cpu_str(cpu):
'''
Return a random subset of cpus for the cpuset config
'''
cpu = int(cpu)
avail = __salt__['status.nproc']()
if cpu < avail:
return '0-{0}'.format(avail)
to_set = set()
while len(to_set) < cpu:
choice = random.randint(0, avail - 1)
if choice not in to_set:
to_set.add(six.text_type(choice))
return ','.join(sorted(to_set))
def _network_conf(conf_tuples=None, **kwargs):
'''
Network configuration defaults
network_profile
as for containers, we can either call this function
either with a network_profile dict or network profile name
in the kwargs
nic_opts
overrides or extra nics in the form {nic_name: {set: tings}
'''
nic = kwargs.get('network_profile', None)
ret = []
nic_opts = kwargs.get('nic_opts', {})
if nic_opts is None:
# coming from elsewhere
nic_opts = {}
if not conf_tuples:
conf_tuples = []
old = _get_veths(conf_tuples)
if not old:
old = {}
# if we have a profile name, get the profile and load the network settings
# this will obviously by default look for a profile called "eth0"
# or by what is defined in nic_opts
# and complete each nic settings by sane defaults
if nic and isinstance(nic, (six.string_types, dict)):
nicp = get_network_profile(nic)
else:
nicp = {}
if DEFAULT_NIC not in nicp:
nicp[DEFAULT_NIC] = {}
kwargs = copy.deepcopy(kwargs)
gateway = kwargs.pop('gateway', None)
bridge = kwargs.get('bridge', None)
if nic_opts:
for dev, args in six.iteritems(nic_opts):
ethx = nicp.setdefault(dev, {})
try:
ethx = salt.utils.dictupdate.update(ethx, args)
except AttributeError:
raise SaltInvocationError('Invalid nic_opts configuration')
ifs = [a for a in nicp]
ifs += [a for a in old if a not in nicp]
ifs.sort()
gateway_set = False
for dev in ifs:
args = nicp.get(dev, {})
opts = nic_opts.get(dev, {}) if nic_opts else {}
old_if = old.get(dev, {})
disable = opts.get('disable', args.get('disable', False))
if disable:
continue
mac = opts.get('mac',
opts.get('hwaddr',
args.get('mac',
args.get('hwaddr', ''))))
type_ = opts.get('type', args.get('type', ''))
flags = opts.get('flags', args.get('flags', ''))
link = opts.get('link', args.get('link', ''))
ipv4 = opts.get('ipv4', args.get('ipv4', ''))
ipv6 = opts.get('ipv6', args.get('ipv6', ''))
infos = salt.utils.odict.OrderedDict([
('lxc.network.type', {
'test': not type_,
'value': type_,
'old': old_if.get('lxc.network.type'),
'default': 'veth'}),
('lxc.network.name', {
'test': False,
'value': dev,
'old': dev,
'default': dev}),
('lxc.network.flags', {
'test': not flags,
'value': flags,
'old': old_if.get('lxc.network.flags'),
'default': 'up'}),
('lxc.network.link', {
'test': not link,
'value': link,
'old': old_if.get('lxc.network.link'),
'default': search_lxc_bridge()}),
('lxc.network.hwaddr', {
'test': not mac,
'value': mac,
'old': old_if.get('lxc.network.hwaddr'),
'default': salt.utils.network.gen_mac()}),
('lxc.network.ipv4', {
'test': not ipv4,
'value': ipv4,
'old': old_if.get('lxc.network.ipv4', ''),
'default': None}),
('lxc.network.ipv6', {
'test': not ipv6,
'value': ipv6,
'old': old_if.get('lxc.network.ipv6', ''),
'default': None})])
# for each parameter, if not explicitly set, the
# config value present in the LXC configuration should
# take precedence over the profile configuration
for info in list(infos.keys()):
bundle = infos[info]
if bundle['test']:
if bundle['old']:
bundle['value'] = bundle['old']
elif bundle['default']:
bundle['value'] = bundle['default']
for info, data in six.iteritems(infos):
if data['value']:
ret.append({info: data['value']})
for key, val in six.iteritems(args):
if key == 'link' and bridge:
val = bridge
val = opts.get(key, val)
if key in [
'type', 'flags', 'name',
'gateway', 'mac', 'link', 'ipv4', 'ipv6'
]:
continue
ret.append({'lxc.network.{0}'.format(key): val})
# gateway (in automode) must be appended following network conf !
if not gateway:
gateway = args.get('gateway', None)
if gateway is not None and not gateway_set:
ret.append({'lxc.network.ipv4.gateway': gateway})
# only one network gateway ;)
gateway_set = True
# normally, this won't happen
# set the gateway if specified even if we did
# not managed the network underlying
if gateway is not None and not gateway_set:
ret.append({'lxc.network.ipv4.gateway': gateway})
# only one network gateway ;)
gateway_set = True
new = _get_veths(ret)
# verify that we did not loose the mac settings
for iface in [a for a in new]:
ndata = new[iface]
nmac = ndata.get('lxc.network.hwaddr', '')
ntype = ndata.get('lxc.network.type', '')
omac, otype = '', ''
if iface in old:
odata = old[iface]
omac = odata.get('lxc.network.hwaddr', '')
otype = odata.get('lxc.network.type', '')
# default for network type is setted here
# attention not to change the network type
# without a good and explicit reason to.
if otype and not ntype:
ntype = otype
if not ntype:
ntype = 'veth'
new[iface]['lxc.network.type'] = ntype
if omac and not nmac:
new[iface]['lxc.network.hwaddr'] = omac
ret = []
for val in six.itervalues(new):
for row in val:
ret.append(salt.utils.odict.OrderedDict([(row, val[row])]))
# on old versions of lxc, still support the gateway auto mode
# if we didn't explicitly say no to
# (lxc.network.ipv4.gateway: auto)
if _LooseVersion(version()) <= _LooseVersion('1.0.7') and \
True not in ['lxc.network.ipv4.gateway' in a for a in ret] and \
True in ['lxc.network.ipv4' in a for a in ret]:
ret.append({'lxc.network.ipv4.gateway': 'auto'})
return ret
def _get_lxc_default_data(**kwargs):
kwargs = copy.deepcopy(kwargs)
ret = {}
for k in ['utsname', 'rootfs']:
val = kwargs.get(k, None)
if val is not None:
ret['lxc.{0}'.format(k)] = val
autostart = kwargs.get('autostart')
# autostart can have made in kwargs, but with the None
# value which is invalid, we need an explicit boolean
# autostart = on is the default.
if autostart is None:
autostart = True
# we will set the regular lxc marker to restart container at
# machine (re)boot only if we did not explicitly ask
# not to touch to the autostart settings via
# autostart == 'keep'
if autostart != 'keep':
if autostart:
ret['lxc.start.auto'] = '1'
else:
ret['lxc.start.auto'] = '0'
memory = kwargs.get('memory')
if memory is not None:
# converting the config value from MB to bytes
ret['lxc.cgroup.memory.limit_in_bytes'] = memory * 1024 * 1024
cpuset = kwargs.get('cpuset')
if cpuset:
ret['lxc.cgroup.cpuset.cpus'] = cpuset
cpushare = kwargs.get('cpushare')
cpu = kwargs.get('cpu')
if cpushare:
ret['lxc.cgroup.cpu.shares'] = cpushare
if cpu and not cpuset:
ret['lxc.cgroup.cpuset.cpus'] = _rand_cpu_str(cpu)
return ret
def _config_list(conf_tuples=None, only_net=False, **kwargs):
'''
Return a list of dicts from the salt level configurations
conf_tuples
_LXCConfig compatible list of entries which can contain
- string line
- tuple (lxc config param,value)
- dict of one entry: {lxc config param: value)
only_net
by default we add to the tuples a reflection of both
the real config if avalaible and a certain amount of
default values like the cpu parameters, the memory
and etc.
On the other hand, we also no matter the case reflect
the network configuration computed from the actual config if
available and given values.
if no_default_loads is set, we will only
reflect the network configuration back to the conf tuples
list
'''
# explicit cast
only_net = bool(only_net)
if not conf_tuples:
conf_tuples = []
kwargs = copy.deepcopy(kwargs)
ret = []
if not only_net:
default_data = _get_lxc_default_data(**kwargs)
for k, val in six.iteritems(default_data):
ret.append({k: val})
net_datas = _network_conf(conf_tuples=conf_tuples, **kwargs)
ret.extend(net_datas)
return ret
def _get_veths(net_data):
'''
Parse the nic setup inside lxc conf tuples back to a dictionary indexed by
network interface
'''
if isinstance(net_data, dict):
net_data = list(net_data.items())
nics = salt.utils.odict.OrderedDict()
current_nic = salt.utils.odict.OrderedDict()
no_names = True
for item in net_data:
if item and isinstance(item, dict):
item = list(item.items())[0]
# skip LXC configuration comment lines, and play only with tuples conf
elif isinstance(item, six.string_types):
# deal with reflection of commented lxc configs
sitem = item.strip()
if sitem.startswith('#') or not sitem:
continue
elif '=' in item:
item = tuple([a.strip() for a in item.split('=', 1)])
if item[0] == 'lxc.network.type':
current_nic = salt.utils.odict.OrderedDict()
if item[0] == 'lxc.network.name':
no_names = False
nics[item[1].strip()] = current_nic
current_nic[item[0].strip()] = item[1].strip()
# if not ethernet card name has been collected, assuming we collected
# data for eth0
if no_names and current_nic:
nics[DEFAULT_NIC] = current_nic
return nics
class _LXCConfig(object):
'''
LXC configuration data
'''
pattern = re.compile(r'^(\S+)(\s*)(=)(\s*)(.*)')
non_interpretable_pattern = re.compile(r'^((#.*)|(\s*))$')
def __init__(self, **kwargs):
kwargs = copy.deepcopy(kwargs)
self.name = kwargs.pop('name', None)
path = get_root_path(kwargs.get('path', None))
self.data = []
if self.name:
self.path = os.path.join(path, self.name, 'config')
if os.path.isfile(self.path):
with salt.utils.files.fopen(self.path) as fhr:
for line in salt.utils.data.decode(fhr.readlines()):
match = self.pattern.findall((line.strip()))
if match:
self.data.append((match[0][0], match[0][-1]))
match = self.non_interpretable_pattern.findall(
(line.strip()))
if match:
self.data.append(('', match[0][0]))
else:
self.path = None
def _replace(key, val):
if val:
self._filter_data(key)
self.data.append((key, val))
default_data = _get_lxc_default_data(**kwargs)
for key, val in six.iteritems(default_data):
_replace(key, val)
old_net = self._filter_data('lxc.network')
net_datas = _network_conf(conf_tuples=old_net, **kwargs)
if net_datas:
for row in net_datas:
self.data.extend(list(row.items()))
# be sure to reset harmful settings
for idx in ['lxc.cgroup.memory.limit_in_bytes']:
if not default_data.get(idx):
self._filter_data(idx)
def as_string(self):
chunks = ('{0[0]}{1}{0[1]}'.format(item, (' = ' if item[0] else '')) for item in self.data)
return '\n'.join(chunks) + '\n'
def write(self):
if self.path:
content = self.as_string()
# 2 step rendering to be sure not to open/wipe the config
# before as_string succeeds.
with salt.utils.files.fopen(self.path, 'w') as fic:
fic.write(salt.utils.stringutils.to_str(content))
fic.flush()
def tempfile(self):
# this might look like the function name is shadowing the
# module, but it's not since the method belongs to the class
ntf = tempfile.NamedTemporaryFile()
ntf.write(self.as_string())
ntf.flush()
return ntf
def _filter_data(self, pattern):
'''
Removes parameters which match the pattern from the config data
'''
removed = []
filtered = []
for param in self.data:
if not param[0].startswith(pattern):
filtered.append(param)
else:
removed.append(param)
self.data = filtered
return removed
def _get_base(**kwargs):
'''
If the needed base does not exist, then create it, if it does exist
create nothing and return the name of the base lxc container so
it can be cloned.
'''
profile = get_container_profile(copy.deepcopy(kwargs.get('profile')))
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, _marker)
profile_match = profile.pop(key, default)
# let kwarg overrides be the preferred choice
if kw_overrides_match is _marker:
return profile_match
return kw_overrides_match
template = select('template')
image = select('image')
vgname = select('vgname')
path = kwargs.get('path', None)
# remove the above three variables from kwargs, if they exist, to avoid
# duplicates if create() is invoked below.
for param in ('path', 'image', 'vgname', 'template'):
kwargs.pop(param, None)
if image:
proto = _urlparse(image).scheme
img_tar = __salt__['cp.cache_file'](image)
img_name = os.path.basename(img_tar)
hash_ = salt.utils.hashutils.get_hash(
img_tar,
__salt__['config.get']('hash_type'))
name = '__base_{0}_{1}_{2}'.format(proto, img_name, hash_)
if not exists(name, path=path):
create(name, template=template, image=image,
path=path, vgname=vgname, **kwargs)
if vgname:
rootfs = os.path.join('/dev', vgname, name)
edit_conf(info(name, path=path)['config'],
out_format='commented', **{'lxc.rootfs': rootfs})
return name
elif template:
name = '__base_{0}'.format(template)
if not exists(name, path=path):
create(name, template=template, image=image, path=path,
vgname=vgname, **kwargs)
if vgname:
rootfs = os.path.join('/dev', vgname, name)
edit_conf(info(name, path=path)['config'],
out_format='commented', **{'lxc.rootfs': rootfs})
return name
return ''
def init(name,
config=None,
cpuset=None,
cpushare=None,
memory=None,
profile=None,
network_profile=None,
nic_opts=None,
cpu=None,
autostart=True,
password=None,
password_encrypted=None,
users=None,
dnsservers=None,
searchdomains=None,
bridge=None,
gateway=None,
pub_key=None,
priv_key=None,
force_install=False,
unconditional_install=False,
bootstrap_delay=None,
bootstrap_args=None,
bootstrap_shell=None,
bootstrap_url=None,
**kwargs):
'''
Initialize a new container.
This is a partial idempotent function as if it is already provisioned, we
will reset a bit the lxc configuration file but much of the hard work will
be escaped as markers will prevent re-execution of harmful tasks.
name
Name of the container
image
A tar archive to use as the rootfs for the container. Conflicts with
the ``template`` argument.
cpus
Select a random number of cpu cores and assign it to the cpuset, if the
cpuset option is set then this option will be ignored
cpuset
Explicitly define the cpus this container will be bound to
cpushare
cgroups cpu shares
autostart
autostart container on reboot
memory
cgroups memory limit, in MB
.. versionchanged:: 2015.5.0
If no value is passed, no limit is set. In earlier Salt versions,
not passing this value causes a 1024MB memory limit to be set, and
it was necessary to pass ``memory=0`` to set no limit.
gateway
the ipv4 gateway to use
the default does nothing more than lxcutils does
bridge
the bridge to use
the default does nothing more than lxcutils does
network_profile
Network profile to use for the container
.. versionadded:: 2015.5.0
nic_opts
Extra options for network interfaces, will override
``{"eth0": {"hwaddr": "aa:bb:cc:dd:ee:ff", "ipv4": "10.1.1.1", "ipv6": "2001:db8::ff00:42:8329"}}``
or
``{"eth0": {"hwaddr": "aa:bb:cc:dd:ee:ff", "ipv4": "10.1.1.1/24", "ipv6": "2001:db8::ff00:42:8329"}}``
users
Users for which the password defined in the ``password`` param should
be set. Can be passed as a comma separated list or a python list.
Defaults to just the ``root`` user.
password
Set the initial password for the users defined in the ``users``
parameter
password_encrypted : False
Set to ``True`` to denote a password hash instead of a plaintext
password
.. versionadded:: 2015.5.0
profile
A LXC profile (defined in config or pillar).
This can be either a real profile mapping or a string
to retrieve it in configuration
start
Start the newly-created container
dnsservers
list of dns servers to set in the container, default [] (no setting)
seed
Seed the container with the minion config. Default: ``True``
install
If salt-minion is not already installed, install it. Default: ``True``
config
Optional config parameters. By default, the id is set to
the name of the container.
master
salt master (default to minion's master)
master_port
salt master port (default to minion's master port)
pub_key
Explicit public key to preseed the minion with (optional).
This can be either a filepath or a string representing the key
priv_key
Explicit private key to preseed the minion with (optional).
This can be either a filepath or a string representing the key
approve_key
If explicit preseeding is not used;
Attempt to request key approval from the master. Default: ``True``
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
clone_from
Original from which to use a clone operation to create the container.
Default: ``None``
bootstrap_delay
Delay in seconds between end of container creation and bootstrapping.
Useful when waiting for container to obtain a DHCP lease.
.. versionadded:: 2015.5.0
bootstrap_url
See lxc.bootstrap
bootstrap_shell
See lxc.bootstrap
bootstrap_args
See lxc.bootstrap
force_install
Force installation even if salt-minion is detected,
this is the way to run vendor bootstrap scripts even
if a salt minion is already present in the container
unconditional_install
Run the script even if the container seems seeded
CLI Example:
.. code-block:: bash
salt 'minion' lxc.init name [cpuset=cgroups_cpuset] \\
[cpushare=cgroups_cpushare] [memory=cgroups_memory] \\
[nic=nic_profile] [profile=lxc_profile] \\
[nic_opts=nic_opts] [start=(True|False)] \\
[seed=(True|False)] [install=(True|False)] \\
[config=minion_config] [approve_key=(True|False) \\
[clone_from=original] [autostart=True] \\
[priv_key=/path_or_content] [pub_key=/path_or_content] \\
[bridge=lxcbr0] [gateway=10.0.3.1] \\
[dnsservers[dns1,dns2]] \\
[users=[foo]] [password='secret'] \\
[password_encrypted=(True|False)]
'''
ret = {'name': name,
'changes': {}}
profile = get_container_profile(copy.deepcopy(profile))
if not network_profile:
network_profile = profile.get('network_profile')
if not network_profile:
network_profile = DEFAULT_NIC
# Changes is a pointer to changes_dict['init']. This method is used so that
# we can have a list of changes as they are made, providing an ordered list
# of things that were changed.
changes_dict = {'init': []}
changes = changes_dict.get('init')
if users is None:
users = []
dusers = ['root']
for user in dusers:
if user not in users:
users.append(user)
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, _marker)
profile_match = profile.pop(key, default)
# let kwarg overrides be the preferred choice
if kw_overrides_match is _marker:
return profile_match
return kw_overrides_match
path = select('path')
bpath = get_root_path(path)
state_pre = state(name, path=path)
tvg = select('vgname')
vgname = tvg if tvg else __salt__['config.get']('lxc.vgname')
start_ = select('start', True)
autostart = select('autostart', autostart)
seed = select('seed', True)
install = select('install', True)
seed_cmd = select('seed_cmd')
salt_config = _get_salt_config(config, **kwargs)
approve_key = select('approve_key', True)
clone_from = select('clone_from')
# If using a volume group then set up to make snapshot cow clones
if vgname and not clone_from:
try:
kwargs['vgname'] = vgname
clone_from = _get_base(profile=profile, **kwargs)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = exc.strerror
if changes:
ret['changes'] = changes_dict
return ret
if not kwargs.get('snapshot') is False:
kwargs['snapshot'] = True
does_exist = exists(name, path=path)
to_reboot = False
remove_seed_marker = False
if does_exist:
pass
elif clone_from:
remove_seed_marker = True
try:
clone(name, clone_from, profile=profile, **kwargs)
changes.append({'create': 'Container cloned'})
except (SaltInvocationError, CommandExecutionError) as exc:
if 'already exists' in exc.strerror:
changes.append({'create': 'Container already exists'})
else:
ret['result'] = False
ret['comment'] = exc.strerror
if changes:
ret['changes'] = changes_dict
return ret
cfg = _LXCConfig(name=name, network_profile=network_profile,
nic_opts=nic_opts, bridge=bridge, path=path,
gateway=gateway, autostart=autostart,
cpuset=cpuset, cpushare=cpushare, memory=memory)
old_chunks = read_conf(cfg.path, out_format='commented')
cfg.write()
chunks = read_conf(cfg.path, out_format='commented')
if old_chunks != chunks:
to_reboot = True
else:
remove_seed_marker = True
cfg = _LXCConfig(network_profile=network_profile,
nic_opts=nic_opts, cpuset=cpuset, path=path,
bridge=bridge, gateway=gateway,
autostart=autostart,
cpushare=cpushare, memory=memory)
with cfg.tempfile() as cfile:
try:
create(name, config=cfile.name, profile=profile, **kwargs)
changes.append({'create': 'Container created'})
except (SaltInvocationError, CommandExecutionError) as exc:
if 'already exists' in exc.strerror:
changes.append({'create': 'Container already exists'})
else:
ret['comment'] = exc.strerror
if changes:
ret['changes'] = changes_dict
return ret
cpath = os.path.join(bpath, name, 'config')
old_chunks = []
if os.path.exists(cpath):
old_chunks = read_conf(cpath, out_format='commented')
new_cfg = _config_list(conf_tuples=old_chunks,
cpu=cpu,
network_profile=network_profile,
nic_opts=nic_opts, bridge=bridge,
cpuset=cpuset, cpushare=cpushare,
memory=memory)
if new_cfg:
edit_conf(cpath, out_format='commented', lxc_config=new_cfg)
chunks = read_conf(cpath, out_format='commented')
if old_chunks != chunks:
to_reboot = True
# last time to be sure any of our property is correctly applied
cfg = _LXCConfig(name=name, network_profile=network_profile,
nic_opts=nic_opts, bridge=bridge, path=path,
gateway=gateway, autostart=autostart,
cpuset=cpuset, cpushare=cpushare, memory=memory)
old_chunks = []
if os.path.exists(cfg.path):
old_chunks = read_conf(cfg.path, out_format='commented')
cfg.write()
chunks = read_conf(cfg.path, out_format='commented')
if old_chunks != chunks:
changes.append({'config': 'Container configuration updated'})
to_reboot = True
if to_reboot:
try:
stop(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
if changes:
ret['changes'] = changes_dict
return ret
if not does_exist or (does_exist and state(name, path=path) != 'running'):
try:
start(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
if changes:
ret['changes'] = changes_dict
return ret
if remove_seed_marker:
run(name,
'rm -f \'{0}\''.format(SEED_MARKER),
path=path,
chroot_fallback=False,
python_shell=False)
# set the default user/password, only the first time
if ret.get('result', True) and password:
gid = '/.lxc.initial_pass'
gids = [gid,
'/lxc.initial_pass',
'/.lxc.{0}.initial_pass'.format(name)]
if not any(retcode(name,
'test -e "{0}"'.format(x),
chroot_fallback=True,
path=path,
ignore_retcode=True) == 0
for x in gids):
# think to touch the default user generated by default templates
# which has a really unsecure passwords...
# root is defined as a member earlier in the code
for default_user in ['ubuntu']:
if (
default_user not in users and
retcode(name,
'id {0}'.format(default_user),
python_shell=False,
path=path,
chroot_fallback=True,
ignore_retcode=True) == 0
):
users.append(default_user)
for user in users:
try:
cret = set_password(name,
users=[user],
path=path,
password=password,
encrypted=password_encrypted)
except (SaltInvocationError, CommandExecutionError) as exc:
msg = '{0}: Failed to set password'.format(
user) + exc.strerror
# only hardfail in unrecoverable situation:
# root cannot be setted up
if user == 'root':
ret['comment'] = msg
ret['result'] = False
else:
log.debug(msg)
if ret.get('result', True):
changes.append({'password': 'Password(s) updated'})
if retcode(name,
('sh -c \'touch "{0}"; test -e "{0}"\''
.format(gid)),
path=path,
chroot_fallback=True,
ignore_retcode=True) != 0:
ret['comment'] = 'Failed to set password marker'
changes[-1]['password'] += '. ' + ret['comment'] + '.'
ret['result'] = False
# set dns servers if any, only the first time
if ret.get('result', True) and dnsservers:
# retro compatibility, test also old markers
gid = '/.lxc.initial_dns'
gids = [gid,
'/lxc.initial_dns',
'/lxc.{0}.initial_dns'.format(name)]
if not any(retcode(name,
'test -e "{0}"'.format(x),
chroot_fallback=True,
path=path,
ignore_retcode=True) == 0
for x in gids):
try:
set_dns(name,
path=path,
dnsservers=dnsservers,
searchdomains=searchdomains)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Failed to set DNS: ' + exc.strerror
ret['result'] = False
else:
changes.append({'dns': 'DNS updated'})
if retcode(name,
('sh -c \'touch "{0}"; test -e "{0}"\''
.format(gid)),
chroot_fallback=True,
path=path,
ignore_retcode=True) != 0:
ret['comment'] = 'Failed to set DNS marker'
changes[-1]['dns'] += '. ' + ret['comment'] + '.'
ret['result'] = False
# retro compatibility, test also old markers
if remove_seed_marker:
run(name,
'rm -f \'{0}\''.format(SEED_MARKER),
path=path,
python_shell=False)
gid = '/.lxc.initial_seed'
gids = [gid, '/lxc.initial_seed']
if (
any(retcode(name,
'test -e {0}'.format(x),
path=path,
chroot_fallback=True,
ignore_retcode=True) == 0
for x in gids) or not ret.get('result', True)
):
pass
elif seed or seed_cmd:
if seed:
try:
result = bootstrap(
name, config=salt_config, path=path,
approve_key=approve_key,
pub_key=pub_key, priv_key=priv_key,
install=install,
force_install=force_install,
unconditional_install=unconditional_install,
bootstrap_delay=bootstrap_delay,
bootstrap_url=bootstrap_url,
bootstrap_shell=bootstrap_shell,
bootstrap_args=bootstrap_args)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Bootstrap failed: ' + exc.strerror
ret['result'] = False
else:
if not result:
ret['comment'] = ('Bootstrap failed, see minion log for '
'more information')
ret['result'] = False
else:
changes.append(
{'bootstrap': 'Container successfully bootstrapped'}
)
elif seed_cmd:
try:
result = __salt__[seed_cmd](info(name, path=path)['rootfs'],
name,
salt_config)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = ('Bootstrap via seed_cmd \'{0}\' failed: {1}'
.format(seed_cmd, exc.strerror))
ret['result'] = False
else:
if not result:
ret['comment'] = ('Bootstrap via seed_cmd \'{0}\' failed, '
'see minion log for more information '
.format(seed_cmd))
ret['result'] = False
else:
changes.append(
{'bootstrap': 'Container successfully bootstrapped '
'using seed_cmd \'{0}\''
.format(seed_cmd)}
)
if ret.get('result', True) and not start_:
try:
stop(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
ret['result'] = False
state_post = state(name, path=path)
if state_pre != state_post:
changes.append({'state': {'old': state_pre, 'new': state_post}})
if ret.get('result', True):
ret['comment'] = ('Container \'{0}\' successfully initialized'
.format(name))
ret['result'] = True
if changes:
ret['changes'] = changes_dict
return ret
def cloud_init(name, vm_=None, **kwargs):
'''
Thin wrapper to lxc.init to be used from the saltcloud lxc driver
name
Name of the container
may be None and then guessed from saltcloud mapping
`vm_`
saltcloud mapping defaults for the vm
CLI Example:
.. code-block:: bash
salt '*' lxc.cloud_init foo
'''
init_interface = cloud_init_interface(name, vm_, **kwargs)
name = init_interface.pop('name', name)
return init(name, **init_interface)
def images(dist=None):
'''
.. versionadded:: 2015.5.0
List the available images for LXC's ``download`` template.
dist : None
Filter results to a single Linux distribution
CLI Examples:
.. code-block:: bash
salt myminion lxc.images
salt myminion lxc.images dist=centos
'''
out = __salt__['cmd.run_stdout'](
'lxc-create -n __imgcheck -t download -- --list',
ignore_retcode=True
)
if 'DIST' not in out:
raise CommandExecutionError(
'Unable to run the \'download\' template script. Is it installed?'
)
ret = {}
passed_header = False
for line in out.splitlines():
try:
distro, release, arch, variant, build_time = line.split()
except ValueError:
continue
if not passed_header:
if distro == 'DIST':
passed_header = True
continue
dist_list = ret.setdefault(distro, [])
dist_list.append({
'release': release,
'arch': arch,
'variant': variant,
'build_time': build_time,
})
if dist is not None:
return dict([(dist, ret.get(dist, []))])
return ret
def templates():
'''
.. versionadded:: 2015.5.0
List the available LXC template scripts installed on the minion
CLI Examples:
.. code-block:: bash
salt myminion lxc.templates
'''
try:
template_scripts = os.listdir('/usr/share/lxc/templates')
except OSError:
return []
else:
return [x[4:] for x in template_scripts if x.startswith('lxc-')]
def _after_ignition_network_profile(cmd,
ret,
name,
network_profile,
path,
nic_opts):
_clear_context()
if ret['retcode'] == 0 and exists(name, path=path):
if network_profile:
network_changes = apply_network_profile(name,
network_profile,
path=path,
nic_opts=nic_opts)
if network_changes:
log.info(
'Network changes from applying network profile \'%s\' '
'to newly-created container \'%s\':\n%s',
network_profile, name, network_changes
)
c_state = state(name, path=path)
return {'result': True,
'state': {'old': None, 'new': c_state}}
else:
if exists(name, path=path):
# destroy the container if it was partially created
cmd = 'lxc-destroy'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0}'.format(name)
__salt__['cmd.retcode'](cmd, python_shell=False)
raise CommandExecutionError(
'Container could not be created with cmd \'{0}\': {1}'
.format(cmd, ret['stderr'])
)
def create(name,
config=None,
profile=None,
network_profile=None,
nic_opts=None,
**kwargs):
'''
Create a new container.
name
Name of the container
config
The config file to use for the container. Defaults to system-wide
config (usually in /etc/lxc/lxc.conf).
profile
Profile to use in container creation (see
:mod:`lxc.get_container_profile
<salt.modules.lxc.get_container_profile>`). Values in a profile will be
overridden by the **Container Creation Arguments** listed below.
network_profile
Network profile to use for container
.. versionadded:: 2015.5.0
**Container Creation Arguments**
template
The template to use. For example, ``ubuntu`` or ``fedora``.
For a full list of available templates, check out
the :mod:`lxc.templates <salt.modules.lxc.templates>` function.
Conflicts with the ``image`` argument.
.. note::
The ``download`` template requires the following three parameters
to be defined in ``options``:
* **dist** - The name of the distribution
* **release** - Release name/version
* **arch** - Architecture of the container
The available images can be listed using the :mod:`lxc.images
<salt.modules.lxc.images>` function.
options
Template-specific options to pass to the lxc-create command. These
correspond to the long options (ones beginning with two dashes) that
the template script accepts. For example:
.. code-block:: bash
options='{"dist": "centos", "release": "6", "arch": "amd64"}'
For available template options, refer to the lxc template scripts
which are ususally located under ``/usr/share/lxc/templates``,
or run ``lxc-create -t <template> -h``.
image
A tar archive to use as the rootfs for the container. Conflicts with
the ``template`` argument.
backing
The type of storage to use. Set to ``lvm`` to use an LVM group.
Defaults to filesystem within /var/lib/lxc.
fstype
Filesystem type to use on LVM logical volume
size : 1G
Size of the volume to create. Only applicable if ``backing=lvm``.
vgname : lxc
Name of the LVM volume group in which to create the volume for this
container. Only applicable if ``backing=lvm``.
lvname
Name of the LVM logical volume in which to create the volume for this
container. Only applicable if ``backing=lvm``.
thinpool
Name of a pool volume that will be used for thin-provisioning this
container. Only applicable if ``backing=lvm``.
nic_opts
give extra opts overriding network profile values
path
parent path for the container creation (default: /var/lib/lxc)
zfsroot
Name of the ZFS root in which to create the volume for this container.
Only applicable if ``backing=zfs``. (default: tank/lxc)
.. versionadded:: 2015.8.0
'''
# Required params for 'download' template
download_template_deps = ('dist', 'release', 'arch')
cmd = 'lxc-create -n {0}'.format(name)
profile = get_container_profile(copy.deepcopy(profile))
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, None)
profile_match = profile.pop(key, default)
# Return the profile match if the the kwarg match was None, as the
# lxc.present state will pass these kwargs set to None by default.
if kw_overrides_match is None:
return profile_match
return kw_overrides_match
path = select('path')
if exists(name, path=path):
raise CommandExecutionError(
'Container \'{0}\' already exists'.format(name)
)
tvg = select('vgname')
vgname = tvg if tvg else __salt__['config.get']('lxc.vgname')
# The 'template' and 'image' params conflict
template = select('template')
image = select('image')
if template and image:
raise SaltInvocationError(
'Only one of \'template\' and \'image\' is permitted'
)
elif not any((template, image, profile)):
raise SaltInvocationError(
'At least one of \'template\', \'image\', and \'profile\' is '
'required'
)
options = select('options') or {}
backing = select('backing')
if vgname and not backing:
backing = 'lvm'
lvname = select('lvname')
thinpool = select('thinpool')
fstype = select('fstype')
size = select('size', '1G')
zfsroot = select('zfsroot')
if backing in ('dir', 'overlayfs', 'btrfs', 'zfs'):
fstype = None
size = None
# some backends won't support some parameters
if backing in ('aufs', 'dir', 'overlayfs', 'btrfs'):
lvname = vgname = thinpool = None
if image:
img_tar = __salt__['cp.cache_file'](image)
template = os.path.join(
os.path.dirname(salt.__file__),
'templates',
'lxc',
'salt_tarball')
options['imgtar'] = img_tar
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
if not os.path.exists(path):
os.makedirs(path)
if config:
cmd += ' -f {0}'.format(config)
if template:
cmd += ' -t {0}'.format(template)
if backing:
backing = backing.lower()
cmd += ' -B {0}'.format(backing)
if backing in ('zfs',):
if zfsroot:
cmd += ' --zfsroot {0}'.format(zfsroot)
if backing in ('lvm',):
if lvname:
cmd += ' --lvname {0}'.format(lvname)
if vgname:
cmd += ' --vgname {0}'.format(vgname)
if thinpool:
cmd += ' --thinpool {0}'.format(thinpool)
if backing not in ('dir', 'overlayfs'):
if fstype:
cmd += ' --fstype {0}'.format(fstype)
if size:
cmd += ' --fssize {0}'.format(size)
if options:
if template == 'download':
missing_deps = [x for x in download_template_deps
if x not in options]
if missing_deps:
raise SaltInvocationError(
'Missing params in \'options\' dict: {0}'
.format(', '.join(missing_deps))
)
cmd += ' --'
for key, val in six.iteritems(options):
cmd += ' --{0} {1}'.format(key, val)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
# please do not merge extra conflicting stuff
# inside those two line (ret =, return)
return _after_ignition_network_profile(cmd,
ret,
name,
network_profile,
path,
nic_opts)
def clone(name,
orig,
profile=None,
network_profile=None,
nic_opts=None,
**kwargs):
'''
Create a new container as a clone of another container
name
Name of the container
orig
Name of the original container to be cloned
profile
Profile to use in container cloning (see
:mod:`lxc.get_container_profile
<salt.modules.lxc.get_container_profile>`). Values in a profile will be
overridden by the **Container Cloning Arguments** listed below.
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
**Container Cloning Arguments**
snapshot
Use Copy On Write snapshots (LVM)
size : 1G
Size of the volume to create. Only applicable if ``backing=lvm``.
backing
The type of storage to use. Set to ``lvm`` to use an LVM group.
Defaults to filesystem within /var/lib/lxc.
network_profile
Network profile to use for container
.. versionadded:: 2015.8.0
nic_opts
give extra opts overriding network profile values
.. versionadded:: 2015.8.0
CLI Examples:
.. code-block:: bash
salt '*' lxc.clone myclone orig=orig_container
salt '*' lxc.clone myclone orig=orig_container snapshot=True
'''
profile = get_container_profile(copy.deepcopy(profile))
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, None)
profile_match = profile.pop(key, default)
# let kwarg overrides be the preferred choice
if kw_overrides_match is None:
return profile_match
return kw_overrides_match
path = select('path')
if exists(name, path=path):
raise CommandExecutionError(
'Container \'{0}\' already exists'.format(name)
)
_ensure_exists(orig, path=path)
if state(orig, path=path) != 'stopped':
raise CommandExecutionError(
'Container \'{0}\' must be stopped to be cloned'.format(orig)
)
backing = select('backing')
snapshot = select('snapshot')
if backing in ('dir',):
snapshot = False
if not snapshot:
snapshot = ''
else:
snapshot = '-s'
size = select('size', '1G')
if backing in ('dir', 'overlayfs', 'btrfs'):
size = None
# LXC commands and options changed in 2.0 - CF issue #34086 for details
if _LooseVersion(version()) >= _LooseVersion('2.0'):
# https://linuxcontainers.org/lxc/manpages//man1/lxc-copy.1.html
cmd = 'lxc-copy'
cmd += ' {0} -n {1} -N {2}'.format(snapshot, orig, name)
else:
# https://linuxcontainers.org/lxc/manpages//man1/lxc-clone.1.html
cmd = 'lxc-clone'
cmd += ' {0} -o {1} -n {2}'.format(snapshot, orig, name)
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
if not os.path.exists(path):
os.makedirs(path)
if backing:
backing = backing.lower()
cmd += ' -B {0}'.format(backing)
if backing not in ('dir', 'overlayfs'):
if size:
cmd += ' -L {0}'.format(size)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
# please do not merge extra conflicting stuff
# inside those two line (ret =, return)
return _after_ignition_network_profile(cmd,
ret,
name,
network_profile,
path,
nic_opts)
def ls_(active=None, cache=True, path=None):
'''
Return a list of the containers available on the minion
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
active
If ``True``, return only active (i.e. running) containers
.. versionadded:: 2015.5.0
CLI Example:
.. code-block:: bash
salt '*' lxc.ls
salt '*' lxc.ls active=True
'''
contextvar = 'lxc.ls{0}'.format(path)
if active:
contextvar += '.active'
if cache and (contextvar in __context__):
return __context__[contextvar]
else:
ret = []
cmd = 'lxc-ls'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
if active:
cmd += ' --active'
output = __salt__['cmd.run_stdout'](cmd, python_shell=False)
for line in output.splitlines():
ret.extend(line.split())
__context__[contextvar] = ret
return ret
def list_(extra=False, limit=None, path=None):
'''
List containers classified by state
extra
Also get per-container specific info. This will change the return data.
Instead of returning a list of containers, a dictionary of containers
and each container's output from :mod:`lxc.info
<salt.modules.lxc.info>`.
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
limit
Return output matching a specific state (**frozen**, **running**, or
**stopped**).
.. versionadded:: 2015.5.0
CLI Examples:
.. code-block:: bash
salt '*' lxc.list
salt '*' lxc.list extra=True
salt '*' lxc.list limit=running
'''
ctnrs = ls_(path=path)
if extra:
stopped = {}
frozen = {}
running = {}
else:
stopped = []
frozen = []
running = []
ret = {'running': running,
'stopped': stopped,
'frozen': frozen}
for container in ctnrs:
cmd = 'lxc-info'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0}'.format(container)
c_info = __salt__['cmd.run'](
cmd,
python_shell=False,
output_loglevel='debug'
)
c_state = None
for line in c_info.splitlines():
stat = line.split(':')
if stat[0] in ('State', 'state'):
c_state = stat[1].strip()
break
if not c_state or (limit is not None and c_state.lower() != limit):
continue
if extra:
infos = info(container, path=path)
method = 'update'
value = {container: infos}
else:
method = 'append'
value = container
if c_state == 'STOPPED':
getattr(stopped, method)(value)
continue
if c_state == 'FROZEN':
getattr(frozen, method)(value)
continue
if c_state == 'RUNNING':
getattr(running, method)(value)
continue
if limit is not None:
return ret.get(limit, {} if extra else [])
return ret
def _change_state(cmd,
name,
expected,
stdin=_marker,
stdout=_marker,
stderr=_marker,
with_communicate=_marker,
use_vt=_marker,
path=None):
pre = state(name, path=path)
if pre == expected:
return {'result': True,
'state': {'old': expected, 'new': expected},
'comment': 'Container \'{0}\' already {1}'
.format(name, expected)}
if cmd == 'lxc-destroy':
# Kill the container first
scmd = 'lxc-stop'
if path:
scmd += ' -P {0}'.format(pipes.quote(path))
scmd += ' -k -n {0}'.format(name)
__salt__['cmd.run'](scmd,
python_shell=False)
if path and ' -P ' not in cmd:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0}'.format(name)
# certain lxc commands need to be taken with care (lxc-start)
# as te command itself mess with double forks; we must not
# communicate with it, but just wait for the exit status
pkwargs = {'python_shell': False,
'redirect_stderr': True,
'with_communicate': with_communicate,
'use_vt': use_vt,
'stdin': stdin,
'stdout': stdout}
for i in [a for a in pkwargs]:
val = pkwargs[i]
if val is _marker:
pkwargs.pop(i, None)
_cmdout = __salt__['cmd.run_all'](cmd, **pkwargs)
if _cmdout['retcode'] != 0:
raise CommandExecutionError(
'Error changing state for container \'{0}\' using command '
'\'{1}\': {2}'.format(name, cmd, _cmdout['stdout'])
)
if expected is not None:
# some commands do not wait, so we will
rcmd = 'lxc-wait'
if path:
rcmd += ' -P {0}'.format(pipes.quote(path))
rcmd += ' -n {0} -s {1}'.format(name, expected.upper())
__salt__['cmd.run'](rcmd, python_shell=False, timeout=30)
_clear_context()
post = state(name, path=path)
ret = {'result': post == expected,
'state': {'old': pre, 'new': post}}
return ret
def _ensure_exists(name, path=None):
'''
Raise an exception if the container does not exist
'''
if not exists(name, path=path):
raise CommandExecutionError(
'Container \'{0}\' does not exist'.format(name)
)
def _ensure_running(name, no_start=False, path=None):
'''
If the container is not currently running, start it. This function returns
the state that the container was in before changing
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
'''
_ensure_exists(name, path=path)
pre = state(name, path=path)
if pre == 'running':
# This will be a no-op but running the function will give us a pretty
# return dict.
return start(name, path=path)
elif pre == 'stopped':
if no_start:
raise CommandExecutionError(
'Container \'{0}\' is not running'.format(name)
)
return start(name, path=path)
elif pre == 'frozen':
if no_start:
raise CommandExecutionError(
'Container \'{0}\' is not running'.format(name)
)
return unfreeze(name, path=path)
def restart(name, path=None, lxc_config=None, force=False):
'''
.. versionadded:: 2015.5.0
Restart the named container. If the container was not running, the
container will merely be started.
name
The name of the container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
lxc_config
path to a lxc config file
config file will be guessed from container name otherwise
.. versionadded:: 2015.8.0
force : False
If ``True``, the container will be force-stopped instead of gracefully
shut down
CLI Example:
.. code-block:: bash
salt myminion lxc.restart name
'''
_ensure_exists(name, path=path)
orig_state = state(name, path=path)
if orig_state != 'stopped':
stop(name, kill=force, path=path)
ret = start(name, path=path, lxc_config=lxc_config)
ret['state']['old'] = orig_state
if orig_state != 'stopped':
ret['restarted'] = True
return ret
def start(name, **kwargs):
'''
Start the named container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
lxc_config
path to a lxc config file
config file will be guessed from container name otherwise
.. versionadded:: 2015.8.0
use_vt
run the command through VT
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.start name
'''
path = kwargs.get('path', None)
cpath = get_root_path(path)
lxc_config = kwargs.get('lxc_config', None)
cmd = 'lxc-start'
if not lxc_config:
lxc_config = os.path.join(cpath, name, 'config')
# we try to start, even without config, if global opts are there
if os.path.exists(lxc_config):
cmd += ' -f {0}'.format(pipes.quote(lxc_config))
cmd += ' -d'
_ensure_exists(name, path=path)
if state(name, path=path) == 'frozen':
raise CommandExecutionError(
'Container \'{0}\' is frozen, use lxc.unfreeze'.format(name)
)
# lxc-start daemonize itself violently, we must not communicate with it
use_vt = kwargs.get('use_vt', None)
with_communicate = kwargs.get('with_communicate', False)
return _change_state(cmd, name, 'running',
stdout=None,
stderr=None,
stdin=None,
with_communicate=with_communicate,
path=path,
use_vt=use_vt)
def stop(name, kill=False, path=None, use_vt=None):
'''
Stop the named container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
kill: False
Do not wait for the container to stop, kill all tasks in the container.
Older LXC versions will stop containers like this irrespective of this
argument.
.. versionchanged:: 2015.5.0
Default value changed to ``False``
use_vt
run the command through VT
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.stop name
'''
_ensure_exists(name, path=path)
orig_state = state(name, path=path)
if orig_state == 'frozen' and not kill:
# Gracefully stopping a frozen container is slower than unfreezing and
# then stopping it (at least in my testing), so if we're not
# force-stopping the container, unfreeze it first.
unfreeze(name, path=path)
cmd = 'lxc-stop'
if kill:
cmd += ' -k'
ret = _change_state(cmd, name, 'stopped', use_vt=use_vt, path=path)
ret['state']['old'] = orig_state
return ret
def freeze(name, **kwargs):
'''
Freeze the named container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
start : False
If ``True`` and the container is stopped, the container will be started
before attempting to freeze.
.. versionadded:: 2015.5.0
use_vt
run the command through VT
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.freeze name
'''
use_vt = kwargs.get('use_vt', None)
path = kwargs.get('path', None)
_ensure_exists(name, path=path)
orig_state = state(name, path=path)
start_ = kwargs.get('start', False)
if orig_state == 'stopped':
if not start_:
raise CommandExecutionError(
'Container \'{0}\' is stopped'.format(name)
)
start(name, path=path)
cmd = 'lxc-freeze'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
ret = _change_state(cmd, name, 'frozen', use_vt=use_vt, path=path)
if orig_state == 'stopped' and start_:
ret['state']['old'] = orig_state
ret['started'] = True
ret['state']['new'] = state(name, path=path)
return ret
def unfreeze(name, path=None, use_vt=None):
'''
Unfreeze the named container.
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
use_vt
run the command through VT
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.unfreeze name
'''
_ensure_exists(name, path=path)
if state(name, path=path) == 'stopped':
raise CommandExecutionError(
'Container \'{0}\' is stopped'.format(name)
)
cmd = 'lxc-unfreeze'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
return _change_state(cmd, name, 'running', path=path, use_vt=use_vt)
def destroy(name, stop=False, path=None):
'''
Destroy the named container.
.. warning::
Destroys all data associated with the container.
path
path to the container parent directory (default: /var/lib/lxc)
.. versionadded:: 2015.8.0
stop : False
If ``True``, the container will be destroyed even if it is
running/frozen.
.. versionchanged:: 2015.5.0
Default value changed to ``False``. This more closely matches the
behavior of ``lxc-destroy(1)``, and also makes it less likely that
an accidental command will destroy a running container that was
being used for important things.
CLI Examples:
.. code-block:: bash
salt '*' lxc.destroy foo
salt '*' lxc.destroy foo stop=True
'''
_ensure_exists(name, path=path)
if not stop and state(name, path=path) != 'stopped':
raise CommandExecutionError(
'Container \'{0}\' is not stopped'.format(name)
)
return _change_state('lxc-destroy', name, None, path=path)
# Compatibility between LXC and nspawn
remove = salt.utils.functools.alias_function(destroy, 'remove')
def exists(name, path=None):
'''
Returns whether the named container exists.
path
path to the container parent directory (default: /var/lib/lxc)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.exists name
'''
_exists = name in ls_(path=path)
# container may be just created but we did cached earlier the
# lxc-ls results
if not _exists:
_exists = name in ls_(cache=False, path=path)
return _exists
def state(name, path=None):
'''
Returns the state of a container.
path
path to the container parent directory (default: /var/lib/lxc)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.state name
'''
# Don't use _ensure_exists() here, it will mess with _change_state()
cachekey = 'lxc.state.{0}{1}'.format(name, path)
try:
return __context__[cachekey]
except KeyError:
if not exists(name, path=path):
__context__[cachekey] = None
else:
cmd = 'lxc-info'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0}'.format(name)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
if ret['retcode'] != 0:
_clear_context()
raise CommandExecutionError(
'Unable to get state of container \'{0}\''.format(name)
)
c_infos = ret['stdout'].splitlines()
c_state = None
for c_info in c_infos:
stat = c_info.split(':')
if stat[0].lower() == 'state':
c_state = stat[1].strip().lower()
break
__context__[cachekey] = c_state
return __context__[cachekey]
def get_parameter(name, parameter, path=None):
'''
Returns the value of a cgroup parameter for a container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.get_parameter container_name memory.limit_in_bytes
'''
_ensure_exists(name, path=path)
cmd = 'lxc-cgroup'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0} {1}'.format(name, parameter)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
if ret['retcode'] != 0:
raise CommandExecutionError(
'Unable to retrieve value for \'{0}\''.format(parameter)
)
return ret['stdout'].strip()
def set_parameter(name, parameter, value, path=None):
'''
Set the value of a cgroup parameter for a container.
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.set_parameter name parameter value
'''
if not exists(name, path=path):
return None
cmd = 'lxc-cgroup'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0} {1} {2}'.format(name, parameter, value)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
if ret['retcode'] != 0:
return False
else:
return True
def info(name, path=None):
'''
Returns information about a container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.info name
'''
cachekey = 'lxc.info.{0}{1}'.format(name, path)
try:
return __context__[cachekey]
except KeyError:
_ensure_exists(name, path=path)
cpath = get_root_path(path)
try:
conf_file = os.path.join(cpath, name, 'config')
except AttributeError:
conf_file = os.path.join(cpath, six.text_type(name), 'config')
if not os.path.isfile(conf_file):
raise CommandExecutionError(
'LXC config file {0} does not exist'.format(conf_file)
)
ret = {}
config = []
with salt.utils.files.fopen(conf_file) as fp_:
for line in fp_:
line = salt.utils.stringutils.to_unicode(line)
comps = [x.strip() for x in
line.split('#', 1)[0].strip().split('=', 1)]
if len(comps) == 2:
config.append(tuple(comps))
ifaces = []
current = None
for key, val in config:
if key == 'lxc.network.type':
current = {'type': val}
ifaces.append(current)
elif not current:
continue
elif key.startswith('lxc.network.'):
current[key.replace('lxc.network.', '', 1)] = val
if ifaces:
ret['nics'] = ifaces
ret['rootfs'] = next(
(x[1] for x in config if x[0] == 'lxc.rootfs'),
None
)
ret['state'] = state(name, path=path)
ret['ips'] = []
ret['public_ips'] = []
ret['private_ips'] = []
ret['public_ipv4_ips'] = []
ret['public_ipv6_ips'] = []
ret['private_ipv4_ips'] = []
ret['private_ipv6_ips'] = []
ret['ipv4_ips'] = []
ret['ipv6_ips'] = []
ret['size'] = None
ret['config'] = conf_file
if ret['state'] == 'running':
try:
limit = int(get_parameter(name, 'memory.limit_in_bytes'))
except (CommandExecutionError, TypeError, ValueError):
limit = 0
try:
usage = int(get_parameter(name, 'memory.usage_in_bytes'))
except (CommandExecutionError, TypeError, ValueError):
usage = 0
free = limit - usage
ret['memory_limit'] = limit
ret['memory_free'] = free
size = run_stdout(name, 'df /', path=path, python_shell=False)
# The size is the 2nd column of the last line
ret['size'] = size.splitlines()[-1].split()[1]
# First try iproute2
ip_cmd = run_all(
name, 'ip link show', path=path, python_shell=False)
if ip_cmd['retcode'] == 0:
ip_data = ip_cmd['stdout']
ip_cmd = run_all(
name, 'ip addr show', path=path, python_shell=False)
ip_data += '\n' + ip_cmd['stdout']
ip_data = salt.utils.network._interfaces_ip(ip_data)
else:
# That didn't work, try ifconfig
ip_cmd = run_all(
name, 'ifconfig', path=path, python_shell=False)
if ip_cmd['retcode'] == 0:
ip_data = \
salt.utils.network._interfaces_ifconfig(
ip_cmd['stdout'])
else:
# Neither was successful, give up
log.warning(
'Unable to run ip or ifconfig in container \'%s\'', name
)
ip_data = {}
ret['ipv4_ips'] = salt.utils.network.ip_addrs(
include_loopback=True,
interface_data=ip_data
)
ret['ipv6_ips'] = salt.utils.network.ip_addrs6(
include_loopback=True,
interface_data=ip_data
)
ret['ips'] = ret['ipv4_ips'] + ret['ipv6_ips']
for address in ret['ipv4_ips']:
if address == '127.0.0.1':
ret['private_ips'].append(address)
ret['private_ipv4_ips'].append(address)
elif salt.utils.cloud.is_public_ip(address):
ret['public_ips'].append(address)
ret['public_ipv4_ips'].append(address)
else:
ret['private_ips'].append(address)
ret['private_ipv4_ips'].append(address)
for address in ret['ipv6_ips']:
if address == '::1' or address.startswith('fe80'):
ret['private_ips'].append(address)
ret['private_ipv6_ips'].append(address)
else:
ret['public_ips'].append(address)
ret['public_ipv6_ips'].append(address)
for key in [x for x in ret if x == 'ips' or x.endswith('ips')]:
ret[key].sort(key=_ip_sort)
__context__[cachekey] = ret
return __context__[cachekey]
def set_password(name, users, password, encrypted=True, path=None):
'''
.. versionchanged:: 2015.5.0
Function renamed from ``set_pass`` to ``set_password``. Additionally,
this function now supports (and defaults to using) a password hash
instead of a plaintext password.
Set the password of one or more system users inside containers
users
Comma-separated list (or python list) of users to change password
password
Password to set for the specified user(s)
encrypted : True
If true, ``password`` must be a password hash. Set to ``False`` to set
a plaintext password (not recommended).
.. versionadded:: 2015.5.0
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.set_pass container-name root '$6$uJ2uAyLU$KoI67t8As/0fXtJOPcHKGXmUpcoYUcVR2K6x93walnShTCQvjRwq25yIkiCBOqgbfdKQSFnAo28/ek6716vEV1'
salt '*' lxc.set_pass container-name root foo encrypted=False
'''
def _bad_user_input():
raise SaltInvocationError('Invalid input for \'users\' parameter')
if not isinstance(users, list):
try:
users = users.split(',')
except AttributeError:
_bad_user_input()
if not users:
_bad_user_input()
failed_users = []
for user in users:
result = retcode(name,
'chpasswd{0}'.format(' -e' if encrypted else ''),
stdin=':'.join((user, password)),
python_shell=False,
path=path,
chroot_fallback=True,
output_loglevel='quiet')
if result != 0:
failed_users.append(user)
if failed_users:
raise CommandExecutionError(
'Password change failed for the following user(s): {0}'
.format(', '.join(failed_users))
)
return True
set_pass = salt.utils.functools.alias_function(set_password, 'set_pass')
def update_lxc_conf(name, lxc_conf, lxc_conf_unset, path=None):
'''
Edit LXC configuration options
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.update_lxc_conf ubuntu \\
lxc_conf="[{'network.ipv4.ip':'10.0.3.5'}]" \\
lxc_conf_unset="['lxc.utsname']"
'''
_ensure_exists(name, path=path)
cpath = get_root_path(path)
lxc_conf_p = os.path.join(cpath, name, 'config')
if not os.path.exists(lxc_conf_p):
raise SaltInvocationError(
'Configuration file {0} does not exist'.format(lxc_conf_p)
)
changes = {'edited': [], 'added': [], 'removed': []}
ret = {'changes': changes, 'result': True, 'comment': ''}
# do not use salt.utils.files.fopen !
with salt.utils.files.fopen(lxc_conf_p, 'r') as fic:
filtered_lxc_conf = []
for row in lxc_conf:
if not row:
continue
for conf in row:
filtered_lxc_conf.append((conf.strip(),
row[conf].strip()))
ret['comment'] = 'lxc.conf is up to date'
lines = []
orig_config = salt.utils.stringutils.to_unicode(fic.read())
for line in orig_config.splitlines():
if line.startswith('#') or not line.strip():
lines.append([line, ''])
else:
line = line.split('=')
index = line.pop(0)
val = (index.strip(), '='.join(line).strip())
if val not in lines:
lines.append(val)
for key, item in filtered_lxc_conf:
matched = False
for idx, line in enumerate(lines[:]):
if line[0] == key:
matched = True
lines[idx] = (key, item)
if '='.join(line[1:]).strip() != item.strip():
changes['edited'].append(
({line[0]: line[1:]}, {key: item}))
break
if not matched:
if (key, item) not in lines:
lines.append((key, item))
changes['added'].append({key: item})
dest_lxc_conf = []
# filter unset
if lxc_conf_unset:
for line in lines:
for opt in lxc_conf_unset:
if (
not line[0].startswith(opt) and
line not in dest_lxc_conf
):
dest_lxc_conf.append(line)
else:
changes['removed'].append(opt)
else:
dest_lxc_conf = lines
conf = ''
for key, val in dest_lxc_conf:
if not val:
conf += '{0}\n'.format(key)
else:
conf += '{0} = {1}\n'.format(key.strip(), val.strip())
conf_changed = conf != orig_config
chrono = datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S')
if conf_changed:
# DO NOT USE salt.utils.files.fopen here, i got (kiorky)
# problems with lxc configs which were wiped !
with salt.utils.files.fopen('{0}.{1}'.format(lxc_conf_p, chrono), 'w') as wfic:
wfic.write(salt.utils.stringutils.to_str(conf))
with salt.utils.files.fopen(lxc_conf_p, 'w') as wfic:
wfic.write(salt.utils.stringutils.to_str(conf))
ret['comment'] = 'Updated'
ret['result'] = True
if not any(changes[x] for x in changes):
# Ensure an empty changes dict if nothing was modified
ret['changes'] = {}
return ret
def set_dns(name, dnsservers=None, searchdomains=None, path=None):
'''
.. versionchanged:: 2015.5.0
The ``dnsservers`` and ``searchdomains`` parameters can now be passed
as a comma-separated list.
Update /etc/resolv.confo
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.set_dns ubuntu "['8.8.8.8', '4.4.4.4']"
'''
if dnsservers is None:
dnsservers = ['8.8.8.8', '4.4.4.4']
elif not isinstance(dnsservers, list):
try:
dnsservers = dnsservers.split(',')
except AttributeError:
raise SaltInvocationError(
'Invalid input for \'dnsservers\' parameter'
)
if searchdomains is None:
searchdomains = []
elif not isinstance(searchdomains, list):
try:
searchdomains = searchdomains.split(',')
except AttributeError:
raise SaltInvocationError(
'Invalid input for \'searchdomains\' parameter'
)
dns = ['nameserver {0}'.format(x) for x in dnsservers]
dns.extend(['search {0}'.format(x) for x in searchdomains])
dns = '\n'.join(dns) + '\n'
# we may be using resolvconf in the container
# We need to handle that case with care:
# - we create the resolv.conf runtime directory (the
# linked directory) as anyway it will be shadowed when the real
# runned tmpfs mountpoint will be mounted.
# ( /etc/resolv.conf -> ../run/resolvconf/resolv.conf)
# Indeed, it can save us in any other case (running, eg, in a
# bare chroot when repairing or preparing the container for
# operation.
# - We also teach resolvconf to use the aforementioned dns.
# - We finally also set /etc/resolv.conf in all cases
rstr = __salt__['test.random_hash']()
# no tmp here, apparmor won't let us execute !
script = '/sbin/{0}_dns.sh'.format(rstr)
DNS_SCRIPT = "\n".join([
# 'set -x',
'#!/usr/bin/env bash',
'if [ -h /etc/resolv.conf ];then',
' if [ "x$(readlink /etc/resolv.conf)"'
' = "x../run/resolvconf/resolv.conf" ];then',
' if [ ! -d /run/resolvconf/ ];then',
' mkdir -p /run/resolvconf',
' fi',
' cat > /etc/resolvconf/resolv.conf.d/head <<EOF',
dns,
'EOF',
'',
' fi',
'fi',
'cat > /etc/resolv.conf <<EOF',
dns,
'EOF',
''])
result = run_all(
name, 'tee {0}'.format(script), path=path,
stdin=DNS_SCRIPT, python_shell=True)
if result['retcode'] == 0:
result = run_all(
name, 'sh -c "chmod +x {0};{0}"'.format(script),
path=path, python_shell=True)
# blindly delete the setter file
run_all(name,
'sh -c \'if [ -f "{0}" ];then rm -f "{0}";fi\''.format(script),
path=path, python_shell=True)
if result['retcode'] != 0:
error = ('Unable to write to /etc/resolv.conf in container \'{0}\''
.format(name))
if result['stderr']:
error += ': {0}'.format(result['stderr'])
raise CommandExecutionError(error)
return True
def running_systemd(name, cache=True, path=None):
'''
Determine if systemD is running
path
path to the container parent
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.running_systemd ubuntu
'''
k = 'lxc.systemd.test.{0}{1}'.format(name, path)
ret = __context__.get(k, None)
if ret is None or not cache:
rstr = __salt__['test.random_hash']()
# no tmp here, apparmor won't let us execute !
script = '/sbin/{0}_testsystemd.sh'.format(rstr)
# ubuntu already had since trusty some bits of systemd but was
# still using upstart ...
# we need to be a bit more careful that just testing that systemd
# is present
_script = textwrap.dedent(
'''\
#!/usr/bin/env bash
set -x
if ! command -v systemctl 1>/dev/null 2>/dev/null;then exit 2;fi
for i in \\
/run/systemd/journal/dev-log\\
/run/systemd/journal/flushed\\
/run/systemd/journal/kernel-seqnum\\
/run/systemd/journal/socket\\
/run/systemd/journal/stdout\\
/var/run/systemd/journal/dev-log\\
/var/run/systemd/journal/flushed\\
/var/run/systemd/journal/kernel-seqnum\\
/var/run/systemd/journal/socket\\
/var/run/systemd/journal/stdout\\
;do\\
if test -e ${i};then exit 0;fi
done
if test -d /var/systemd/system;then exit 0;fi
exit 2
''')
result = run_all(
name, 'tee {0}'.format(script), path=path,
stdin=_script, python_shell=True)
if result['retcode'] == 0:
result = run_all(name,
'sh -c "chmod +x {0};{0}"'''.format(script),
path=path,
python_shell=True)
else:
raise CommandExecutionError(
'lxc {0} failed to copy initd tester'.format(name))
run_all(name,
'sh -c \'if [ -f "{0}" ];then rm -f "{0}";fi\''
''.format(script),
path=path,
ignore_retcode=True,
python_shell=True)
if result['retcode'] != 0:
error = ('Unable to determine if the container \'{0}\''
' was running systemd, assmuming it is not.'
''.format(name))
if result['stderr']:
error += ': {0}'.format(result['stderr'])
# only cache result if we got a known exit code
if result['retcode'] in (0, 2):
__context__[k] = ret = not result['retcode']
return ret
def systemd_running_state(name, path=None):
'''
Get the operational state of a systemd based container
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.systemd_running_state ubuntu
'''
try:
ret = run_all(name,
'systemctl is-system-running',
path=path,
ignore_retcode=True)['stdout']
except CommandExecutionError:
ret = ''
return ret
def test_sd_started_state(name, path=None):
'''
Test if a systemd container is fully started
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.test_sd_started_state ubuntu
'''
qstate = systemd_running_state(name, path=path)
if qstate in ('initializing', 'starting'):
return False
elif qstate == '':
return None
else:
return True
def test_bare_started_state(name, path=None):
'''
Test if a non systemd container is fully started
For now, it consists only to test if the container is attachable
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.test_bare_started_state ubuntu
'''
try:
ret = run_all(
name, 'ls', path=path, ignore_retcode=True
)['retcode'] == 0
except (CommandExecutionError,):
ret = None
return ret
def wait_started(name, path=None, timeout=300):
'''
Check that the system has fully inited
This is actually very important for systemD based containers
see https://github.com/saltstack/salt/issues/23847
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.wait_started ubuntu
'''
if not exists(name, path=path):
raise CommandExecutionError(
'Container {0} does does exists'.format(name))
if not state(name, path=path) == 'running':
raise CommandExecutionError(
'Container {0} is not running'.format(name))
ret = False
if running_systemd(name, path=path):
test_started = test_sd_started_state
logger = log.error
else:
test_started = test_bare_started_state
logger = log.debug
now = time.time()
expire = now + timeout
now = time.time()
started = test_started(name, path=path)
while time.time() < expire and not started:
time.sleep(0.3)
started = test_started(name, path=path)
if started is None:
logger(
'Assuming %s is started, although we failed to detect that'
' is fully started correctly', name)
ret = True
else:
ret = started
return ret
def _needs_install(name, path=None):
ret = 0
has_minion = retcode(name,
'which salt-minion',
path=path,
ignore_retcode=True)
# we assume that installing is when no minion is running
# but testing the executable presence is not enougth for custom
# installs where the bootstrap can do much more than installing
# the bare salt binaries.
if has_minion:
processes = run_stdout(name, "ps aux", path=path)
if 'salt-minion' not in processes:
ret = 1
else:
retcode(name, 'salt-call --local service.stop salt-minion')
else:
ret = 1
return ret
def bootstrap(name,
config=None,
approve_key=True,
install=True,
pub_key=None,
priv_key=None,
bootstrap_url=None,
force_install=False,
unconditional_install=False,
path=None,
bootstrap_delay=None,
bootstrap_args=None,
bootstrap_shell=None):
'''
Install and configure salt in a container.
config
Minion configuration options. By default, the ``master`` option is set
to the target host's master.
approve_key
Request a pre-approval of the generated minion key. Requires
that the salt-master be configured to either auto-accept all keys or
expect a signing request from the target host. Default: ``True``
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
pub_key
Explicit public key to pressed the minion with (optional).
This can be either a filepath or a string representing the key
priv_key
Explicit private key to pressed the minion with (optional).
This can be either a filepath or a string representing the key
bootstrap_delay
Delay in seconds between end of container creation and bootstrapping.
Useful when waiting for container to obtain a DHCP lease.
.. versionadded:: 2015.5.0
bootstrap_url
url, content or filepath to the salt bootstrap script
bootstrap_args
salt bootstrap script arguments
bootstrap_shell
shell to execute the script into
install
Whether to attempt a full installation of salt-minion if needed.
force_install
Force installation even if salt-minion is detected,
this is the way to run vendor bootstrap scripts even
if a salt minion is already present in the container
unconditional_install
Run the script even if the container seems seeded
CLI Examples:
.. code-block:: bash
salt 'minion' lxc.bootstrap container_name [config=config_data] \\
[approve_key=(True|False)] [install=(True|False)]
'''
wait_started(name, path=path)
if bootstrap_delay is not None:
try:
log.info('LXC %s: bootstrap_delay: %s', name, bootstrap_delay)
time.sleep(bootstrap_delay)
except TypeError:
# Bad input, but assume since a value was passed that
# a delay was desired, and sleep for 5 seconds
time.sleep(5)
c_info = info(name, path=path)
if not c_info:
return None
# default set here as we cannot set them
# in def as it can come from a chain of procedures.
if bootstrap_args:
# custom bootstrap args can be totally customized, and user could
# have inserted the placeholder for the config directory.
# For example, some salt bootstrap script do not use at all -c
if '{0}' not in bootstrap_args:
bootstrap_args += ' -c {0}'
else:
bootstrap_args = '-c {0}'
if not bootstrap_shell:
bootstrap_shell = 'sh'
orig_state = _ensure_running(name, path=path)
if not orig_state:
return orig_state
if not force_install:
needs_install = _needs_install(name, path=path)
else:
needs_install = True
seeded = retcode(name,
'test -e \'{0}\''.format(SEED_MARKER),
path=path,
chroot_fallback=True,
ignore_retcode=True) == 0
tmp = tempfile.mkdtemp()
if seeded and not unconditional_install:
ret = True
else:
ret = False
cfg_files = __salt__['seed.mkconfig'](
config, tmp=tmp, id_=name, approve_key=approve_key,
pub_key=pub_key, priv_key=priv_key)
if needs_install or force_install or unconditional_install:
if install:
rstr = __salt__['test.random_hash']()
configdir = '/var/tmp/.c_{0}'.format(rstr)
cmd = 'install -m 0700 -d {0}'.format(configdir)
if run_all(
name, cmd, path=path, python_shell=False
)['retcode'] != 0:
log.error('tmpdir %s creation failed %s', configdir, cmd)
return False
bs_ = __salt__['config.gather_bootstrap_script'](
bootstrap=bootstrap_url)
script = '/sbin/{0}_bootstrap.sh'.format(rstr)
copy_to(name, bs_, script, path=path)
result = run_all(name,
'sh -c "chmod +x {0}"'.format(script),
path=path,
python_shell=True)
copy_to(name, cfg_files['config'],
os.path.join(configdir, 'minion'),
path=path)
copy_to(name, cfg_files['privkey'],
os.path.join(configdir, 'minion.pem'),
path=path)
copy_to(name, cfg_files['pubkey'],
os.path.join(configdir, 'minion.pub'),
path=path)
bootstrap_args = bootstrap_args.format(configdir)
cmd = ('{0} {2} {1}'
.format(bootstrap_shell,
bootstrap_args.replace("'", "''"),
script))
# log ASAP the forged bootstrap command which can be wrapped
# out of the output in case of unexpected problem
log.info('Running %s in LXC container \'%s\'', cmd, name)
ret = retcode(name, cmd, output_loglevel='info',
path=path, use_vt=True) == 0
run_all(name,
'sh -c \'if [ -f "{0}" ];then rm -f "{0}";fi\''
''.format(script),
path=path,
ignore_retcode=True,
python_shell=True)
else:
ret = False
else:
minion_config = salt.config.minion_config(cfg_files['config'])
pki_dir = minion_config['pki_dir']
copy_to(name,
cfg_files['config'],
'/etc/salt/minion',
path=path)
copy_to(name,
cfg_files['privkey'],
os.path.join(pki_dir, 'minion.pem'),
path=path)
copy_to(name,
cfg_files['pubkey'],
os.path.join(pki_dir, 'minion.pub'),
path=path)
run(name,
'salt-call --local service.enable salt-minion',
path=path,
python_shell=False)
ret = True
shutil.rmtree(tmp)
if orig_state == 'stopped':
stop(name, path=path)
elif orig_state == 'frozen':
freeze(name, path=path)
# mark seeded upon successful install
if ret:
run(name,
'touch \'{0}\''.format(SEED_MARKER),
path=path,
python_shell=False)
return ret
def attachable(name, path=None):
'''
Return True if the named container can be attached to via the lxc-attach
command
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt 'minion' lxc.attachable ubuntu
'''
cachekey = 'lxc.attachable{0}{1}'.format(name, path)
try:
return __context__[cachekey]
except KeyError:
_ensure_exists(name, path=path)
# Can't use run() here because it uses attachable() and would
# endlessly recurse, resulting in a traceback
log.debug('Checking if LXC container %s is attachable', name)
cmd = 'lxc-attach'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' --clear-env -n {0} -- /usr/bin/env'.format(name)
result = __salt__['cmd.retcode'](cmd,
python_shell=False,
output_loglevel='quiet',
ignore_retcode=True) == 0
__context__[cachekey] = result
return __context__[cachekey]
def _run(name,
cmd,
output=None,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=None,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
Common logic for lxc.run functions
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
'''
orig_state = state(name, path=path)
try:
if attachable(name, path=path):
ret = __salt__['container_resource.run'](
name,
cmd,
path=path,
container_type=__virtualname__,
exec_driver=EXEC_DRIVER,
output=output,
no_start=no_start,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
ignore_retcode=ignore_retcode,
use_vt=use_vt,
keep_env=keep_env)
else:
if not chroot_fallback:
raise CommandExecutionError(
'{0} is not attachable.'.format(name))
rootfs = info(name, path=path).get('rootfs')
# Set context var to make cmd.run_chroot run cmd.run instead of
# cmd.run_all.
__context__['cmd.run_chroot.func'] = __salt__['cmd.run']
ret = __salt__['cmd.run_chroot'](rootfs,
cmd,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
ignore_retcode=ignore_retcode)
except Exception:
raise
finally:
# Make sure we honor preserve_state, even if there was an exception
new_state = state(name, path=path)
if preserve_state:
if orig_state == 'stopped' and new_state != 'stopped':
stop(name, path=path)
elif orig_state == 'frozen' and new_state != 'frozen':
freeze(name, start=True, path=path)
if output in (None, 'all'):
return ret
else:
return ret[output]
def run(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.8.0
Run :mod:`cmd.run <salt.modules.cmdmod.run>` within a container
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed in stderr if the command being run
does not exist. If no output is returned using this function, try using
:mod:`lxc.run_stderr <salt.modules.lxc.run_stderr>` or
:mod:`lxc.run_all <salt.modules.lxc.run_all>`.
name
Name of the container in which to run the command
cmd
Command to run
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console. Assumes
``output=all``.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
CLI Example:
.. code-block:: bash
salt myminion lxc.run mycontainer 'ifconfig -a'
'''
return _run(name,
cmd,
path=path,
output=None,
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def run_stdout(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.5.0
Run :mod:`cmd.run_stdout <salt.modules.cmdmod.run_stdout>` within a container
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed in stderr if the command being run
does not exist. If no output is returned using this function, try using
:mod:`lxc.run_stderr <salt.modules.lxc.run_stderr>` or
:mod:`lxc.run_all <salt.modules.lxc.run_all>`.
name
Name of the container in which to run the command
cmd
Command to run
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console
``output=all``.
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
CLI Example:
.. code-block:: bash
salt myminion lxc.run_stdout mycontainer 'ifconfig -a'
'''
return _run(name,
cmd,
path=path,
output='stdout',
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def run_stderr(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.5.0
Run :mod:`cmd.run_stderr <salt.modules.cmdmod.run_stderr>` within a container
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed if the command being run does not
exist.
name
Name of the container in which to run the command
cmd
Command to run
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console
``output=all``.
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
CLI Example:
.. code-block:: bash
salt myminion lxc.run_stderr mycontainer 'ip addr show'
'''
return _run(name,
cmd,
path=path,
output='stderr',
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def retcode(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.5.0
Run :mod:`cmd.retcode <salt.modules.cmdmod.retcode>` within a container
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed in stderr if the command being run
does not exist. If the retcode is nonzero and not what was expected,
try using :mod:`lxc.run_stderr <salt.modules.lxc.run_stderr>`
or :mod:`lxc.run_all <salt.modules.lxc.run_all>`.
name
Name of the container in which to run the command
cmd
Command to run
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console
``output=all``.
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
CLI Example:
.. code-block:: bash
salt myminion lxc.retcode mycontainer 'ip addr show'
'''
return _run(name,
cmd,
output='retcode',
path=path,
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def run_all(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.5.0
Run :mod:`cmd.run_all <salt.modules.cmdmod.run_all>` within a container
.. note::
While the command is run within the container, it is initiated from the
host. Therefore, the PID in the return dict is from the host, not from
the container.
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed in stderr if the command being run
does not exist.
name
Name of the container in which to run the command
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
cmd
Command to run
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console
``output=all``.
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
CLI Example:
.. code-block:: bash
salt myminion lxc.run_all mycontainer 'ip addr show'
'''
return _run(name,
cmd,
output='all',
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
path=path,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def _get_md5(name, path):
'''
Get the MD5 checksum of a file from a container
'''
output = run_stdout(name, 'md5sum "{0}"'.format(path),
chroot_fallback=True,
ignore_retcode=True)
try:
return output.split()[0]
except IndexError:
# Destination file does not exist or could not be accessed
return None
def copy_to(name, source, dest, overwrite=False, makedirs=False, path=None):
'''
.. versionchanged:: 2015.8.0
Function renamed from ``lxc.cp`` to ``lxc.copy_to`` for consistency
with other container types. ``lxc.cp`` will continue to work, however.
For versions 2015.2.x and earlier, use ``lxc.cp``.
Copy a file or directory from the host into a container
name
Container name
source
File to be copied to the container
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
dest
Destination on the container. Must be an absolute path.
.. versionchanged:: 2015.5.0
If the destination is a directory, the file will be copied into
that directory.
overwrite : False
Unless this option is set to ``True``, then if a file exists at the
location specified by the ``dest`` argument, an error will be raised.
.. versionadded:: 2015.8.0
makedirs : False
Create the parent directory on the container if it does not already
exist.
.. versionadded:: 2015.5.0
CLI Example:
.. code-block:: bash
salt 'minion' lxc.copy_to /tmp/foo /root/foo
salt 'minion' lxc.cp /tmp/foo /root/foo
'''
_ensure_running(name, no_start=True, path=path)
return __salt__['container_resource.copy_to'](
name,
source,
dest,
container_type=__virtualname__,
path=path,
exec_driver=EXEC_DRIVER,
overwrite=overwrite,
makedirs=makedirs)
cp = salt.utils.functools.alias_function(copy_to, 'cp')
def read_conf(conf_file, out_format='simple'):
'''
Read in an LXC configuration file. By default returns a simple, unsorted
dict, but can also return a more detailed structure including blank lines
and comments.
out_format:
set to 'simple' if you need the old and unsupported behavior.
This won't support the multiple lxc values (eg: multiple network nics)
CLI Examples:
.. code-block:: bash
salt 'minion' lxc.read_conf /etc/lxc/mycontainer.conf
salt 'minion' lxc.read_conf /etc/lxc/mycontainer.conf out_format=commented
'''
ret_commented = []
ret_simple = {}
with salt.utils.files.fopen(conf_file, 'r') as fp_:
for line in salt.utils.data.decode(fp_.readlines()):
if '=' not in line:
ret_commented.append(line)
continue
comps = line.split('=')
value = '='.join(comps[1:]).strip()
comment = None
if value.strip().startswith('#'):
vcomps = value.strip().split('#')
value = vcomps[1].strip()
comment = '#'.join(vcomps[1:]).strip()
ret_commented.append({comps[0].strip(): {
'value': value,
'comment': comment,
}})
else:
ret_commented.append({comps[0].strip(): value})
ret_simple[comps[0].strip()] = value
if out_format == 'simple':
return ret_simple
return ret_commented
def write_conf(conf_file, conf):
'''
Write out an LXC configuration file
This is normally only used internally. The format of the data structure
must match that which is returned from ``lxc.read_conf()``, with
``out_format`` set to ``commented``.
An example might look like:
.. code-block:: python
[
{'lxc.utsname': '$CONTAINER_NAME'},
'# This is a commented line\\n',
'\\n',
{'lxc.mount': '$CONTAINER_FSTAB'},
{'lxc.rootfs': {'comment': 'This is another test',
'value': 'This is another test'}},
'\\n',
{'lxc.network.type': 'veth'},
{'lxc.network.flags': 'up'},
{'lxc.network.link': 'br0'},
{'lxc.network.mac': '$CONTAINER_MACADDR'},
{'lxc.network.ipv4': '$CONTAINER_IPADDR'},
{'lxc.network.name': '$CONTAINER_DEVICENAME'},
]
CLI Example:
.. code-block:: bash
salt 'minion' lxc.write_conf /etc/lxc/mycontainer.conf \\
out_format=commented
'''
if not isinstance(conf, list):
raise SaltInvocationError('Configuration must be passed as a list')
# construct the content prior to write to the file
# to avoid half written configs
content = ''
for line in conf:
if isinstance(line, (six.text_type, six.string_types)):
content += line
elif isinstance(line, dict):
for key in list(line.keys()):
out_line = None
if isinstance(
line[key],
(six.text_type, six.string_types, six.integer_types, float)
):
out_line = ' = '.join((key, "{0}".format(line[key])))
elif isinstance(line[key], dict):
out_line = ' = '.join((key, line[key]['value']))
if 'comment' in line[key]:
out_line = ' # '.join((out_line, line[key]['comment']))
if out_line:
content += out_line
content += '\n'
with salt.utils.files.fopen(conf_file, 'w') as fp_:
fp_.write(salt.utils.stringutils.to_str(content))
return {}
def edit_conf(conf_file,
out_format='simple',
read_only=False,
lxc_config=None,
**kwargs):
'''
Edit an LXC configuration file. If a setting is already present inside the
file, its value will be replaced. If it does not exist, it will be appended
to the end of the file. Comments and blank lines will be kept in-tact if
they already exist in the file.
out_format:
Set to simple if you need backward compatibility (multiple items for a
simple key is not supported)
read_only:
return only the edited configuration without applying it
to the underlying lxc configuration file
lxc_config:
List of dict containning lxc configuration items
For network configuration, you also need to add the device it belongs
to, otherwise it will default to eth0.
Also, any change to a network parameter will result in the whole
network reconfiguration to avoid mismatchs, be aware of that !
After the file is edited, its contents will be returned. By default, it
will be returned in ``simple`` format, meaning an unordered dict (which
may not represent the actual file order). Passing in an ``out_format`` of
``commented`` will return a data structure which accurately represents the
order and content of the file.
CLI Example:
.. code-block:: bash
salt 'minion' lxc.edit_conf /etc/lxc/mycontainer.conf \\
out_format=commented lxc.network.type=veth
salt 'minion' lxc.edit_conf /etc/lxc/mycontainer.conf \\
out_format=commented \\
lxc_config="[{'lxc.network.name': 'eth0', \\
'lxc.network.ipv4': '1.2.3.4'},
{'lxc.network.name': 'eth2', \\
'lxc.network.ipv4': '1.2.3.5',\\
'lxc.network.gateway': '1.2.3.1'}]"
'''
data = []
try:
conf = read_conf(conf_file, out_format=out_format)
except Exception:
conf = []
if not lxc_config:
lxc_config = []
lxc_config = copy.deepcopy(lxc_config)
# search if we want to access net config
# in that case, we will replace all the net configuration
net_config = []
for lxc_kws in lxc_config + [kwargs]:
net_params = {}
for kwarg in [a for a in lxc_kws]:
if kwarg.startswith('__'):
continue
if kwarg.startswith('lxc.network.'):
net_params[kwarg] = lxc_kws[kwarg]
lxc_kws.pop(kwarg, None)
if net_params:
net_config.append(net_params)
nic_opts = salt.utils.odict.OrderedDict()
for params in net_config:
dev = params.get('lxc.network.name', DEFAULT_NIC)
dev_opts = nic_opts.setdefault(dev, salt.utils.odict.OrderedDict())
for param in params:
opt = param.replace('lxc.network.', '')
opt = {'hwaddr': 'mac'}.get(opt, opt)
dev_opts[opt] = params[param]
net_changes = []
if nic_opts:
net_changes = _config_list(conf, only_net=True,
**{'network_profile': DEFAULT_NIC,
'nic_opts': nic_opts})
if net_changes:
lxc_config.extend(net_changes)
for line in conf:
if not isinstance(line, dict):
data.append(line)
continue
else:
for key in list(line.keys()):
val = line[key]
if net_changes and key.startswith('lxc.network.'):
continue
found = False
for ix in range(len(lxc_config)):
kw = lxc_config[ix]
if key in kw:
found = True
data.append({key: kw[key]})
del kw[key]
if not found:
data.append({key: val})
for lxc_kws in lxc_config:
for kwarg in lxc_kws:
data.append({kwarg: lxc_kws[kwarg]})
if read_only:
return data
write_conf(conf_file, data)
return read_conf(conf_file, out_format)
def reboot(name, path=None):
'''
Reboot a container.
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Examples:
.. code-block:: bash
salt 'minion' lxc.reboot myvm
'''
ret = {'result': True,
'changes': {},
'comment': '{0} rebooted'.format(name)}
does_exist = exists(name, path=path)
if does_exist and (state(name, path=path) == 'running'):
try:
stop(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
ret['result'] = False
return ret
if does_exist and (state(name, path=path) != 'running'):
try:
start(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
ret['result'] = False
return ret
ret['changes'][name] = 'rebooted'
return ret
def reconfigure(name,
cpu=None,
cpuset=None,
cpushare=None,
memory=None,
profile=None,
network_profile=None,
nic_opts=None,
bridge=None,
gateway=None,
autostart=None,
utsname=None,
rootfs=None,
path=None,
**kwargs):
'''
Reconfigure a container.
This only applies to a few property
name
Name of the container.
utsname
utsname of the container.
.. versionadded:: 2016.3.0
rootfs
rootfs of the container.
.. versionadded:: 2016.3.0
cpu
Select a random number of cpu cores and assign it to the cpuset, if the
cpuset option is set then this option will be ignored
cpuset
Explicitly define the cpus this container will be bound to
cpushare
cgroups cpu shares.
autostart
autostart container on reboot
memory
cgroups memory limit, in MB.
(0 for nolimit, None for old default 1024MB)
gateway
the ipv4 gateway to use
the default does nothing more than lxcutils does
bridge
the bridge to use
the default does nothing more than lxcutils does
nic
Network interfaces profile (defined in config or pillar).
nic_opts
Extra options for network interfaces, will override
``{"eth0": {"mac": "aa:bb:cc:dd:ee:ff", "ipv4": "10.1.1.1", "ipv6": "2001:db8::ff00:42:8329"}}``
or
``{"eth0": {"mac": "aa:bb:cc:dd:ee:ff", "ipv4": "10.1.1.1/24", "ipv6": "2001:db8::ff00:42:8329"}}``
path
path to the container parent
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt-call -lall mc_lxc_fork.reconfigure foobar nic_opts="{'eth1': {'mac': '00:16:3e:dd:ee:44'}}" memory=4
'''
changes = {}
cpath = get_root_path(path)
path = os.path.join(cpath, name, 'config')
ret = {'name': name,
'comment': 'config for {0} up to date'.format(name),
'result': True,
'changes': changes}
profile = get_container_profile(copy.deepcopy(profile))
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, _marker)
profile_match = profile.pop(key, default)
# let kwarg overrides be the preferred choice
if kw_overrides_match is _marker:
return profile_match
return kw_overrides_match
if nic_opts is not None and not network_profile:
network_profile = DEFAULT_NIC
if autostart is not None:
autostart = select('autostart', autostart)
else:
autostart = 'keep'
if not utsname:
utsname = select('utsname', utsname)
if os.path.exists(path):
old_chunks = read_conf(path, out_format='commented')
make_kw = salt.utils.odict.OrderedDict([
('utsname', utsname),
('rootfs', rootfs),
('autostart', autostart),
('cpu', cpu),
('gateway', gateway),
('cpuset', cpuset),
('cpushare', cpushare),
('network_profile', network_profile),
('nic_opts', nic_opts),
('bridge', bridge)])
# match 0 and none as memory = 0 in lxc config is harmful
if memory:
make_kw['memory'] = memory
kw = salt.utils.odict.OrderedDict()
for key, val in six.iteritems(make_kw):
if val is not None:
kw[key] = val
new_cfg = _config_list(conf_tuples=old_chunks, **kw)
if new_cfg:
edit_conf(path, out_format='commented', lxc_config=new_cfg)
chunks = read_conf(path, out_format='commented')
if old_chunks != chunks:
ret['comment'] = '{0} lxc config updated'.format(name)
if state(name, path=path) == 'running':
cret = reboot(name, path=path)
ret['result'] = cret['result']
return ret
def apply_network_profile(name, network_profile, nic_opts=None, path=None):
'''
.. versionadded:: 2015.5.0
Apply a network profile to a container
network_profile
profile name or default values (dict)
nic_opts
values to override in defaults (dict)
indexed by nic card names
path
path to the container parent
.. versionadded:: 2015.8.0
CLI Examples:
.. code-block:: bash
salt 'minion' lxc.apply_network_profile web1 centos
salt 'minion' lxc.apply_network_profile web1 centos \\
nic_opts="{'eth0': {'mac': 'xx:xx:xx:xx:xx:xx'}}"
salt 'minion' lxc.apply_network_profile web1 \\
"{'eth0': {'mac': 'xx:xx:xx:xx:xx:yy'}}"
nic_opts="{'eth0': {'mac': 'xx:xx:xx:xx:xx:xx'}}"
The special case to disable use of ethernet nics:
.. code-block:: bash
salt 'minion' lxc.apply_network_profile web1 centos \\
"{eth0: {disable: true}}"
'''
cpath = get_root_path(path)
cfgpath = os.path.join(cpath, name, 'config')
before = []
with salt.utils.files.fopen(cfgpath, 'r') as fp_:
for line in fp_:
before.append(line)
lxcconfig = _LXCConfig(name=name, path=path)
old_net = lxcconfig._filter_data('lxc.network')
network_params = {}
for param in _network_conf(
conf_tuples=old_net,
network_profile=network_profile, nic_opts=nic_opts
):
network_params.update(param)
if network_params:
edit_conf(cfgpath, out_format='commented', **network_params)
after = []
with salt.utils.files.fopen(cfgpath, 'r') as fp_:
for line in fp_:
after.append(line)
diff = ''
for line in difflib.unified_diff(before,
after,
fromfile='before',
tofile='after'):
diff += line
return diff
def get_pid(name, path=None):
'''
Returns a container pid.
Throw an exception if the container isn't running.
CLI Example:
.. code-block:: bash
salt '*' lxc.get_pid name
'''
if name not in list_(limit='running', path=path):
raise CommandExecutionError('Container {0} is not running, can\'t determine PID'.format(name))
info = __salt__['cmd.run']('lxc-info -n {0}'.format(name)).split("\n")
pid = [line.split(':')[1].strip() for line in info if re.match(r'\s*PID', line)][0]
return pid
def add_veth(name, interface_name, bridge=None, path=None):
'''
Add a veth to a container.
Note : this function doesn't update the container config, just add the interface at runtime
name
Name of the container
interface_name
Name of the interface in the container
bridge
Name of the bridge to attach the interface to (facultative)
CLI Examples:
.. code-block:: bash
salt '*' lxc.add_veth container_name eth1 br1
salt '*' lxc.add_veth container_name eth1
'''
# Get container init PID
pid = get_pid(name, path=path)
# Generate a ramdom string for veth and ensure that is isn't present on the system
while True:
random_veth = 'veth'+''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(6))
if random_veth not in __salt__['network.interfaces']().keys():
break
# Check prerequisites
if not __salt__['file.directory_exists']('/var/run/'):
raise CommandExecutionError('Directory /var/run required for lxc.add_veth doesn\'t exists')
if not __salt__['file.file_exists']('/proc/{0}/ns/net'.format(pid)):
raise CommandExecutionError('Proc file for container {0} network namespace doesn\'t exists'.format(name))
if not __salt__['file.directory_exists']('/var/run/netns'):
__salt__['file.mkdir']('/var/run/netns')
# Ensure that the symlink is up to date (change on container restart)
if __salt__['file.is_link']('/var/run/netns/{0}'.format(name)):
__salt__['file.remove']('/var/run/netns/{0}'.format(name))
__salt__['file.symlink']('/proc/{0}/ns/net'.format(pid), '/var/run/netns/{0}'.format(name))
# Ensure that interface doesn't exists
interface_exists = 0 == __salt__['cmd.retcode']('ip netns exec {netns} ip address list {interface}'.format(
netns=name,
interface=interface_name
))
if interface_exists:
raise CommandExecutionError('Interface {interface} already exists in {container}'.format(
interface=interface_name,
container=name
))
# Create veth and bring it up
if __salt__['cmd.retcode']('ip link add name {veth} type veth peer name {veth}_c'.format(veth=random_veth)) != 0:
raise CommandExecutionError('Error while creating the veth pair {0}'.format(random_veth))
if __salt__['cmd.retcode']('ip link set dev {0} up'.format(random_veth)) != 0:
raise CommandExecutionError('Error while bringing up host-side veth {0}'.format(random_veth))
# Attach it to the container
attached = 0 == __salt__['cmd.retcode']('ip link set dev {veth}_c netns {container} name {interface_name}'.format(
veth=random_veth,
container=name,
interface_name=interface_name
))
if not attached:
raise CommandExecutionError('Error while attaching the veth {veth} to container {container}'.format(
veth=random_veth,
container=name
))
__salt__['file.remove']('/var/run/netns/{0}'.format(name))
if bridge is not None:
__salt__['bridge.addif'](bridge, random_veth)
|
saltstack/salt
|
salt/modules/lxc.py
|
_ip_sort
|
python
|
def _ip_sort(ip):
'''Ip sorting'''
idx = '001'
if ip == '127.0.0.1':
idx = '200'
if ip == '::1':
idx = '201'
elif '::' in ip:
idx = '100'
return '{0}___{1}'.format(idx, ip)
|
Ip sorting
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/lxc.py#L144-L153
| null |
# -*- coding: utf-8 -*-
'''
Control Linux Containers via Salt
:depends: lxc package for distribution
lxc >= 1.0 (even beta alpha) is required
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import datetime
import copy
import string
import textwrap
import difflib
import logging
import tempfile
import os
import pipes
import time
import shutil
import re
import random
# Import salt libs
import salt.utils.args
import salt.utils.cloud
import salt.utils.data
import salt.utils.dictupdate
import salt.utils.files
import salt.utils.functools
import salt.utils.hashutils
import salt.utils.network
import salt.utils.odict
import salt.utils.path
import salt.utils.stringutils
from salt.exceptions import CommandExecutionError, SaltInvocationError
import salt.config
from salt.utils.versions import LooseVersion as _LooseVersion
# Import 3rd-party libs
from salt.ext import six
# pylint: disable=import-error,no-name-in-module
from salt.ext.six.moves import range # pylint: disable=redefined-builtin
from salt.ext.six.moves.urllib.parse import urlparse as _urlparse
# pylint: enable=import-error,no-name-in-module
# Set up logging
log = logging.getLogger(__name__)
# Don't shadow built-in's.
__func_alias__ = {
'list_': 'list',
'ls_': 'ls'
}
__virtualname__ = 'lxc'
DEFAULT_NIC = 'eth0'
DEFAULT_BR = 'br0'
SEED_MARKER = '/lxc.initial_seed'
EXEC_DRIVER = 'lxc-attach'
DEFAULT_PATH = '/var/lib/lxc'
_marker = object()
def __virtual__():
if salt.utils.path.which('lxc-start'):
return __virtualname__
# To speed up the whole thing, we decided to not use the
# subshell way and assume things are in place for lxc
# Discussion made by @kiorky and @thatch45
# lxc-version presence is not sufficient, in lxc1.0 alpha
# (precise backports), we have it and it is sufficient
# for the module to execute.
# elif salt.utils.path.which('lxc-version'):
# passed = False
# try:
# passed = subprocess.check_output(
# 'lxc-version').split(':')[1].strip() >= '1.0'
# except Exception:
# pass
# if not passed:
# log.warning('Support for lxc < 1.0 may be incomplete.')
# return 'lxc'
# return False
#
return (False, 'The lxc execution module cannot be loaded: the lxc-start binary is not in the path.')
def get_root_path(path):
'''
Get the configured lxc root for containers
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.get_root_path
'''
if not path:
path = __opts__.get('lxc.root_path', DEFAULT_PATH)
return path
def version():
'''
Return the actual lxc client version
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.version
'''
k = 'lxc.version'
if not __context__.get(k, None):
cversion = __salt__['cmd.run_all']('lxc-info --version')
if not cversion['retcode']:
ver = _LooseVersion(cversion['stdout'])
if ver < _LooseVersion('1.0'):
raise CommandExecutionError('LXC should be at least 1.0')
__context__[k] = "{0}".format(ver)
return __context__.get(k, None)
def _clear_context():
'''
Clear any lxc variables set in __context__
'''
for var in [x for x in __context__ if x.startswith('lxc.')]:
log.trace('Clearing __context__[\'%s\']', var)
__context__.pop(var, None)
def search_lxc_bridges():
'''
Search which bridges are potentially available as LXC bridges
CLI Example:
.. code-block:: bash
salt '*' lxc.search_lxc_bridges
'''
bridges = __context__.get('lxc.bridges', None)
# either match not yet called or no bridges were found
# to handle the case where lxc was not installed on the first
# call
if not bridges:
bridges = set()
running_bridges = set()
bridges.add(DEFAULT_BR)
try:
output = __salt__['cmd.run_all']('brctl show')
for line in output['stdout'].splitlines()[1:]:
if not line.startswith(' '):
running_bridges.add(line.split()[0].strip())
except (SaltInvocationError, CommandExecutionError):
pass
for ifc, ip in six.iteritems(
__grains__.get('ip_interfaces', {})
):
if ifc in running_bridges:
bridges.add(ifc)
elif os.path.exists(
'/sys/devices/virtual/net/{0}/bridge'.format(ifc)
):
bridges.add(ifc)
bridges = list(bridges)
# if we found interfaces that have lxc in their names
# we filter them as being the potential lxc bridges
# we also try to default on br0 on other cases
def sort_bridges(a):
pref = 'z'
if 'lxc' in a:
pref = 'a'
elif 'br0' == a:
pref = 'c'
return '{0}_{1}'.format(pref, a)
bridges.sort(key=sort_bridges)
__context__['lxc.bridges'] = bridges
return bridges
def search_lxc_bridge():
'''
Search the first bridge which is potentially available as LXC bridge
CLI Example:
.. code-block:: bash
salt '*' lxc.search_lxc_bridge
'''
return search_lxc_bridges()[0]
def _get_salt_config(config, **kwargs):
if not config:
config = kwargs.get('minion', {})
if not config:
config = {}
config.setdefault('master',
kwargs.get('master',
__opts__.get('master',
__opts__['id'])))
config.setdefault(
'master_port',
kwargs.get('master_port',
__opts__.get('master_port',
__opts__.get('ret_port',
__opts__.get('4506')))))
if not config['master']:
config = {}
return config
def cloud_init_interface(name, vm_=None, **kwargs):
'''
Interface between salt.cloud.lxc driver and lxc.init
``vm_`` is a mapping of vm opts in the salt.cloud format
as documented for the lxc driver.
This can be used either:
- from the salt cloud driver
- because you find the argument to give easier here
than using directly lxc.init
.. warning::
BE REALLY CAREFUL CHANGING DEFAULTS !!!
IT'S A RETRO COMPATIBLE INTERFACE WITH
THE SALT CLOUD DRIVER (ask kiorky).
name
name of the lxc container to create
pub_key
public key to preseed the minion with.
Can be the keycontent or a filepath
priv_key
private key to preseed the minion with.
Can be the keycontent or a filepath
path
path to the container parent directory (default: /var/lib/lxc)
.. versionadded:: 2015.8.0
profile
:ref:`profile <tutorial-lxc-profiles-container>` selection
network_profile
:ref:`network profile <tutorial-lxc-profiles-network>` selection
nic_opts
per interface settings compatibles with
network profile (ipv4/ipv6/link/gateway/mac/netmask)
eg::
- {'eth0': {'mac': '00:16:3e:01:29:40',
'gateway': None, (default)
'link': 'br0', (default)
'gateway': None, (default)
'netmask': '', (default)
'ip': '22.1.4.25'}}
unconditional_install
given to lxc.bootstrap (see relative doc)
force_install
given to lxc.bootstrap (see relative doc)
config
any extra argument for the salt minion config
dnsservers
list of DNS servers to set inside the container
dns_via_dhcp
do not set the dns servers, let them be set by the dhcp.
autostart
autostart the container at boot time
password
administrative password for the container
bootstrap_delay
delay before launching bootstrap script at Container init
.. warning::
Legacy but still supported options:
from_container
which container we use as a template
when running lxc.clone
image
which template do we use when we
are using lxc.create. This is the default
mode unless you specify something in from_container
backing
which backing store to use.
Values can be: overlayfs, dir(default), lvm, zfs, brtfs
fstype
When using a blockdevice level backing store,
which filesystem to use on
size
When using a blockdevice level backing store,
which size for the filesystem to use on
snapshot
Use snapshot when cloning the container source
vgname
if using LVM: vgname
lvname
if using LVM: lvname
thinpool:
if using LVM: thinpool
ip
ip for the primary nic
mac
mac address for the primary nic
netmask
netmask for the primary nic (24)
= ``vm_.get('netmask', '24')``
bridge
bridge for the primary nic (lxcbr0)
gateway
network gateway for the container
additional_ips
additional ips which will be wired on the main bridge (br0)
which is connected to internet.
Be aware that you may use manual virtual mac addresses
providen by you provider (online, ovh, etc).
This is a list of mappings {ip: '', mac: '', netmask:''}
Set gateway to None and an interface with a gateway
to escape from another interface that eth0.
eg::
- {'mac': '00:16:3e:01:29:40',
'gateway': None, (default)
'link': 'br0', (default)
'netmask': '', (default)
'ip': '22.1.4.25'}
users
administrative users for the container
default: [root] and [root, ubuntu] on ubuntu
default_nic
name of the first interface, you should
really not override this
CLI Example:
.. code-block:: bash
salt '*' lxc.cloud_init_interface foo
'''
if vm_ is None:
vm_ = {}
vm_ = copy.deepcopy(vm_)
vm_ = salt.utils.dictupdate.update(vm_, kwargs)
profile_data = copy.deepcopy(
vm_.get('lxc_profile',
vm_.get('profile', {})))
if not isinstance(profile_data, (dict, six.string_types)):
profile_data = {}
profile = get_container_profile(profile_data)
def _cloud_get(k, default=None):
return vm_.get(k, profile.get(k, default))
if name is None:
name = vm_['name']
# if we are on ubuntu, default to ubuntu
default_template = ''
if __grains__.get('os', '') in ['Ubuntu']:
default_template = 'ubuntu'
image = _cloud_get('image')
if not image:
_cloud_get('template', default_template)
backing = _cloud_get('backing', 'dir')
if image:
profile['template'] = image
vgname = _cloud_get('vgname', None)
if vgname:
profile['vgname'] = vgname
if backing:
profile['backing'] = backing
snapshot = _cloud_get('snapshot', False)
autostart = bool(_cloud_get('autostart', True))
dnsservers = _cloud_get('dnsservers', [])
dns_via_dhcp = _cloud_get('dns_via_dhcp', True)
password = _cloud_get('password', 's3cr3t')
password_encrypted = _cloud_get('password_encrypted', False)
fstype = _cloud_get('fstype', None)
lvname = _cloud_get('lvname', None)
thinpool = _cloud_get('thinpool', None)
pub_key = _cloud_get('pub_key', None)
priv_key = _cloud_get('priv_key', None)
size = _cloud_get('size', '20G')
script = _cloud_get('script', None)
script_args = _cloud_get('script_args', None)
users = _cloud_get('users', None)
if users is None:
users = []
ssh_username = _cloud_get('ssh_username', None)
if ssh_username and (ssh_username not in users):
users.append(ssh_username)
network_profile = _cloud_get('network_profile', None)
nic_opts = kwargs.get('nic_opts', None)
netmask = _cloud_get('netmask', '24')
path = _cloud_get('path', None)
bridge = _cloud_get('bridge', None)
gateway = _cloud_get('gateway', None)
unconditional_install = _cloud_get('unconditional_install', False)
force_install = _cloud_get('force_install', True)
config = _get_salt_config(_cloud_get('config', {}), **vm_)
default_nic = _cloud_get('default_nic', DEFAULT_NIC)
# do the interface with lxc.init mainly via nic_opts
# to avoid extra and confusing extra use cases.
if not isinstance(nic_opts, dict):
nic_opts = salt.utils.odict.OrderedDict()
# have a reference to the default nic
eth0 = nic_opts.setdefault(default_nic,
salt.utils.odict.OrderedDict())
# lxc config is based of ifc order, be sure to use odicts.
if not isinstance(nic_opts, salt.utils.odict.OrderedDict):
bnic_opts = salt.utils.odict.OrderedDict()
bnic_opts.update(nic_opts)
nic_opts = bnic_opts
gw = None
# legacy salt.cloud scheme for network interfaces settings support
bridge = _cloud_get('bridge', None)
ip = _cloud_get('ip', None)
mac = _cloud_get('mac', None)
if ip:
fullip = ip
if netmask:
fullip += '/{0}'.format(netmask)
eth0['ipv4'] = fullip
if mac is not None:
eth0['mac'] = mac
for ix, iopts in enumerate(_cloud_get("additional_ips", [])):
ifh = "eth{0}".format(ix+1)
ethx = nic_opts.setdefault(ifh, {})
if gw is None:
gw = iopts.get('gateway', ethx.get('gateway', None))
if gw:
# only one and only one default gateway is allowed !
eth0.pop('gateway', None)
gateway = None
# even if the gateway if on default "eth0" nic
# and we popped it will work
# as we reinject or set it here.
ethx['gateway'] = gw
elink = iopts.get('link', ethx.get('link', None))
if elink:
ethx['link'] = elink
# allow dhcp
aip = iopts.get('ipv4', iopts.get('ip', None))
if aip:
ethx['ipv4'] = aip
nm = iopts.get('netmask', '')
if nm:
ethx['ipv4'] += '/{0}'.format(nm)
for i in ('mac', 'hwaddr'):
if i in iopts:
ethx['mac'] = iopts[i]
break
if 'mac' not in ethx:
ethx['mac'] = salt.utils.network.gen_mac()
# last round checking for unique gateway and such
gw = None
for ethx in [a for a in nic_opts]:
ndata = nic_opts[ethx]
if gw:
ndata.pop('gateway', None)
if 'gateway' in ndata:
gw = ndata['gateway']
gateway = None
# only use a default bridge / gateway if we configured them
# via the legacy salt cloud configuration style.
# On other cases, we should rely on settings provided by the new
# salt lxc network profile style configuration which can
# be also be overridden or a per interface basis via the nic_opts dict.
if bridge:
eth0['link'] = bridge
if gateway:
eth0['gateway'] = gateway
#
lxc_init_interface = {}
lxc_init_interface['name'] = name
lxc_init_interface['config'] = config
lxc_init_interface['memory'] = _cloud_get('memory', 0) # nolimit
lxc_init_interface['pub_key'] = pub_key
lxc_init_interface['priv_key'] = priv_key
lxc_init_interface['nic_opts'] = nic_opts
for clone_from in ['clone_from', 'clone', 'from_container']:
# clone_from should default to None if not available
lxc_init_interface['clone_from'] = _cloud_get(clone_from, None)
if lxc_init_interface['clone_from'] is not None:
break
lxc_init_interface['profile'] = profile
lxc_init_interface['snapshot'] = snapshot
lxc_init_interface['dnsservers'] = dnsservers
lxc_init_interface['fstype'] = fstype
lxc_init_interface['path'] = path
lxc_init_interface['vgname'] = vgname
lxc_init_interface['size'] = size
lxc_init_interface['lvname'] = lvname
lxc_init_interface['thinpool'] = thinpool
lxc_init_interface['force_install'] = force_install
lxc_init_interface['unconditional_install'] = (
unconditional_install
)
lxc_init_interface['bootstrap_url'] = script
lxc_init_interface['bootstrap_args'] = script_args
lxc_init_interface['bootstrap_shell'] = _cloud_get('bootstrap_shell', 'sh')
lxc_init_interface['bootstrap_delay'] = _cloud_get('bootstrap_delay', None)
lxc_init_interface['autostart'] = autostart
lxc_init_interface['users'] = users
lxc_init_interface['password'] = password
lxc_init_interface['password_encrypted'] = password_encrypted
# be sure not to let objects goes inside the return
# as this return will be msgpacked for use in the runner !
lxc_init_interface['network_profile'] = network_profile
for i in ['cpu', 'cpuset', 'cpushare']:
if _cloud_get(i, None):
try:
lxc_init_interface[i] = vm_[i]
except KeyError:
lxc_init_interface[i] = profile[i]
return lxc_init_interface
def _get_profile(key, name, **kwargs):
if isinstance(name, dict):
profilename = name.pop('name', None)
return _get_profile(key, profilename, **name)
if name is None:
profile_match = {}
else:
profile_match = \
__salt__['config.get'](
'lxc.{1}:{0}'.format(name, key),
default=None,
merge='recurse'
)
if profile_match is None:
# No matching profile, make the profile an empty dict so that
# overrides can be applied below.
profile_match = {}
if not isinstance(profile_match, dict):
raise CommandExecutionError('lxc.{0} must be a dictionary'.format(key))
# Overlay the kwargs to override matched profile data
overrides = salt.utils.args.clean_kwargs(**copy.deepcopy(kwargs))
profile_match = salt.utils.dictupdate.update(
copy.deepcopy(profile_match),
overrides
)
return profile_match
def get_container_profile(name=None, **kwargs):
'''
.. versionadded:: 2015.5.0
Gather a pre-configured set of container configuration parameters. If no
arguments are passed, an empty profile is returned.
Profiles can be defined in the minion or master config files, or in pillar
or grains, and are loaded using :mod:`config.get
<salt.modules.config.get>`. The key under which LXC profiles must be
configured is ``lxc.container_profile.profile_name``. An example container
profile would be as follows:
.. code-block:: yaml
lxc.container_profile:
ubuntu:
template: ubuntu
backing: lvm
vgname: lxc
size: 1G
Parameters set in a profile can be overridden by passing additional
container creation arguments (such as the ones passed to :mod:`lxc.create
<salt.modules.lxc.create>`) to this function.
A profile can be defined either as the name of the profile, or a dictionary
of variable names and values. See the :ref:`LXC Tutorial
<tutorial-lxc-profiles>` for more information on how to use LXC profiles.
CLI Example:
.. code-block:: bash
salt-call lxc.get_container_profile centos
salt-call lxc.get_container_profile ubuntu template=ubuntu backing=overlayfs
'''
profile = _get_profile('container_profile', name, **kwargs)
return profile
def get_network_profile(name=None, **kwargs):
'''
.. versionadded:: 2015.5.0
Gather a pre-configured set of network configuration parameters. If no
arguments are passed, the following default profile is returned:
.. code-block:: python
{'eth0': {'link': 'br0', 'type': 'veth', 'flags': 'up'}}
Profiles can be defined in the minion or master config files, or in pillar
or grains, and are loaded using :mod:`config.get
<salt.modules.config.get>`. The key under which LXC profiles must be
configured is ``lxc.network_profile``. An example network profile would be
as follows:
.. code-block:: yaml
lxc.network_profile.centos:
eth0:
link: br0
type: veth
flags: up
To disable networking entirely:
.. code-block:: yaml
lxc.network_profile.centos:
eth0:
disable: true
Parameters set in a profile can be overridden by passing additional
arguments to this function.
A profile can be passed either as the name of the profile, or a
dictionary of variable names and values. See the :ref:`LXC Tutorial
<tutorial-lxc-profiles>` for more information on how to use network
profiles.
.. warning::
The ``ipv4``, ``ipv6``, ``gateway``, and ``link`` (bridge) settings in
network profiles will only work if the container doesn't redefine the
network configuration (for example in
``/etc/sysconfig/network-scripts/ifcfg-<interface_name>`` on
RHEL/CentOS, or ``/etc/network/interfaces`` on Debian/Ubuntu/etc.)
CLI Example:
.. code-block:: bash
salt-call lxc.get_network_profile default
'''
profile = _get_profile('network_profile', name, **kwargs)
return profile
def _rand_cpu_str(cpu):
'''
Return a random subset of cpus for the cpuset config
'''
cpu = int(cpu)
avail = __salt__['status.nproc']()
if cpu < avail:
return '0-{0}'.format(avail)
to_set = set()
while len(to_set) < cpu:
choice = random.randint(0, avail - 1)
if choice not in to_set:
to_set.add(six.text_type(choice))
return ','.join(sorted(to_set))
def _network_conf(conf_tuples=None, **kwargs):
'''
Network configuration defaults
network_profile
as for containers, we can either call this function
either with a network_profile dict or network profile name
in the kwargs
nic_opts
overrides or extra nics in the form {nic_name: {set: tings}
'''
nic = kwargs.get('network_profile', None)
ret = []
nic_opts = kwargs.get('nic_opts', {})
if nic_opts is None:
# coming from elsewhere
nic_opts = {}
if not conf_tuples:
conf_tuples = []
old = _get_veths(conf_tuples)
if not old:
old = {}
# if we have a profile name, get the profile and load the network settings
# this will obviously by default look for a profile called "eth0"
# or by what is defined in nic_opts
# and complete each nic settings by sane defaults
if nic and isinstance(nic, (six.string_types, dict)):
nicp = get_network_profile(nic)
else:
nicp = {}
if DEFAULT_NIC not in nicp:
nicp[DEFAULT_NIC] = {}
kwargs = copy.deepcopy(kwargs)
gateway = kwargs.pop('gateway', None)
bridge = kwargs.get('bridge', None)
if nic_opts:
for dev, args in six.iteritems(nic_opts):
ethx = nicp.setdefault(dev, {})
try:
ethx = salt.utils.dictupdate.update(ethx, args)
except AttributeError:
raise SaltInvocationError('Invalid nic_opts configuration')
ifs = [a for a in nicp]
ifs += [a for a in old if a not in nicp]
ifs.sort()
gateway_set = False
for dev in ifs:
args = nicp.get(dev, {})
opts = nic_opts.get(dev, {}) if nic_opts else {}
old_if = old.get(dev, {})
disable = opts.get('disable', args.get('disable', False))
if disable:
continue
mac = opts.get('mac',
opts.get('hwaddr',
args.get('mac',
args.get('hwaddr', ''))))
type_ = opts.get('type', args.get('type', ''))
flags = opts.get('flags', args.get('flags', ''))
link = opts.get('link', args.get('link', ''))
ipv4 = opts.get('ipv4', args.get('ipv4', ''))
ipv6 = opts.get('ipv6', args.get('ipv6', ''))
infos = salt.utils.odict.OrderedDict([
('lxc.network.type', {
'test': not type_,
'value': type_,
'old': old_if.get('lxc.network.type'),
'default': 'veth'}),
('lxc.network.name', {
'test': False,
'value': dev,
'old': dev,
'default': dev}),
('lxc.network.flags', {
'test': not flags,
'value': flags,
'old': old_if.get('lxc.network.flags'),
'default': 'up'}),
('lxc.network.link', {
'test': not link,
'value': link,
'old': old_if.get('lxc.network.link'),
'default': search_lxc_bridge()}),
('lxc.network.hwaddr', {
'test': not mac,
'value': mac,
'old': old_if.get('lxc.network.hwaddr'),
'default': salt.utils.network.gen_mac()}),
('lxc.network.ipv4', {
'test': not ipv4,
'value': ipv4,
'old': old_if.get('lxc.network.ipv4', ''),
'default': None}),
('lxc.network.ipv6', {
'test': not ipv6,
'value': ipv6,
'old': old_if.get('lxc.network.ipv6', ''),
'default': None})])
# for each parameter, if not explicitly set, the
# config value present in the LXC configuration should
# take precedence over the profile configuration
for info in list(infos.keys()):
bundle = infos[info]
if bundle['test']:
if bundle['old']:
bundle['value'] = bundle['old']
elif bundle['default']:
bundle['value'] = bundle['default']
for info, data in six.iteritems(infos):
if data['value']:
ret.append({info: data['value']})
for key, val in six.iteritems(args):
if key == 'link' and bridge:
val = bridge
val = opts.get(key, val)
if key in [
'type', 'flags', 'name',
'gateway', 'mac', 'link', 'ipv4', 'ipv6'
]:
continue
ret.append({'lxc.network.{0}'.format(key): val})
# gateway (in automode) must be appended following network conf !
if not gateway:
gateway = args.get('gateway', None)
if gateway is not None and not gateway_set:
ret.append({'lxc.network.ipv4.gateway': gateway})
# only one network gateway ;)
gateway_set = True
# normally, this won't happen
# set the gateway if specified even if we did
# not managed the network underlying
if gateway is not None and not gateway_set:
ret.append({'lxc.network.ipv4.gateway': gateway})
# only one network gateway ;)
gateway_set = True
new = _get_veths(ret)
# verify that we did not loose the mac settings
for iface in [a for a in new]:
ndata = new[iface]
nmac = ndata.get('lxc.network.hwaddr', '')
ntype = ndata.get('lxc.network.type', '')
omac, otype = '', ''
if iface in old:
odata = old[iface]
omac = odata.get('lxc.network.hwaddr', '')
otype = odata.get('lxc.network.type', '')
# default for network type is setted here
# attention not to change the network type
# without a good and explicit reason to.
if otype and not ntype:
ntype = otype
if not ntype:
ntype = 'veth'
new[iface]['lxc.network.type'] = ntype
if omac and not nmac:
new[iface]['lxc.network.hwaddr'] = omac
ret = []
for val in six.itervalues(new):
for row in val:
ret.append(salt.utils.odict.OrderedDict([(row, val[row])]))
# on old versions of lxc, still support the gateway auto mode
# if we didn't explicitly say no to
# (lxc.network.ipv4.gateway: auto)
if _LooseVersion(version()) <= _LooseVersion('1.0.7') and \
True not in ['lxc.network.ipv4.gateway' in a for a in ret] and \
True in ['lxc.network.ipv4' in a for a in ret]:
ret.append({'lxc.network.ipv4.gateway': 'auto'})
return ret
def _get_lxc_default_data(**kwargs):
kwargs = copy.deepcopy(kwargs)
ret = {}
for k in ['utsname', 'rootfs']:
val = kwargs.get(k, None)
if val is not None:
ret['lxc.{0}'.format(k)] = val
autostart = kwargs.get('autostart')
# autostart can have made in kwargs, but with the None
# value which is invalid, we need an explicit boolean
# autostart = on is the default.
if autostart is None:
autostart = True
# we will set the regular lxc marker to restart container at
# machine (re)boot only if we did not explicitly ask
# not to touch to the autostart settings via
# autostart == 'keep'
if autostart != 'keep':
if autostart:
ret['lxc.start.auto'] = '1'
else:
ret['lxc.start.auto'] = '0'
memory = kwargs.get('memory')
if memory is not None:
# converting the config value from MB to bytes
ret['lxc.cgroup.memory.limit_in_bytes'] = memory * 1024 * 1024
cpuset = kwargs.get('cpuset')
if cpuset:
ret['lxc.cgroup.cpuset.cpus'] = cpuset
cpushare = kwargs.get('cpushare')
cpu = kwargs.get('cpu')
if cpushare:
ret['lxc.cgroup.cpu.shares'] = cpushare
if cpu and not cpuset:
ret['lxc.cgroup.cpuset.cpus'] = _rand_cpu_str(cpu)
return ret
def _config_list(conf_tuples=None, only_net=False, **kwargs):
'''
Return a list of dicts from the salt level configurations
conf_tuples
_LXCConfig compatible list of entries which can contain
- string line
- tuple (lxc config param,value)
- dict of one entry: {lxc config param: value)
only_net
by default we add to the tuples a reflection of both
the real config if avalaible and a certain amount of
default values like the cpu parameters, the memory
and etc.
On the other hand, we also no matter the case reflect
the network configuration computed from the actual config if
available and given values.
if no_default_loads is set, we will only
reflect the network configuration back to the conf tuples
list
'''
# explicit cast
only_net = bool(only_net)
if not conf_tuples:
conf_tuples = []
kwargs = copy.deepcopy(kwargs)
ret = []
if not only_net:
default_data = _get_lxc_default_data(**kwargs)
for k, val in six.iteritems(default_data):
ret.append({k: val})
net_datas = _network_conf(conf_tuples=conf_tuples, **kwargs)
ret.extend(net_datas)
return ret
def _get_veths(net_data):
'''
Parse the nic setup inside lxc conf tuples back to a dictionary indexed by
network interface
'''
if isinstance(net_data, dict):
net_data = list(net_data.items())
nics = salt.utils.odict.OrderedDict()
current_nic = salt.utils.odict.OrderedDict()
no_names = True
for item in net_data:
if item and isinstance(item, dict):
item = list(item.items())[0]
# skip LXC configuration comment lines, and play only with tuples conf
elif isinstance(item, six.string_types):
# deal with reflection of commented lxc configs
sitem = item.strip()
if sitem.startswith('#') or not sitem:
continue
elif '=' in item:
item = tuple([a.strip() for a in item.split('=', 1)])
if item[0] == 'lxc.network.type':
current_nic = salt.utils.odict.OrderedDict()
if item[0] == 'lxc.network.name':
no_names = False
nics[item[1].strip()] = current_nic
current_nic[item[0].strip()] = item[1].strip()
# if not ethernet card name has been collected, assuming we collected
# data for eth0
if no_names and current_nic:
nics[DEFAULT_NIC] = current_nic
return nics
class _LXCConfig(object):
'''
LXC configuration data
'''
pattern = re.compile(r'^(\S+)(\s*)(=)(\s*)(.*)')
non_interpretable_pattern = re.compile(r'^((#.*)|(\s*))$')
def __init__(self, **kwargs):
kwargs = copy.deepcopy(kwargs)
self.name = kwargs.pop('name', None)
path = get_root_path(kwargs.get('path', None))
self.data = []
if self.name:
self.path = os.path.join(path, self.name, 'config')
if os.path.isfile(self.path):
with salt.utils.files.fopen(self.path) as fhr:
for line in salt.utils.data.decode(fhr.readlines()):
match = self.pattern.findall((line.strip()))
if match:
self.data.append((match[0][0], match[0][-1]))
match = self.non_interpretable_pattern.findall(
(line.strip()))
if match:
self.data.append(('', match[0][0]))
else:
self.path = None
def _replace(key, val):
if val:
self._filter_data(key)
self.data.append((key, val))
default_data = _get_lxc_default_data(**kwargs)
for key, val in six.iteritems(default_data):
_replace(key, val)
old_net = self._filter_data('lxc.network')
net_datas = _network_conf(conf_tuples=old_net, **kwargs)
if net_datas:
for row in net_datas:
self.data.extend(list(row.items()))
# be sure to reset harmful settings
for idx in ['lxc.cgroup.memory.limit_in_bytes']:
if not default_data.get(idx):
self._filter_data(idx)
def as_string(self):
chunks = ('{0[0]}{1}{0[1]}'.format(item, (' = ' if item[0] else '')) for item in self.data)
return '\n'.join(chunks) + '\n'
def write(self):
if self.path:
content = self.as_string()
# 2 step rendering to be sure not to open/wipe the config
# before as_string succeeds.
with salt.utils.files.fopen(self.path, 'w') as fic:
fic.write(salt.utils.stringutils.to_str(content))
fic.flush()
def tempfile(self):
# this might look like the function name is shadowing the
# module, but it's not since the method belongs to the class
ntf = tempfile.NamedTemporaryFile()
ntf.write(self.as_string())
ntf.flush()
return ntf
def _filter_data(self, pattern):
'''
Removes parameters which match the pattern from the config data
'''
removed = []
filtered = []
for param in self.data:
if not param[0].startswith(pattern):
filtered.append(param)
else:
removed.append(param)
self.data = filtered
return removed
def _get_base(**kwargs):
'''
If the needed base does not exist, then create it, if it does exist
create nothing and return the name of the base lxc container so
it can be cloned.
'''
profile = get_container_profile(copy.deepcopy(kwargs.get('profile')))
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, _marker)
profile_match = profile.pop(key, default)
# let kwarg overrides be the preferred choice
if kw_overrides_match is _marker:
return profile_match
return kw_overrides_match
template = select('template')
image = select('image')
vgname = select('vgname')
path = kwargs.get('path', None)
# remove the above three variables from kwargs, if they exist, to avoid
# duplicates if create() is invoked below.
for param in ('path', 'image', 'vgname', 'template'):
kwargs.pop(param, None)
if image:
proto = _urlparse(image).scheme
img_tar = __salt__['cp.cache_file'](image)
img_name = os.path.basename(img_tar)
hash_ = salt.utils.hashutils.get_hash(
img_tar,
__salt__['config.get']('hash_type'))
name = '__base_{0}_{1}_{2}'.format(proto, img_name, hash_)
if not exists(name, path=path):
create(name, template=template, image=image,
path=path, vgname=vgname, **kwargs)
if vgname:
rootfs = os.path.join('/dev', vgname, name)
edit_conf(info(name, path=path)['config'],
out_format='commented', **{'lxc.rootfs': rootfs})
return name
elif template:
name = '__base_{0}'.format(template)
if not exists(name, path=path):
create(name, template=template, image=image, path=path,
vgname=vgname, **kwargs)
if vgname:
rootfs = os.path.join('/dev', vgname, name)
edit_conf(info(name, path=path)['config'],
out_format='commented', **{'lxc.rootfs': rootfs})
return name
return ''
def init(name,
config=None,
cpuset=None,
cpushare=None,
memory=None,
profile=None,
network_profile=None,
nic_opts=None,
cpu=None,
autostart=True,
password=None,
password_encrypted=None,
users=None,
dnsservers=None,
searchdomains=None,
bridge=None,
gateway=None,
pub_key=None,
priv_key=None,
force_install=False,
unconditional_install=False,
bootstrap_delay=None,
bootstrap_args=None,
bootstrap_shell=None,
bootstrap_url=None,
**kwargs):
'''
Initialize a new container.
This is a partial idempotent function as if it is already provisioned, we
will reset a bit the lxc configuration file but much of the hard work will
be escaped as markers will prevent re-execution of harmful tasks.
name
Name of the container
image
A tar archive to use as the rootfs for the container. Conflicts with
the ``template`` argument.
cpus
Select a random number of cpu cores and assign it to the cpuset, if the
cpuset option is set then this option will be ignored
cpuset
Explicitly define the cpus this container will be bound to
cpushare
cgroups cpu shares
autostart
autostart container on reboot
memory
cgroups memory limit, in MB
.. versionchanged:: 2015.5.0
If no value is passed, no limit is set. In earlier Salt versions,
not passing this value causes a 1024MB memory limit to be set, and
it was necessary to pass ``memory=0`` to set no limit.
gateway
the ipv4 gateway to use
the default does nothing more than lxcutils does
bridge
the bridge to use
the default does nothing more than lxcutils does
network_profile
Network profile to use for the container
.. versionadded:: 2015.5.0
nic_opts
Extra options for network interfaces, will override
``{"eth0": {"hwaddr": "aa:bb:cc:dd:ee:ff", "ipv4": "10.1.1.1", "ipv6": "2001:db8::ff00:42:8329"}}``
or
``{"eth0": {"hwaddr": "aa:bb:cc:dd:ee:ff", "ipv4": "10.1.1.1/24", "ipv6": "2001:db8::ff00:42:8329"}}``
users
Users for which the password defined in the ``password`` param should
be set. Can be passed as a comma separated list or a python list.
Defaults to just the ``root`` user.
password
Set the initial password for the users defined in the ``users``
parameter
password_encrypted : False
Set to ``True`` to denote a password hash instead of a plaintext
password
.. versionadded:: 2015.5.0
profile
A LXC profile (defined in config or pillar).
This can be either a real profile mapping or a string
to retrieve it in configuration
start
Start the newly-created container
dnsservers
list of dns servers to set in the container, default [] (no setting)
seed
Seed the container with the minion config. Default: ``True``
install
If salt-minion is not already installed, install it. Default: ``True``
config
Optional config parameters. By default, the id is set to
the name of the container.
master
salt master (default to minion's master)
master_port
salt master port (default to minion's master port)
pub_key
Explicit public key to preseed the minion with (optional).
This can be either a filepath or a string representing the key
priv_key
Explicit private key to preseed the minion with (optional).
This can be either a filepath or a string representing the key
approve_key
If explicit preseeding is not used;
Attempt to request key approval from the master. Default: ``True``
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
clone_from
Original from which to use a clone operation to create the container.
Default: ``None``
bootstrap_delay
Delay in seconds between end of container creation and bootstrapping.
Useful when waiting for container to obtain a DHCP lease.
.. versionadded:: 2015.5.0
bootstrap_url
See lxc.bootstrap
bootstrap_shell
See lxc.bootstrap
bootstrap_args
See lxc.bootstrap
force_install
Force installation even if salt-minion is detected,
this is the way to run vendor bootstrap scripts even
if a salt minion is already present in the container
unconditional_install
Run the script even if the container seems seeded
CLI Example:
.. code-block:: bash
salt 'minion' lxc.init name [cpuset=cgroups_cpuset] \\
[cpushare=cgroups_cpushare] [memory=cgroups_memory] \\
[nic=nic_profile] [profile=lxc_profile] \\
[nic_opts=nic_opts] [start=(True|False)] \\
[seed=(True|False)] [install=(True|False)] \\
[config=minion_config] [approve_key=(True|False) \\
[clone_from=original] [autostart=True] \\
[priv_key=/path_or_content] [pub_key=/path_or_content] \\
[bridge=lxcbr0] [gateway=10.0.3.1] \\
[dnsservers[dns1,dns2]] \\
[users=[foo]] [password='secret'] \\
[password_encrypted=(True|False)]
'''
ret = {'name': name,
'changes': {}}
profile = get_container_profile(copy.deepcopy(profile))
if not network_profile:
network_profile = profile.get('network_profile')
if not network_profile:
network_profile = DEFAULT_NIC
# Changes is a pointer to changes_dict['init']. This method is used so that
# we can have a list of changes as they are made, providing an ordered list
# of things that were changed.
changes_dict = {'init': []}
changes = changes_dict.get('init')
if users is None:
users = []
dusers = ['root']
for user in dusers:
if user not in users:
users.append(user)
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, _marker)
profile_match = profile.pop(key, default)
# let kwarg overrides be the preferred choice
if kw_overrides_match is _marker:
return profile_match
return kw_overrides_match
path = select('path')
bpath = get_root_path(path)
state_pre = state(name, path=path)
tvg = select('vgname')
vgname = tvg if tvg else __salt__['config.get']('lxc.vgname')
start_ = select('start', True)
autostart = select('autostart', autostart)
seed = select('seed', True)
install = select('install', True)
seed_cmd = select('seed_cmd')
salt_config = _get_salt_config(config, **kwargs)
approve_key = select('approve_key', True)
clone_from = select('clone_from')
# If using a volume group then set up to make snapshot cow clones
if vgname and not clone_from:
try:
kwargs['vgname'] = vgname
clone_from = _get_base(profile=profile, **kwargs)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = exc.strerror
if changes:
ret['changes'] = changes_dict
return ret
if not kwargs.get('snapshot') is False:
kwargs['snapshot'] = True
does_exist = exists(name, path=path)
to_reboot = False
remove_seed_marker = False
if does_exist:
pass
elif clone_from:
remove_seed_marker = True
try:
clone(name, clone_from, profile=profile, **kwargs)
changes.append({'create': 'Container cloned'})
except (SaltInvocationError, CommandExecutionError) as exc:
if 'already exists' in exc.strerror:
changes.append({'create': 'Container already exists'})
else:
ret['result'] = False
ret['comment'] = exc.strerror
if changes:
ret['changes'] = changes_dict
return ret
cfg = _LXCConfig(name=name, network_profile=network_profile,
nic_opts=nic_opts, bridge=bridge, path=path,
gateway=gateway, autostart=autostart,
cpuset=cpuset, cpushare=cpushare, memory=memory)
old_chunks = read_conf(cfg.path, out_format='commented')
cfg.write()
chunks = read_conf(cfg.path, out_format='commented')
if old_chunks != chunks:
to_reboot = True
else:
remove_seed_marker = True
cfg = _LXCConfig(network_profile=network_profile,
nic_opts=nic_opts, cpuset=cpuset, path=path,
bridge=bridge, gateway=gateway,
autostart=autostart,
cpushare=cpushare, memory=memory)
with cfg.tempfile() as cfile:
try:
create(name, config=cfile.name, profile=profile, **kwargs)
changes.append({'create': 'Container created'})
except (SaltInvocationError, CommandExecutionError) as exc:
if 'already exists' in exc.strerror:
changes.append({'create': 'Container already exists'})
else:
ret['comment'] = exc.strerror
if changes:
ret['changes'] = changes_dict
return ret
cpath = os.path.join(bpath, name, 'config')
old_chunks = []
if os.path.exists(cpath):
old_chunks = read_conf(cpath, out_format='commented')
new_cfg = _config_list(conf_tuples=old_chunks,
cpu=cpu,
network_profile=network_profile,
nic_opts=nic_opts, bridge=bridge,
cpuset=cpuset, cpushare=cpushare,
memory=memory)
if new_cfg:
edit_conf(cpath, out_format='commented', lxc_config=new_cfg)
chunks = read_conf(cpath, out_format='commented')
if old_chunks != chunks:
to_reboot = True
# last time to be sure any of our property is correctly applied
cfg = _LXCConfig(name=name, network_profile=network_profile,
nic_opts=nic_opts, bridge=bridge, path=path,
gateway=gateway, autostart=autostart,
cpuset=cpuset, cpushare=cpushare, memory=memory)
old_chunks = []
if os.path.exists(cfg.path):
old_chunks = read_conf(cfg.path, out_format='commented')
cfg.write()
chunks = read_conf(cfg.path, out_format='commented')
if old_chunks != chunks:
changes.append({'config': 'Container configuration updated'})
to_reboot = True
if to_reboot:
try:
stop(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
if changes:
ret['changes'] = changes_dict
return ret
if not does_exist or (does_exist and state(name, path=path) != 'running'):
try:
start(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
if changes:
ret['changes'] = changes_dict
return ret
if remove_seed_marker:
run(name,
'rm -f \'{0}\''.format(SEED_MARKER),
path=path,
chroot_fallback=False,
python_shell=False)
# set the default user/password, only the first time
if ret.get('result', True) and password:
gid = '/.lxc.initial_pass'
gids = [gid,
'/lxc.initial_pass',
'/.lxc.{0}.initial_pass'.format(name)]
if not any(retcode(name,
'test -e "{0}"'.format(x),
chroot_fallback=True,
path=path,
ignore_retcode=True) == 0
for x in gids):
# think to touch the default user generated by default templates
# which has a really unsecure passwords...
# root is defined as a member earlier in the code
for default_user in ['ubuntu']:
if (
default_user not in users and
retcode(name,
'id {0}'.format(default_user),
python_shell=False,
path=path,
chroot_fallback=True,
ignore_retcode=True) == 0
):
users.append(default_user)
for user in users:
try:
cret = set_password(name,
users=[user],
path=path,
password=password,
encrypted=password_encrypted)
except (SaltInvocationError, CommandExecutionError) as exc:
msg = '{0}: Failed to set password'.format(
user) + exc.strerror
# only hardfail in unrecoverable situation:
# root cannot be setted up
if user == 'root':
ret['comment'] = msg
ret['result'] = False
else:
log.debug(msg)
if ret.get('result', True):
changes.append({'password': 'Password(s) updated'})
if retcode(name,
('sh -c \'touch "{0}"; test -e "{0}"\''
.format(gid)),
path=path,
chroot_fallback=True,
ignore_retcode=True) != 0:
ret['comment'] = 'Failed to set password marker'
changes[-1]['password'] += '. ' + ret['comment'] + '.'
ret['result'] = False
# set dns servers if any, only the first time
if ret.get('result', True) and dnsservers:
# retro compatibility, test also old markers
gid = '/.lxc.initial_dns'
gids = [gid,
'/lxc.initial_dns',
'/lxc.{0}.initial_dns'.format(name)]
if not any(retcode(name,
'test -e "{0}"'.format(x),
chroot_fallback=True,
path=path,
ignore_retcode=True) == 0
for x in gids):
try:
set_dns(name,
path=path,
dnsservers=dnsservers,
searchdomains=searchdomains)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Failed to set DNS: ' + exc.strerror
ret['result'] = False
else:
changes.append({'dns': 'DNS updated'})
if retcode(name,
('sh -c \'touch "{0}"; test -e "{0}"\''
.format(gid)),
chroot_fallback=True,
path=path,
ignore_retcode=True) != 0:
ret['comment'] = 'Failed to set DNS marker'
changes[-1]['dns'] += '. ' + ret['comment'] + '.'
ret['result'] = False
# retro compatibility, test also old markers
if remove_seed_marker:
run(name,
'rm -f \'{0}\''.format(SEED_MARKER),
path=path,
python_shell=False)
gid = '/.lxc.initial_seed'
gids = [gid, '/lxc.initial_seed']
if (
any(retcode(name,
'test -e {0}'.format(x),
path=path,
chroot_fallback=True,
ignore_retcode=True) == 0
for x in gids) or not ret.get('result', True)
):
pass
elif seed or seed_cmd:
if seed:
try:
result = bootstrap(
name, config=salt_config, path=path,
approve_key=approve_key,
pub_key=pub_key, priv_key=priv_key,
install=install,
force_install=force_install,
unconditional_install=unconditional_install,
bootstrap_delay=bootstrap_delay,
bootstrap_url=bootstrap_url,
bootstrap_shell=bootstrap_shell,
bootstrap_args=bootstrap_args)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Bootstrap failed: ' + exc.strerror
ret['result'] = False
else:
if not result:
ret['comment'] = ('Bootstrap failed, see minion log for '
'more information')
ret['result'] = False
else:
changes.append(
{'bootstrap': 'Container successfully bootstrapped'}
)
elif seed_cmd:
try:
result = __salt__[seed_cmd](info(name, path=path)['rootfs'],
name,
salt_config)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = ('Bootstrap via seed_cmd \'{0}\' failed: {1}'
.format(seed_cmd, exc.strerror))
ret['result'] = False
else:
if not result:
ret['comment'] = ('Bootstrap via seed_cmd \'{0}\' failed, '
'see minion log for more information '
.format(seed_cmd))
ret['result'] = False
else:
changes.append(
{'bootstrap': 'Container successfully bootstrapped '
'using seed_cmd \'{0}\''
.format(seed_cmd)}
)
if ret.get('result', True) and not start_:
try:
stop(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
ret['result'] = False
state_post = state(name, path=path)
if state_pre != state_post:
changes.append({'state': {'old': state_pre, 'new': state_post}})
if ret.get('result', True):
ret['comment'] = ('Container \'{0}\' successfully initialized'
.format(name))
ret['result'] = True
if changes:
ret['changes'] = changes_dict
return ret
def cloud_init(name, vm_=None, **kwargs):
'''
Thin wrapper to lxc.init to be used from the saltcloud lxc driver
name
Name of the container
may be None and then guessed from saltcloud mapping
`vm_`
saltcloud mapping defaults for the vm
CLI Example:
.. code-block:: bash
salt '*' lxc.cloud_init foo
'''
init_interface = cloud_init_interface(name, vm_, **kwargs)
name = init_interface.pop('name', name)
return init(name, **init_interface)
def images(dist=None):
'''
.. versionadded:: 2015.5.0
List the available images for LXC's ``download`` template.
dist : None
Filter results to a single Linux distribution
CLI Examples:
.. code-block:: bash
salt myminion lxc.images
salt myminion lxc.images dist=centos
'''
out = __salt__['cmd.run_stdout'](
'lxc-create -n __imgcheck -t download -- --list',
ignore_retcode=True
)
if 'DIST' not in out:
raise CommandExecutionError(
'Unable to run the \'download\' template script. Is it installed?'
)
ret = {}
passed_header = False
for line in out.splitlines():
try:
distro, release, arch, variant, build_time = line.split()
except ValueError:
continue
if not passed_header:
if distro == 'DIST':
passed_header = True
continue
dist_list = ret.setdefault(distro, [])
dist_list.append({
'release': release,
'arch': arch,
'variant': variant,
'build_time': build_time,
})
if dist is not None:
return dict([(dist, ret.get(dist, []))])
return ret
def templates():
'''
.. versionadded:: 2015.5.0
List the available LXC template scripts installed on the minion
CLI Examples:
.. code-block:: bash
salt myminion lxc.templates
'''
try:
template_scripts = os.listdir('/usr/share/lxc/templates')
except OSError:
return []
else:
return [x[4:] for x in template_scripts if x.startswith('lxc-')]
def _after_ignition_network_profile(cmd,
ret,
name,
network_profile,
path,
nic_opts):
_clear_context()
if ret['retcode'] == 0 and exists(name, path=path):
if network_profile:
network_changes = apply_network_profile(name,
network_profile,
path=path,
nic_opts=nic_opts)
if network_changes:
log.info(
'Network changes from applying network profile \'%s\' '
'to newly-created container \'%s\':\n%s',
network_profile, name, network_changes
)
c_state = state(name, path=path)
return {'result': True,
'state': {'old': None, 'new': c_state}}
else:
if exists(name, path=path):
# destroy the container if it was partially created
cmd = 'lxc-destroy'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0}'.format(name)
__salt__['cmd.retcode'](cmd, python_shell=False)
raise CommandExecutionError(
'Container could not be created with cmd \'{0}\': {1}'
.format(cmd, ret['stderr'])
)
def create(name,
config=None,
profile=None,
network_profile=None,
nic_opts=None,
**kwargs):
'''
Create a new container.
name
Name of the container
config
The config file to use for the container. Defaults to system-wide
config (usually in /etc/lxc/lxc.conf).
profile
Profile to use in container creation (see
:mod:`lxc.get_container_profile
<salt.modules.lxc.get_container_profile>`). Values in a profile will be
overridden by the **Container Creation Arguments** listed below.
network_profile
Network profile to use for container
.. versionadded:: 2015.5.0
**Container Creation Arguments**
template
The template to use. For example, ``ubuntu`` or ``fedora``.
For a full list of available templates, check out
the :mod:`lxc.templates <salt.modules.lxc.templates>` function.
Conflicts with the ``image`` argument.
.. note::
The ``download`` template requires the following three parameters
to be defined in ``options``:
* **dist** - The name of the distribution
* **release** - Release name/version
* **arch** - Architecture of the container
The available images can be listed using the :mod:`lxc.images
<salt.modules.lxc.images>` function.
options
Template-specific options to pass to the lxc-create command. These
correspond to the long options (ones beginning with two dashes) that
the template script accepts. For example:
.. code-block:: bash
options='{"dist": "centos", "release": "6", "arch": "amd64"}'
For available template options, refer to the lxc template scripts
which are ususally located under ``/usr/share/lxc/templates``,
or run ``lxc-create -t <template> -h``.
image
A tar archive to use as the rootfs for the container. Conflicts with
the ``template`` argument.
backing
The type of storage to use. Set to ``lvm`` to use an LVM group.
Defaults to filesystem within /var/lib/lxc.
fstype
Filesystem type to use on LVM logical volume
size : 1G
Size of the volume to create. Only applicable if ``backing=lvm``.
vgname : lxc
Name of the LVM volume group in which to create the volume for this
container. Only applicable if ``backing=lvm``.
lvname
Name of the LVM logical volume in which to create the volume for this
container. Only applicable if ``backing=lvm``.
thinpool
Name of a pool volume that will be used for thin-provisioning this
container. Only applicable if ``backing=lvm``.
nic_opts
give extra opts overriding network profile values
path
parent path for the container creation (default: /var/lib/lxc)
zfsroot
Name of the ZFS root in which to create the volume for this container.
Only applicable if ``backing=zfs``. (default: tank/lxc)
.. versionadded:: 2015.8.0
'''
# Required params for 'download' template
download_template_deps = ('dist', 'release', 'arch')
cmd = 'lxc-create -n {0}'.format(name)
profile = get_container_profile(copy.deepcopy(profile))
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, None)
profile_match = profile.pop(key, default)
# Return the profile match if the the kwarg match was None, as the
# lxc.present state will pass these kwargs set to None by default.
if kw_overrides_match is None:
return profile_match
return kw_overrides_match
path = select('path')
if exists(name, path=path):
raise CommandExecutionError(
'Container \'{0}\' already exists'.format(name)
)
tvg = select('vgname')
vgname = tvg if tvg else __salt__['config.get']('lxc.vgname')
# The 'template' and 'image' params conflict
template = select('template')
image = select('image')
if template and image:
raise SaltInvocationError(
'Only one of \'template\' and \'image\' is permitted'
)
elif not any((template, image, profile)):
raise SaltInvocationError(
'At least one of \'template\', \'image\', and \'profile\' is '
'required'
)
options = select('options') or {}
backing = select('backing')
if vgname and not backing:
backing = 'lvm'
lvname = select('lvname')
thinpool = select('thinpool')
fstype = select('fstype')
size = select('size', '1G')
zfsroot = select('zfsroot')
if backing in ('dir', 'overlayfs', 'btrfs', 'zfs'):
fstype = None
size = None
# some backends won't support some parameters
if backing in ('aufs', 'dir', 'overlayfs', 'btrfs'):
lvname = vgname = thinpool = None
if image:
img_tar = __salt__['cp.cache_file'](image)
template = os.path.join(
os.path.dirname(salt.__file__),
'templates',
'lxc',
'salt_tarball')
options['imgtar'] = img_tar
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
if not os.path.exists(path):
os.makedirs(path)
if config:
cmd += ' -f {0}'.format(config)
if template:
cmd += ' -t {0}'.format(template)
if backing:
backing = backing.lower()
cmd += ' -B {0}'.format(backing)
if backing in ('zfs',):
if zfsroot:
cmd += ' --zfsroot {0}'.format(zfsroot)
if backing in ('lvm',):
if lvname:
cmd += ' --lvname {0}'.format(lvname)
if vgname:
cmd += ' --vgname {0}'.format(vgname)
if thinpool:
cmd += ' --thinpool {0}'.format(thinpool)
if backing not in ('dir', 'overlayfs'):
if fstype:
cmd += ' --fstype {0}'.format(fstype)
if size:
cmd += ' --fssize {0}'.format(size)
if options:
if template == 'download':
missing_deps = [x for x in download_template_deps
if x not in options]
if missing_deps:
raise SaltInvocationError(
'Missing params in \'options\' dict: {0}'
.format(', '.join(missing_deps))
)
cmd += ' --'
for key, val in six.iteritems(options):
cmd += ' --{0} {1}'.format(key, val)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
# please do not merge extra conflicting stuff
# inside those two line (ret =, return)
return _after_ignition_network_profile(cmd,
ret,
name,
network_profile,
path,
nic_opts)
def clone(name,
orig,
profile=None,
network_profile=None,
nic_opts=None,
**kwargs):
'''
Create a new container as a clone of another container
name
Name of the container
orig
Name of the original container to be cloned
profile
Profile to use in container cloning (see
:mod:`lxc.get_container_profile
<salt.modules.lxc.get_container_profile>`). Values in a profile will be
overridden by the **Container Cloning Arguments** listed below.
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
**Container Cloning Arguments**
snapshot
Use Copy On Write snapshots (LVM)
size : 1G
Size of the volume to create. Only applicable if ``backing=lvm``.
backing
The type of storage to use. Set to ``lvm`` to use an LVM group.
Defaults to filesystem within /var/lib/lxc.
network_profile
Network profile to use for container
.. versionadded:: 2015.8.0
nic_opts
give extra opts overriding network profile values
.. versionadded:: 2015.8.0
CLI Examples:
.. code-block:: bash
salt '*' lxc.clone myclone orig=orig_container
salt '*' lxc.clone myclone orig=orig_container snapshot=True
'''
profile = get_container_profile(copy.deepcopy(profile))
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, None)
profile_match = profile.pop(key, default)
# let kwarg overrides be the preferred choice
if kw_overrides_match is None:
return profile_match
return kw_overrides_match
path = select('path')
if exists(name, path=path):
raise CommandExecutionError(
'Container \'{0}\' already exists'.format(name)
)
_ensure_exists(orig, path=path)
if state(orig, path=path) != 'stopped':
raise CommandExecutionError(
'Container \'{0}\' must be stopped to be cloned'.format(orig)
)
backing = select('backing')
snapshot = select('snapshot')
if backing in ('dir',):
snapshot = False
if not snapshot:
snapshot = ''
else:
snapshot = '-s'
size = select('size', '1G')
if backing in ('dir', 'overlayfs', 'btrfs'):
size = None
# LXC commands and options changed in 2.0 - CF issue #34086 for details
if _LooseVersion(version()) >= _LooseVersion('2.0'):
# https://linuxcontainers.org/lxc/manpages//man1/lxc-copy.1.html
cmd = 'lxc-copy'
cmd += ' {0} -n {1} -N {2}'.format(snapshot, orig, name)
else:
# https://linuxcontainers.org/lxc/manpages//man1/lxc-clone.1.html
cmd = 'lxc-clone'
cmd += ' {0} -o {1} -n {2}'.format(snapshot, orig, name)
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
if not os.path.exists(path):
os.makedirs(path)
if backing:
backing = backing.lower()
cmd += ' -B {0}'.format(backing)
if backing not in ('dir', 'overlayfs'):
if size:
cmd += ' -L {0}'.format(size)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
# please do not merge extra conflicting stuff
# inside those two line (ret =, return)
return _after_ignition_network_profile(cmd,
ret,
name,
network_profile,
path,
nic_opts)
def ls_(active=None, cache=True, path=None):
'''
Return a list of the containers available on the minion
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
active
If ``True``, return only active (i.e. running) containers
.. versionadded:: 2015.5.0
CLI Example:
.. code-block:: bash
salt '*' lxc.ls
salt '*' lxc.ls active=True
'''
contextvar = 'lxc.ls{0}'.format(path)
if active:
contextvar += '.active'
if cache and (contextvar in __context__):
return __context__[contextvar]
else:
ret = []
cmd = 'lxc-ls'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
if active:
cmd += ' --active'
output = __salt__['cmd.run_stdout'](cmd, python_shell=False)
for line in output.splitlines():
ret.extend(line.split())
__context__[contextvar] = ret
return ret
def list_(extra=False, limit=None, path=None):
'''
List containers classified by state
extra
Also get per-container specific info. This will change the return data.
Instead of returning a list of containers, a dictionary of containers
and each container's output from :mod:`lxc.info
<salt.modules.lxc.info>`.
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
limit
Return output matching a specific state (**frozen**, **running**, or
**stopped**).
.. versionadded:: 2015.5.0
CLI Examples:
.. code-block:: bash
salt '*' lxc.list
salt '*' lxc.list extra=True
salt '*' lxc.list limit=running
'''
ctnrs = ls_(path=path)
if extra:
stopped = {}
frozen = {}
running = {}
else:
stopped = []
frozen = []
running = []
ret = {'running': running,
'stopped': stopped,
'frozen': frozen}
for container in ctnrs:
cmd = 'lxc-info'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0}'.format(container)
c_info = __salt__['cmd.run'](
cmd,
python_shell=False,
output_loglevel='debug'
)
c_state = None
for line in c_info.splitlines():
stat = line.split(':')
if stat[0] in ('State', 'state'):
c_state = stat[1].strip()
break
if not c_state or (limit is not None and c_state.lower() != limit):
continue
if extra:
infos = info(container, path=path)
method = 'update'
value = {container: infos}
else:
method = 'append'
value = container
if c_state == 'STOPPED':
getattr(stopped, method)(value)
continue
if c_state == 'FROZEN':
getattr(frozen, method)(value)
continue
if c_state == 'RUNNING':
getattr(running, method)(value)
continue
if limit is not None:
return ret.get(limit, {} if extra else [])
return ret
def _change_state(cmd,
name,
expected,
stdin=_marker,
stdout=_marker,
stderr=_marker,
with_communicate=_marker,
use_vt=_marker,
path=None):
pre = state(name, path=path)
if pre == expected:
return {'result': True,
'state': {'old': expected, 'new': expected},
'comment': 'Container \'{0}\' already {1}'
.format(name, expected)}
if cmd == 'lxc-destroy':
# Kill the container first
scmd = 'lxc-stop'
if path:
scmd += ' -P {0}'.format(pipes.quote(path))
scmd += ' -k -n {0}'.format(name)
__salt__['cmd.run'](scmd,
python_shell=False)
if path and ' -P ' not in cmd:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0}'.format(name)
# certain lxc commands need to be taken with care (lxc-start)
# as te command itself mess with double forks; we must not
# communicate with it, but just wait for the exit status
pkwargs = {'python_shell': False,
'redirect_stderr': True,
'with_communicate': with_communicate,
'use_vt': use_vt,
'stdin': stdin,
'stdout': stdout}
for i in [a for a in pkwargs]:
val = pkwargs[i]
if val is _marker:
pkwargs.pop(i, None)
_cmdout = __salt__['cmd.run_all'](cmd, **pkwargs)
if _cmdout['retcode'] != 0:
raise CommandExecutionError(
'Error changing state for container \'{0}\' using command '
'\'{1}\': {2}'.format(name, cmd, _cmdout['stdout'])
)
if expected is not None:
# some commands do not wait, so we will
rcmd = 'lxc-wait'
if path:
rcmd += ' -P {0}'.format(pipes.quote(path))
rcmd += ' -n {0} -s {1}'.format(name, expected.upper())
__salt__['cmd.run'](rcmd, python_shell=False, timeout=30)
_clear_context()
post = state(name, path=path)
ret = {'result': post == expected,
'state': {'old': pre, 'new': post}}
return ret
def _ensure_exists(name, path=None):
'''
Raise an exception if the container does not exist
'''
if not exists(name, path=path):
raise CommandExecutionError(
'Container \'{0}\' does not exist'.format(name)
)
def _ensure_running(name, no_start=False, path=None):
'''
If the container is not currently running, start it. This function returns
the state that the container was in before changing
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
'''
_ensure_exists(name, path=path)
pre = state(name, path=path)
if pre == 'running':
# This will be a no-op but running the function will give us a pretty
# return dict.
return start(name, path=path)
elif pre == 'stopped':
if no_start:
raise CommandExecutionError(
'Container \'{0}\' is not running'.format(name)
)
return start(name, path=path)
elif pre == 'frozen':
if no_start:
raise CommandExecutionError(
'Container \'{0}\' is not running'.format(name)
)
return unfreeze(name, path=path)
def restart(name, path=None, lxc_config=None, force=False):
'''
.. versionadded:: 2015.5.0
Restart the named container. If the container was not running, the
container will merely be started.
name
The name of the container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
lxc_config
path to a lxc config file
config file will be guessed from container name otherwise
.. versionadded:: 2015.8.0
force : False
If ``True``, the container will be force-stopped instead of gracefully
shut down
CLI Example:
.. code-block:: bash
salt myminion lxc.restart name
'''
_ensure_exists(name, path=path)
orig_state = state(name, path=path)
if orig_state != 'stopped':
stop(name, kill=force, path=path)
ret = start(name, path=path, lxc_config=lxc_config)
ret['state']['old'] = orig_state
if orig_state != 'stopped':
ret['restarted'] = True
return ret
def start(name, **kwargs):
'''
Start the named container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
lxc_config
path to a lxc config file
config file will be guessed from container name otherwise
.. versionadded:: 2015.8.0
use_vt
run the command through VT
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.start name
'''
path = kwargs.get('path', None)
cpath = get_root_path(path)
lxc_config = kwargs.get('lxc_config', None)
cmd = 'lxc-start'
if not lxc_config:
lxc_config = os.path.join(cpath, name, 'config')
# we try to start, even without config, if global opts are there
if os.path.exists(lxc_config):
cmd += ' -f {0}'.format(pipes.quote(lxc_config))
cmd += ' -d'
_ensure_exists(name, path=path)
if state(name, path=path) == 'frozen':
raise CommandExecutionError(
'Container \'{0}\' is frozen, use lxc.unfreeze'.format(name)
)
# lxc-start daemonize itself violently, we must not communicate with it
use_vt = kwargs.get('use_vt', None)
with_communicate = kwargs.get('with_communicate', False)
return _change_state(cmd, name, 'running',
stdout=None,
stderr=None,
stdin=None,
with_communicate=with_communicate,
path=path,
use_vt=use_vt)
def stop(name, kill=False, path=None, use_vt=None):
'''
Stop the named container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
kill: False
Do not wait for the container to stop, kill all tasks in the container.
Older LXC versions will stop containers like this irrespective of this
argument.
.. versionchanged:: 2015.5.0
Default value changed to ``False``
use_vt
run the command through VT
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.stop name
'''
_ensure_exists(name, path=path)
orig_state = state(name, path=path)
if orig_state == 'frozen' and not kill:
# Gracefully stopping a frozen container is slower than unfreezing and
# then stopping it (at least in my testing), so if we're not
# force-stopping the container, unfreeze it first.
unfreeze(name, path=path)
cmd = 'lxc-stop'
if kill:
cmd += ' -k'
ret = _change_state(cmd, name, 'stopped', use_vt=use_vt, path=path)
ret['state']['old'] = orig_state
return ret
def freeze(name, **kwargs):
'''
Freeze the named container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
start : False
If ``True`` and the container is stopped, the container will be started
before attempting to freeze.
.. versionadded:: 2015.5.0
use_vt
run the command through VT
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.freeze name
'''
use_vt = kwargs.get('use_vt', None)
path = kwargs.get('path', None)
_ensure_exists(name, path=path)
orig_state = state(name, path=path)
start_ = kwargs.get('start', False)
if orig_state == 'stopped':
if not start_:
raise CommandExecutionError(
'Container \'{0}\' is stopped'.format(name)
)
start(name, path=path)
cmd = 'lxc-freeze'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
ret = _change_state(cmd, name, 'frozen', use_vt=use_vt, path=path)
if orig_state == 'stopped' and start_:
ret['state']['old'] = orig_state
ret['started'] = True
ret['state']['new'] = state(name, path=path)
return ret
def unfreeze(name, path=None, use_vt=None):
'''
Unfreeze the named container.
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
use_vt
run the command through VT
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.unfreeze name
'''
_ensure_exists(name, path=path)
if state(name, path=path) == 'stopped':
raise CommandExecutionError(
'Container \'{0}\' is stopped'.format(name)
)
cmd = 'lxc-unfreeze'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
return _change_state(cmd, name, 'running', path=path, use_vt=use_vt)
def destroy(name, stop=False, path=None):
'''
Destroy the named container.
.. warning::
Destroys all data associated with the container.
path
path to the container parent directory (default: /var/lib/lxc)
.. versionadded:: 2015.8.0
stop : False
If ``True``, the container will be destroyed even if it is
running/frozen.
.. versionchanged:: 2015.5.0
Default value changed to ``False``. This more closely matches the
behavior of ``lxc-destroy(1)``, and also makes it less likely that
an accidental command will destroy a running container that was
being used for important things.
CLI Examples:
.. code-block:: bash
salt '*' lxc.destroy foo
salt '*' lxc.destroy foo stop=True
'''
_ensure_exists(name, path=path)
if not stop and state(name, path=path) != 'stopped':
raise CommandExecutionError(
'Container \'{0}\' is not stopped'.format(name)
)
return _change_state('lxc-destroy', name, None, path=path)
# Compatibility between LXC and nspawn
remove = salt.utils.functools.alias_function(destroy, 'remove')
def exists(name, path=None):
'''
Returns whether the named container exists.
path
path to the container parent directory (default: /var/lib/lxc)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.exists name
'''
_exists = name in ls_(path=path)
# container may be just created but we did cached earlier the
# lxc-ls results
if not _exists:
_exists = name in ls_(cache=False, path=path)
return _exists
def state(name, path=None):
'''
Returns the state of a container.
path
path to the container parent directory (default: /var/lib/lxc)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.state name
'''
# Don't use _ensure_exists() here, it will mess with _change_state()
cachekey = 'lxc.state.{0}{1}'.format(name, path)
try:
return __context__[cachekey]
except KeyError:
if not exists(name, path=path):
__context__[cachekey] = None
else:
cmd = 'lxc-info'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0}'.format(name)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
if ret['retcode'] != 0:
_clear_context()
raise CommandExecutionError(
'Unable to get state of container \'{0}\''.format(name)
)
c_infos = ret['stdout'].splitlines()
c_state = None
for c_info in c_infos:
stat = c_info.split(':')
if stat[0].lower() == 'state':
c_state = stat[1].strip().lower()
break
__context__[cachekey] = c_state
return __context__[cachekey]
def get_parameter(name, parameter, path=None):
'''
Returns the value of a cgroup parameter for a container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.get_parameter container_name memory.limit_in_bytes
'''
_ensure_exists(name, path=path)
cmd = 'lxc-cgroup'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0} {1}'.format(name, parameter)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
if ret['retcode'] != 0:
raise CommandExecutionError(
'Unable to retrieve value for \'{0}\''.format(parameter)
)
return ret['stdout'].strip()
def set_parameter(name, parameter, value, path=None):
'''
Set the value of a cgroup parameter for a container.
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.set_parameter name parameter value
'''
if not exists(name, path=path):
return None
cmd = 'lxc-cgroup'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0} {1} {2}'.format(name, parameter, value)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
if ret['retcode'] != 0:
return False
else:
return True
def info(name, path=None):
'''
Returns information about a container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.info name
'''
cachekey = 'lxc.info.{0}{1}'.format(name, path)
try:
return __context__[cachekey]
except KeyError:
_ensure_exists(name, path=path)
cpath = get_root_path(path)
try:
conf_file = os.path.join(cpath, name, 'config')
except AttributeError:
conf_file = os.path.join(cpath, six.text_type(name), 'config')
if not os.path.isfile(conf_file):
raise CommandExecutionError(
'LXC config file {0} does not exist'.format(conf_file)
)
ret = {}
config = []
with salt.utils.files.fopen(conf_file) as fp_:
for line in fp_:
line = salt.utils.stringutils.to_unicode(line)
comps = [x.strip() for x in
line.split('#', 1)[0].strip().split('=', 1)]
if len(comps) == 2:
config.append(tuple(comps))
ifaces = []
current = None
for key, val in config:
if key == 'lxc.network.type':
current = {'type': val}
ifaces.append(current)
elif not current:
continue
elif key.startswith('lxc.network.'):
current[key.replace('lxc.network.', '', 1)] = val
if ifaces:
ret['nics'] = ifaces
ret['rootfs'] = next(
(x[1] for x in config if x[0] == 'lxc.rootfs'),
None
)
ret['state'] = state(name, path=path)
ret['ips'] = []
ret['public_ips'] = []
ret['private_ips'] = []
ret['public_ipv4_ips'] = []
ret['public_ipv6_ips'] = []
ret['private_ipv4_ips'] = []
ret['private_ipv6_ips'] = []
ret['ipv4_ips'] = []
ret['ipv6_ips'] = []
ret['size'] = None
ret['config'] = conf_file
if ret['state'] == 'running':
try:
limit = int(get_parameter(name, 'memory.limit_in_bytes'))
except (CommandExecutionError, TypeError, ValueError):
limit = 0
try:
usage = int(get_parameter(name, 'memory.usage_in_bytes'))
except (CommandExecutionError, TypeError, ValueError):
usage = 0
free = limit - usage
ret['memory_limit'] = limit
ret['memory_free'] = free
size = run_stdout(name, 'df /', path=path, python_shell=False)
# The size is the 2nd column of the last line
ret['size'] = size.splitlines()[-1].split()[1]
# First try iproute2
ip_cmd = run_all(
name, 'ip link show', path=path, python_shell=False)
if ip_cmd['retcode'] == 0:
ip_data = ip_cmd['stdout']
ip_cmd = run_all(
name, 'ip addr show', path=path, python_shell=False)
ip_data += '\n' + ip_cmd['stdout']
ip_data = salt.utils.network._interfaces_ip(ip_data)
else:
# That didn't work, try ifconfig
ip_cmd = run_all(
name, 'ifconfig', path=path, python_shell=False)
if ip_cmd['retcode'] == 0:
ip_data = \
salt.utils.network._interfaces_ifconfig(
ip_cmd['stdout'])
else:
# Neither was successful, give up
log.warning(
'Unable to run ip or ifconfig in container \'%s\'', name
)
ip_data = {}
ret['ipv4_ips'] = salt.utils.network.ip_addrs(
include_loopback=True,
interface_data=ip_data
)
ret['ipv6_ips'] = salt.utils.network.ip_addrs6(
include_loopback=True,
interface_data=ip_data
)
ret['ips'] = ret['ipv4_ips'] + ret['ipv6_ips']
for address in ret['ipv4_ips']:
if address == '127.0.0.1':
ret['private_ips'].append(address)
ret['private_ipv4_ips'].append(address)
elif salt.utils.cloud.is_public_ip(address):
ret['public_ips'].append(address)
ret['public_ipv4_ips'].append(address)
else:
ret['private_ips'].append(address)
ret['private_ipv4_ips'].append(address)
for address in ret['ipv6_ips']:
if address == '::1' or address.startswith('fe80'):
ret['private_ips'].append(address)
ret['private_ipv6_ips'].append(address)
else:
ret['public_ips'].append(address)
ret['public_ipv6_ips'].append(address)
for key in [x for x in ret if x == 'ips' or x.endswith('ips')]:
ret[key].sort(key=_ip_sort)
__context__[cachekey] = ret
return __context__[cachekey]
def set_password(name, users, password, encrypted=True, path=None):
'''
.. versionchanged:: 2015.5.0
Function renamed from ``set_pass`` to ``set_password``. Additionally,
this function now supports (and defaults to using) a password hash
instead of a plaintext password.
Set the password of one or more system users inside containers
users
Comma-separated list (or python list) of users to change password
password
Password to set for the specified user(s)
encrypted : True
If true, ``password`` must be a password hash. Set to ``False`` to set
a plaintext password (not recommended).
.. versionadded:: 2015.5.0
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.set_pass container-name root '$6$uJ2uAyLU$KoI67t8As/0fXtJOPcHKGXmUpcoYUcVR2K6x93walnShTCQvjRwq25yIkiCBOqgbfdKQSFnAo28/ek6716vEV1'
salt '*' lxc.set_pass container-name root foo encrypted=False
'''
def _bad_user_input():
raise SaltInvocationError('Invalid input for \'users\' parameter')
if not isinstance(users, list):
try:
users = users.split(',')
except AttributeError:
_bad_user_input()
if not users:
_bad_user_input()
failed_users = []
for user in users:
result = retcode(name,
'chpasswd{0}'.format(' -e' if encrypted else ''),
stdin=':'.join((user, password)),
python_shell=False,
path=path,
chroot_fallback=True,
output_loglevel='quiet')
if result != 0:
failed_users.append(user)
if failed_users:
raise CommandExecutionError(
'Password change failed for the following user(s): {0}'
.format(', '.join(failed_users))
)
return True
set_pass = salt.utils.functools.alias_function(set_password, 'set_pass')
def update_lxc_conf(name, lxc_conf, lxc_conf_unset, path=None):
'''
Edit LXC configuration options
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.update_lxc_conf ubuntu \\
lxc_conf="[{'network.ipv4.ip':'10.0.3.5'}]" \\
lxc_conf_unset="['lxc.utsname']"
'''
_ensure_exists(name, path=path)
cpath = get_root_path(path)
lxc_conf_p = os.path.join(cpath, name, 'config')
if not os.path.exists(lxc_conf_p):
raise SaltInvocationError(
'Configuration file {0} does not exist'.format(lxc_conf_p)
)
changes = {'edited': [], 'added': [], 'removed': []}
ret = {'changes': changes, 'result': True, 'comment': ''}
# do not use salt.utils.files.fopen !
with salt.utils.files.fopen(lxc_conf_p, 'r') as fic:
filtered_lxc_conf = []
for row in lxc_conf:
if not row:
continue
for conf in row:
filtered_lxc_conf.append((conf.strip(),
row[conf].strip()))
ret['comment'] = 'lxc.conf is up to date'
lines = []
orig_config = salt.utils.stringutils.to_unicode(fic.read())
for line in orig_config.splitlines():
if line.startswith('#') or not line.strip():
lines.append([line, ''])
else:
line = line.split('=')
index = line.pop(0)
val = (index.strip(), '='.join(line).strip())
if val not in lines:
lines.append(val)
for key, item in filtered_lxc_conf:
matched = False
for idx, line in enumerate(lines[:]):
if line[0] == key:
matched = True
lines[idx] = (key, item)
if '='.join(line[1:]).strip() != item.strip():
changes['edited'].append(
({line[0]: line[1:]}, {key: item}))
break
if not matched:
if (key, item) not in lines:
lines.append((key, item))
changes['added'].append({key: item})
dest_lxc_conf = []
# filter unset
if lxc_conf_unset:
for line in lines:
for opt in lxc_conf_unset:
if (
not line[0].startswith(opt) and
line not in dest_lxc_conf
):
dest_lxc_conf.append(line)
else:
changes['removed'].append(opt)
else:
dest_lxc_conf = lines
conf = ''
for key, val in dest_lxc_conf:
if not val:
conf += '{0}\n'.format(key)
else:
conf += '{0} = {1}\n'.format(key.strip(), val.strip())
conf_changed = conf != orig_config
chrono = datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S')
if conf_changed:
# DO NOT USE salt.utils.files.fopen here, i got (kiorky)
# problems with lxc configs which were wiped !
with salt.utils.files.fopen('{0}.{1}'.format(lxc_conf_p, chrono), 'w') as wfic:
wfic.write(salt.utils.stringutils.to_str(conf))
with salt.utils.files.fopen(lxc_conf_p, 'w') as wfic:
wfic.write(salt.utils.stringutils.to_str(conf))
ret['comment'] = 'Updated'
ret['result'] = True
if not any(changes[x] for x in changes):
# Ensure an empty changes dict if nothing was modified
ret['changes'] = {}
return ret
def set_dns(name, dnsservers=None, searchdomains=None, path=None):
'''
.. versionchanged:: 2015.5.0
The ``dnsservers`` and ``searchdomains`` parameters can now be passed
as a comma-separated list.
Update /etc/resolv.confo
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.set_dns ubuntu "['8.8.8.8', '4.4.4.4']"
'''
if dnsservers is None:
dnsservers = ['8.8.8.8', '4.4.4.4']
elif not isinstance(dnsservers, list):
try:
dnsservers = dnsservers.split(',')
except AttributeError:
raise SaltInvocationError(
'Invalid input for \'dnsservers\' parameter'
)
if searchdomains is None:
searchdomains = []
elif not isinstance(searchdomains, list):
try:
searchdomains = searchdomains.split(',')
except AttributeError:
raise SaltInvocationError(
'Invalid input for \'searchdomains\' parameter'
)
dns = ['nameserver {0}'.format(x) for x in dnsservers]
dns.extend(['search {0}'.format(x) for x in searchdomains])
dns = '\n'.join(dns) + '\n'
# we may be using resolvconf in the container
# We need to handle that case with care:
# - we create the resolv.conf runtime directory (the
# linked directory) as anyway it will be shadowed when the real
# runned tmpfs mountpoint will be mounted.
# ( /etc/resolv.conf -> ../run/resolvconf/resolv.conf)
# Indeed, it can save us in any other case (running, eg, in a
# bare chroot when repairing or preparing the container for
# operation.
# - We also teach resolvconf to use the aforementioned dns.
# - We finally also set /etc/resolv.conf in all cases
rstr = __salt__['test.random_hash']()
# no tmp here, apparmor won't let us execute !
script = '/sbin/{0}_dns.sh'.format(rstr)
DNS_SCRIPT = "\n".join([
# 'set -x',
'#!/usr/bin/env bash',
'if [ -h /etc/resolv.conf ];then',
' if [ "x$(readlink /etc/resolv.conf)"'
' = "x../run/resolvconf/resolv.conf" ];then',
' if [ ! -d /run/resolvconf/ ];then',
' mkdir -p /run/resolvconf',
' fi',
' cat > /etc/resolvconf/resolv.conf.d/head <<EOF',
dns,
'EOF',
'',
' fi',
'fi',
'cat > /etc/resolv.conf <<EOF',
dns,
'EOF',
''])
result = run_all(
name, 'tee {0}'.format(script), path=path,
stdin=DNS_SCRIPT, python_shell=True)
if result['retcode'] == 0:
result = run_all(
name, 'sh -c "chmod +x {0};{0}"'.format(script),
path=path, python_shell=True)
# blindly delete the setter file
run_all(name,
'sh -c \'if [ -f "{0}" ];then rm -f "{0}";fi\''.format(script),
path=path, python_shell=True)
if result['retcode'] != 0:
error = ('Unable to write to /etc/resolv.conf in container \'{0}\''
.format(name))
if result['stderr']:
error += ': {0}'.format(result['stderr'])
raise CommandExecutionError(error)
return True
def running_systemd(name, cache=True, path=None):
'''
Determine if systemD is running
path
path to the container parent
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.running_systemd ubuntu
'''
k = 'lxc.systemd.test.{0}{1}'.format(name, path)
ret = __context__.get(k, None)
if ret is None or not cache:
rstr = __salt__['test.random_hash']()
# no tmp here, apparmor won't let us execute !
script = '/sbin/{0}_testsystemd.sh'.format(rstr)
# ubuntu already had since trusty some bits of systemd but was
# still using upstart ...
# we need to be a bit more careful that just testing that systemd
# is present
_script = textwrap.dedent(
'''\
#!/usr/bin/env bash
set -x
if ! command -v systemctl 1>/dev/null 2>/dev/null;then exit 2;fi
for i in \\
/run/systemd/journal/dev-log\\
/run/systemd/journal/flushed\\
/run/systemd/journal/kernel-seqnum\\
/run/systemd/journal/socket\\
/run/systemd/journal/stdout\\
/var/run/systemd/journal/dev-log\\
/var/run/systemd/journal/flushed\\
/var/run/systemd/journal/kernel-seqnum\\
/var/run/systemd/journal/socket\\
/var/run/systemd/journal/stdout\\
;do\\
if test -e ${i};then exit 0;fi
done
if test -d /var/systemd/system;then exit 0;fi
exit 2
''')
result = run_all(
name, 'tee {0}'.format(script), path=path,
stdin=_script, python_shell=True)
if result['retcode'] == 0:
result = run_all(name,
'sh -c "chmod +x {0};{0}"'''.format(script),
path=path,
python_shell=True)
else:
raise CommandExecutionError(
'lxc {0} failed to copy initd tester'.format(name))
run_all(name,
'sh -c \'if [ -f "{0}" ];then rm -f "{0}";fi\''
''.format(script),
path=path,
ignore_retcode=True,
python_shell=True)
if result['retcode'] != 0:
error = ('Unable to determine if the container \'{0}\''
' was running systemd, assmuming it is not.'
''.format(name))
if result['stderr']:
error += ': {0}'.format(result['stderr'])
# only cache result if we got a known exit code
if result['retcode'] in (0, 2):
__context__[k] = ret = not result['retcode']
return ret
def systemd_running_state(name, path=None):
'''
Get the operational state of a systemd based container
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.systemd_running_state ubuntu
'''
try:
ret = run_all(name,
'systemctl is-system-running',
path=path,
ignore_retcode=True)['stdout']
except CommandExecutionError:
ret = ''
return ret
def test_sd_started_state(name, path=None):
'''
Test if a systemd container is fully started
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.test_sd_started_state ubuntu
'''
qstate = systemd_running_state(name, path=path)
if qstate in ('initializing', 'starting'):
return False
elif qstate == '':
return None
else:
return True
def test_bare_started_state(name, path=None):
'''
Test if a non systemd container is fully started
For now, it consists only to test if the container is attachable
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.test_bare_started_state ubuntu
'''
try:
ret = run_all(
name, 'ls', path=path, ignore_retcode=True
)['retcode'] == 0
except (CommandExecutionError,):
ret = None
return ret
def wait_started(name, path=None, timeout=300):
'''
Check that the system has fully inited
This is actually very important for systemD based containers
see https://github.com/saltstack/salt/issues/23847
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.wait_started ubuntu
'''
if not exists(name, path=path):
raise CommandExecutionError(
'Container {0} does does exists'.format(name))
if not state(name, path=path) == 'running':
raise CommandExecutionError(
'Container {0} is not running'.format(name))
ret = False
if running_systemd(name, path=path):
test_started = test_sd_started_state
logger = log.error
else:
test_started = test_bare_started_state
logger = log.debug
now = time.time()
expire = now + timeout
now = time.time()
started = test_started(name, path=path)
while time.time() < expire and not started:
time.sleep(0.3)
started = test_started(name, path=path)
if started is None:
logger(
'Assuming %s is started, although we failed to detect that'
' is fully started correctly', name)
ret = True
else:
ret = started
return ret
def _needs_install(name, path=None):
ret = 0
has_minion = retcode(name,
'which salt-minion',
path=path,
ignore_retcode=True)
# we assume that installing is when no minion is running
# but testing the executable presence is not enougth for custom
# installs where the bootstrap can do much more than installing
# the bare salt binaries.
if has_minion:
processes = run_stdout(name, "ps aux", path=path)
if 'salt-minion' not in processes:
ret = 1
else:
retcode(name, 'salt-call --local service.stop salt-minion')
else:
ret = 1
return ret
def bootstrap(name,
config=None,
approve_key=True,
install=True,
pub_key=None,
priv_key=None,
bootstrap_url=None,
force_install=False,
unconditional_install=False,
path=None,
bootstrap_delay=None,
bootstrap_args=None,
bootstrap_shell=None):
'''
Install and configure salt in a container.
config
Minion configuration options. By default, the ``master`` option is set
to the target host's master.
approve_key
Request a pre-approval of the generated minion key. Requires
that the salt-master be configured to either auto-accept all keys or
expect a signing request from the target host. Default: ``True``
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
pub_key
Explicit public key to pressed the minion with (optional).
This can be either a filepath or a string representing the key
priv_key
Explicit private key to pressed the minion with (optional).
This can be either a filepath or a string representing the key
bootstrap_delay
Delay in seconds between end of container creation and bootstrapping.
Useful when waiting for container to obtain a DHCP lease.
.. versionadded:: 2015.5.0
bootstrap_url
url, content or filepath to the salt bootstrap script
bootstrap_args
salt bootstrap script arguments
bootstrap_shell
shell to execute the script into
install
Whether to attempt a full installation of salt-minion if needed.
force_install
Force installation even if salt-minion is detected,
this is the way to run vendor bootstrap scripts even
if a salt minion is already present in the container
unconditional_install
Run the script even if the container seems seeded
CLI Examples:
.. code-block:: bash
salt 'minion' lxc.bootstrap container_name [config=config_data] \\
[approve_key=(True|False)] [install=(True|False)]
'''
wait_started(name, path=path)
if bootstrap_delay is not None:
try:
log.info('LXC %s: bootstrap_delay: %s', name, bootstrap_delay)
time.sleep(bootstrap_delay)
except TypeError:
# Bad input, but assume since a value was passed that
# a delay was desired, and sleep for 5 seconds
time.sleep(5)
c_info = info(name, path=path)
if not c_info:
return None
# default set here as we cannot set them
# in def as it can come from a chain of procedures.
if bootstrap_args:
# custom bootstrap args can be totally customized, and user could
# have inserted the placeholder for the config directory.
# For example, some salt bootstrap script do not use at all -c
if '{0}' not in bootstrap_args:
bootstrap_args += ' -c {0}'
else:
bootstrap_args = '-c {0}'
if not bootstrap_shell:
bootstrap_shell = 'sh'
orig_state = _ensure_running(name, path=path)
if not orig_state:
return orig_state
if not force_install:
needs_install = _needs_install(name, path=path)
else:
needs_install = True
seeded = retcode(name,
'test -e \'{0}\''.format(SEED_MARKER),
path=path,
chroot_fallback=True,
ignore_retcode=True) == 0
tmp = tempfile.mkdtemp()
if seeded and not unconditional_install:
ret = True
else:
ret = False
cfg_files = __salt__['seed.mkconfig'](
config, tmp=tmp, id_=name, approve_key=approve_key,
pub_key=pub_key, priv_key=priv_key)
if needs_install or force_install or unconditional_install:
if install:
rstr = __salt__['test.random_hash']()
configdir = '/var/tmp/.c_{0}'.format(rstr)
cmd = 'install -m 0700 -d {0}'.format(configdir)
if run_all(
name, cmd, path=path, python_shell=False
)['retcode'] != 0:
log.error('tmpdir %s creation failed %s', configdir, cmd)
return False
bs_ = __salt__['config.gather_bootstrap_script'](
bootstrap=bootstrap_url)
script = '/sbin/{0}_bootstrap.sh'.format(rstr)
copy_to(name, bs_, script, path=path)
result = run_all(name,
'sh -c "chmod +x {0}"'.format(script),
path=path,
python_shell=True)
copy_to(name, cfg_files['config'],
os.path.join(configdir, 'minion'),
path=path)
copy_to(name, cfg_files['privkey'],
os.path.join(configdir, 'minion.pem'),
path=path)
copy_to(name, cfg_files['pubkey'],
os.path.join(configdir, 'minion.pub'),
path=path)
bootstrap_args = bootstrap_args.format(configdir)
cmd = ('{0} {2} {1}'
.format(bootstrap_shell,
bootstrap_args.replace("'", "''"),
script))
# log ASAP the forged bootstrap command which can be wrapped
# out of the output in case of unexpected problem
log.info('Running %s in LXC container \'%s\'', cmd, name)
ret = retcode(name, cmd, output_loglevel='info',
path=path, use_vt=True) == 0
run_all(name,
'sh -c \'if [ -f "{0}" ];then rm -f "{0}";fi\''
''.format(script),
path=path,
ignore_retcode=True,
python_shell=True)
else:
ret = False
else:
minion_config = salt.config.minion_config(cfg_files['config'])
pki_dir = minion_config['pki_dir']
copy_to(name,
cfg_files['config'],
'/etc/salt/minion',
path=path)
copy_to(name,
cfg_files['privkey'],
os.path.join(pki_dir, 'minion.pem'),
path=path)
copy_to(name,
cfg_files['pubkey'],
os.path.join(pki_dir, 'minion.pub'),
path=path)
run(name,
'salt-call --local service.enable salt-minion',
path=path,
python_shell=False)
ret = True
shutil.rmtree(tmp)
if orig_state == 'stopped':
stop(name, path=path)
elif orig_state == 'frozen':
freeze(name, path=path)
# mark seeded upon successful install
if ret:
run(name,
'touch \'{0}\''.format(SEED_MARKER),
path=path,
python_shell=False)
return ret
def attachable(name, path=None):
'''
Return True if the named container can be attached to via the lxc-attach
command
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt 'minion' lxc.attachable ubuntu
'''
cachekey = 'lxc.attachable{0}{1}'.format(name, path)
try:
return __context__[cachekey]
except KeyError:
_ensure_exists(name, path=path)
# Can't use run() here because it uses attachable() and would
# endlessly recurse, resulting in a traceback
log.debug('Checking if LXC container %s is attachable', name)
cmd = 'lxc-attach'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' --clear-env -n {0} -- /usr/bin/env'.format(name)
result = __salt__['cmd.retcode'](cmd,
python_shell=False,
output_loglevel='quiet',
ignore_retcode=True) == 0
__context__[cachekey] = result
return __context__[cachekey]
def _run(name,
cmd,
output=None,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=None,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
Common logic for lxc.run functions
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
'''
orig_state = state(name, path=path)
try:
if attachable(name, path=path):
ret = __salt__['container_resource.run'](
name,
cmd,
path=path,
container_type=__virtualname__,
exec_driver=EXEC_DRIVER,
output=output,
no_start=no_start,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
ignore_retcode=ignore_retcode,
use_vt=use_vt,
keep_env=keep_env)
else:
if not chroot_fallback:
raise CommandExecutionError(
'{0} is not attachable.'.format(name))
rootfs = info(name, path=path).get('rootfs')
# Set context var to make cmd.run_chroot run cmd.run instead of
# cmd.run_all.
__context__['cmd.run_chroot.func'] = __salt__['cmd.run']
ret = __salt__['cmd.run_chroot'](rootfs,
cmd,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
ignore_retcode=ignore_retcode)
except Exception:
raise
finally:
# Make sure we honor preserve_state, even if there was an exception
new_state = state(name, path=path)
if preserve_state:
if orig_state == 'stopped' and new_state != 'stopped':
stop(name, path=path)
elif orig_state == 'frozen' and new_state != 'frozen':
freeze(name, start=True, path=path)
if output in (None, 'all'):
return ret
else:
return ret[output]
def run(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.8.0
Run :mod:`cmd.run <salt.modules.cmdmod.run>` within a container
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed in stderr if the command being run
does not exist. If no output is returned using this function, try using
:mod:`lxc.run_stderr <salt.modules.lxc.run_stderr>` or
:mod:`lxc.run_all <salt.modules.lxc.run_all>`.
name
Name of the container in which to run the command
cmd
Command to run
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console. Assumes
``output=all``.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
CLI Example:
.. code-block:: bash
salt myminion lxc.run mycontainer 'ifconfig -a'
'''
return _run(name,
cmd,
path=path,
output=None,
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def run_stdout(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.5.0
Run :mod:`cmd.run_stdout <salt.modules.cmdmod.run_stdout>` within a container
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed in stderr if the command being run
does not exist. If no output is returned using this function, try using
:mod:`lxc.run_stderr <salt.modules.lxc.run_stderr>` or
:mod:`lxc.run_all <salt.modules.lxc.run_all>`.
name
Name of the container in which to run the command
cmd
Command to run
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console
``output=all``.
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
CLI Example:
.. code-block:: bash
salt myminion lxc.run_stdout mycontainer 'ifconfig -a'
'''
return _run(name,
cmd,
path=path,
output='stdout',
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def run_stderr(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.5.0
Run :mod:`cmd.run_stderr <salt.modules.cmdmod.run_stderr>` within a container
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed if the command being run does not
exist.
name
Name of the container in which to run the command
cmd
Command to run
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console
``output=all``.
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
CLI Example:
.. code-block:: bash
salt myminion lxc.run_stderr mycontainer 'ip addr show'
'''
return _run(name,
cmd,
path=path,
output='stderr',
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def retcode(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.5.0
Run :mod:`cmd.retcode <salt.modules.cmdmod.retcode>` within a container
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed in stderr if the command being run
does not exist. If the retcode is nonzero and not what was expected,
try using :mod:`lxc.run_stderr <salt.modules.lxc.run_stderr>`
or :mod:`lxc.run_all <salt.modules.lxc.run_all>`.
name
Name of the container in which to run the command
cmd
Command to run
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console
``output=all``.
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
CLI Example:
.. code-block:: bash
salt myminion lxc.retcode mycontainer 'ip addr show'
'''
return _run(name,
cmd,
output='retcode',
path=path,
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def run_all(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.5.0
Run :mod:`cmd.run_all <salt.modules.cmdmod.run_all>` within a container
.. note::
While the command is run within the container, it is initiated from the
host. Therefore, the PID in the return dict is from the host, not from
the container.
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed in stderr if the command being run
does not exist.
name
Name of the container in which to run the command
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
cmd
Command to run
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console
``output=all``.
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
CLI Example:
.. code-block:: bash
salt myminion lxc.run_all mycontainer 'ip addr show'
'''
return _run(name,
cmd,
output='all',
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
path=path,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def _get_md5(name, path):
'''
Get the MD5 checksum of a file from a container
'''
output = run_stdout(name, 'md5sum "{0}"'.format(path),
chroot_fallback=True,
ignore_retcode=True)
try:
return output.split()[0]
except IndexError:
# Destination file does not exist or could not be accessed
return None
def copy_to(name, source, dest, overwrite=False, makedirs=False, path=None):
'''
.. versionchanged:: 2015.8.0
Function renamed from ``lxc.cp`` to ``lxc.copy_to`` for consistency
with other container types. ``lxc.cp`` will continue to work, however.
For versions 2015.2.x and earlier, use ``lxc.cp``.
Copy a file or directory from the host into a container
name
Container name
source
File to be copied to the container
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
dest
Destination on the container. Must be an absolute path.
.. versionchanged:: 2015.5.0
If the destination is a directory, the file will be copied into
that directory.
overwrite : False
Unless this option is set to ``True``, then if a file exists at the
location specified by the ``dest`` argument, an error will be raised.
.. versionadded:: 2015.8.0
makedirs : False
Create the parent directory on the container if it does not already
exist.
.. versionadded:: 2015.5.0
CLI Example:
.. code-block:: bash
salt 'minion' lxc.copy_to /tmp/foo /root/foo
salt 'minion' lxc.cp /tmp/foo /root/foo
'''
_ensure_running(name, no_start=True, path=path)
return __salt__['container_resource.copy_to'](
name,
source,
dest,
container_type=__virtualname__,
path=path,
exec_driver=EXEC_DRIVER,
overwrite=overwrite,
makedirs=makedirs)
cp = salt.utils.functools.alias_function(copy_to, 'cp')
def read_conf(conf_file, out_format='simple'):
'''
Read in an LXC configuration file. By default returns a simple, unsorted
dict, but can also return a more detailed structure including blank lines
and comments.
out_format:
set to 'simple' if you need the old and unsupported behavior.
This won't support the multiple lxc values (eg: multiple network nics)
CLI Examples:
.. code-block:: bash
salt 'minion' lxc.read_conf /etc/lxc/mycontainer.conf
salt 'minion' lxc.read_conf /etc/lxc/mycontainer.conf out_format=commented
'''
ret_commented = []
ret_simple = {}
with salt.utils.files.fopen(conf_file, 'r') as fp_:
for line in salt.utils.data.decode(fp_.readlines()):
if '=' not in line:
ret_commented.append(line)
continue
comps = line.split('=')
value = '='.join(comps[1:]).strip()
comment = None
if value.strip().startswith('#'):
vcomps = value.strip().split('#')
value = vcomps[1].strip()
comment = '#'.join(vcomps[1:]).strip()
ret_commented.append({comps[0].strip(): {
'value': value,
'comment': comment,
}})
else:
ret_commented.append({comps[0].strip(): value})
ret_simple[comps[0].strip()] = value
if out_format == 'simple':
return ret_simple
return ret_commented
def write_conf(conf_file, conf):
'''
Write out an LXC configuration file
This is normally only used internally. The format of the data structure
must match that which is returned from ``lxc.read_conf()``, with
``out_format`` set to ``commented``.
An example might look like:
.. code-block:: python
[
{'lxc.utsname': '$CONTAINER_NAME'},
'# This is a commented line\\n',
'\\n',
{'lxc.mount': '$CONTAINER_FSTAB'},
{'lxc.rootfs': {'comment': 'This is another test',
'value': 'This is another test'}},
'\\n',
{'lxc.network.type': 'veth'},
{'lxc.network.flags': 'up'},
{'lxc.network.link': 'br0'},
{'lxc.network.mac': '$CONTAINER_MACADDR'},
{'lxc.network.ipv4': '$CONTAINER_IPADDR'},
{'lxc.network.name': '$CONTAINER_DEVICENAME'},
]
CLI Example:
.. code-block:: bash
salt 'minion' lxc.write_conf /etc/lxc/mycontainer.conf \\
out_format=commented
'''
if not isinstance(conf, list):
raise SaltInvocationError('Configuration must be passed as a list')
# construct the content prior to write to the file
# to avoid half written configs
content = ''
for line in conf:
if isinstance(line, (six.text_type, six.string_types)):
content += line
elif isinstance(line, dict):
for key in list(line.keys()):
out_line = None
if isinstance(
line[key],
(six.text_type, six.string_types, six.integer_types, float)
):
out_line = ' = '.join((key, "{0}".format(line[key])))
elif isinstance(line[key], dict):
out_line = ' = '.join((key, line[key]['value']))
if 'comment' in line[key]:
out_line = ' # '.join((out_line, line[key]['comment']))
if out_line:
content += out_line
content += '\n'
with salt.utils.files.fopen(conf_file, 'w') as fp_:
fp_.write(salt.utils.stringutils.to_str(content))
return {}
def edit_conf(conf_file,
out_format='simple',
read_only=False,
lxc_config=None,
**kwargs):
'''
Edit an LXC configuration file. If a setting is already present inside the
file, its value will be replaced. If it does not exist, it will be appended
to the end of the file. Comments and blank lines will be kept in-tact if
they already exist in the file.
out_format:
Set to simple if you need backward compatibility (multiple items for a
simple key is not supported)
read_only:
return only the edited configuration without applying it
to the underlying lxc configuration file
lxc_config:
List of dict containning lxc configuration items
For network configuration, you also need to add the device it belongs
to, otherwise it will default to eth0.
Also, any change to a network parameter will result in the whole
network reconfiguration to avoid mismatchs, be aware of that !
After the file is edited, its contents will be returned. By default, it
will be returned in ``simple`` format, meaning an unordered dict (which
may not represent the actual file order). Passing in an ``out_format`` of
``commented`` will return a data structure which accurately represents the
order and content of the file.
CLI Example:
.. code-block:: bash
salt 'minion' lxc.edit_conf /etc/lxc/mycontainer.conf \\
out_format=commented lxc.network.type=veth
salt 'minion' lxc.edit_conf /etc/lxc/mycontainer.conf \\
out_format=commented \\
lxc_config="[{'lxc.network.name': 'eth0', \\
'lxc.network.ipv4': '1.2.3.4'},
{'lxc.network.name': 'eth2', \\
'lxc.network.ipv4': '1.2.3.5',\\
'lxc.network.gateway': '1.2.3.1'}]"
'''
data = []
try:
conf = read_conf(conf_file, out_format=out_format)
except Exception:
conf = []
if not lxc_config:
lxc_config = []
lxc_config = copy.deepcopy(lxc_config)
# search if we want to access net config
# in that case, we will replace all the net configuration
net_config = []
for lxc_kws in lxc_config + [kwargs]:
net_params = {}
for kwarg in [a for a in lxc_kws]:
if kwarg.startswith('__'):
continue
if kwarg.startswith('lxc.network.'):
net_params[kwarg] = lxc_kws[kwarg]
lxc_kws.pop(kwarg, None)
if net_params:
net_config.append(net_params)
nic_opts = salt.utils.odict.OrderedDict()
for params in net_config:
dev = params.get('lxc.network.name', DEFAULT_NIC)
dev_opts = nic_opts.setdefault(dev, salt.utils.odict.OrderedDict())
for param in params:
opt = param.replace('lxc.network.', '')
opt = {'hwaddr': 'mac'}.get(opt, opt)
dev_opts[opt] = params[param]
net_changes = []
if nic_opts:
net_changes = _config_list(conf, only_net=True,
**{'network_profile': DEFAULT_NIC,
'nic_opts': nic_opts})
if net_changes:
lxc_config.extend(net_changes)
for line in conf:
if not isinstance(line, dict):
data.append(line)
continue
else:
for key in list(line.keys()):
val = line[key]
if net_changes and key.startswith('lxc.network.'):
continue
found = False
for ix in range(len(lxc_config)):
kw = lxc_config[ix]
if key in kw:
found = True
data.append({key: kw[key]})
del kw[key]
if not found:
data.append({key: val})
for lxc_kws in lxc_config:
for kwarg in lxc_kws:
data.append({kwarg: lxc_kws[kwarg]})
if read_only:
return data
write_conf(conf_file, data)
return read_conf(conf_file, out_format)
def reboot(name, path=None):
'''
Reboot a container.
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Examples:
.. code-block:: bash
salt 'minion' lxc.reboot myvm
'''
ret = {'result': True,
'changes': {},
'comment': '{0} rebooted'.format(name)}
does_exist = exists(name, path=path)
if does_exist and (state(name, path=path) == 'running'):
try:
stop(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
ret['result'] = False
return ret
if does_exist and (state(name, path=path) != 'running'):
try:
start(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
ret['result'] = False
return ret
ret['changes'][name] = 'rebooted'
return ret
def reconfigure(name,
cpu=None,
cpuset=None,
cpushare=None,
memory=None,
profile=None,
network_profile=None,
nic_opts=None,
bridge=None,
gateway=None,
autostart=None,
utsname=None,
rootfs=None,
path=None,
**kwargs):
'''
Reconfigure a container.
This only applies to a few property
name
Name of the container.
utsname
utsname of the container.
.. versionadded:: 2016.3.0
rootfs
rootfs of the container.
.. versionadded:: 2016.3.0
cpu
Select a random number of cpu cores and assign it to the cpuset, if the
cpuset option is set then this option will be ignored
cpuset
Explicitly define the cpus this container will be bound to
cpushare
cgroups cpu shares.
autostart
autostart container on reboot
memory
cgroups memory limit, in MB.
(0 for nolimit, None for old default 1024MB)
gateway
the ipv4 gateway to use
the default does nothing more than lxcutils does
bridge
the bridge to use
the default does nothing more than lxcutils does
nic
Network interfaces profile (defined in config or pillar).
nic_opts
Extra options for network interfaces, will override
``{"eth0": {"mac": "aa:bb:cc:dd:ee:ff", "ipv4": "10.1.1.1", "ipv6": "2001:db8::ff00:42:8329"}}``
or
``{"eth0": {"mac": "aa:bb:cc:dd:ee:ff", "ipv4": "10.1.1.1/24", "ipv6": "2001:db8::ff00:42:8329"}}``
path
path to the container parent
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt-call -lall mc_lxc_fork.reconfigure foobar nic_opts="{'eth1': {'mac': '00:16:3e:dd:ee:44'}}" memory=4
'''
changes = {}
cpath = get_root_path(path)
path = os.path.join(cpath, name, 'config')
ret = {'name': name,
'comment': 'config for {0} up to date'.format(name),
'result': True,
'changes': changes}
profile = get_container_profile(copy.deepcopy(profile))
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, _marker)
profile_match = profile.pop(key, default)
# let kwarg overrides be the preferred choice
if kw_overrides_match is _marker:
return profile_match
return kw_overrides_match
if nic_opts is not None and not network_profile:
network_profile = DEFAULT_NIC
if autostart is not None:
autostart = select('autostart', autostart)
else:
autostart = 'keep'
if not utsname:
utsname = select('utsname', utsname)
if os.path.exists(path):
old_chunks = read_conf(path, out_format='commented')
make_kw = salt.utils.odict.OrderedDict([
('utsname', utsname),
('rootfs', rootfs),
('autostart', autostart),
('cpu', cpu),
('gateway', gateway),
('cpuset', cpuset),
('cpushare', cpushare),
('network_profile', network_profile),
('nic_opts', nic_opts),
('bridge', bridge)])
# match 0 and none as memory = 0 in lxc config is harmful
if memory:
make_kw['memory'] = memory
kw = salt.utils.odict.OrderedDict()
for key, val in six.iteritems(make_kw):
if val is not None:
kw[key] = val
new_cfg = _config_list(conf_tuples=old_chunks, **kw)
if new_cfg:
edit_conf(path, out_format='commented', lxc_config=new_cfg)
chunks = read_conf(path, out_format='commented')
if old_chunks != chunks:
ret['comment'] = '{0} lxc config updated'.format(name)
if state(name, path=path) == 'running':
cret = reboot(name, path=path)
ret['result'] = cret['result']
return ret
def apply_network_profile(name, network_profile, nic_opts=None, path=None):
'''
.. versionadded:: 2015.5.0
Apply a network profile to a container
network_profile
profile name or default values (dict)
nic_opts
values to override in defaults (dict)
indexed by nic card names
path
path to the container parent
.. versionadded:: 2015.8.0
CLI Examples:
.. code-block:: bash
salt 'minion' lxc.apply_network_profile web1 centos
salt 'minion' lxc.apply_network_profile web1 centos \\
nic_opts="{'eth0': {'mac': 'xx:xx:xx:xx:xx:xx'}}"
salt 'minion' lxc.apply_network_profile web1 \\
"{'eth0': {'mac': 'xx:xx:xx:xx:xx:yy'}}"
nic_opts="{'eth0': {'mac': 'xx:xx:xx:xx:xx:xx'}}"
The special case to disable use of ethernet nics:
.. code-block:: bash
salt 'minion' lxc.apply_network_profile web1 centos \\
"{eth0: {disable: true}}"
'''
cpath = get_root_path(path)
cfgpath = os.path.join(cpath, name, 'config')
before = []
with salt.utils.files.fopen(cfgpath, 'r') as fp_:
for line in fp_:
before.append(line)
lxcconfig = _LXCConfig(name=name, path=path)
old_net = lxcconfig._filter_data('lxc.network')
network_params = {}
for param in _network_conf(
conf_tuples=old_net,
network_profile=network_profile, nic_opts=nic_opts
):
network_params.update(param)
if network_params:
edit_conf(cfgpath, out_format='commented', **network_params)
after = []
with salt.utils.files.fopen(cfgpath, 'r') as fp_:
for line in fp_:
after.append(line)
diff = ''
for line in difflib.unified_diff(before,
after,
fromfile='before',
tofile='after'):
diff += line
return diff
def get_pid(name, path=None):
'''
Returns a container pid.
Throw an exception if the container isn't running.
CLI Example:
.. code-block:: bash
salt '*' lxc.get_pid name
'''
if name not in list_(limit='running', path=path):
raise CommandExecutionError('Container {0} is not running, can\'t determine PID'.format(name))
info = __salt__['cmd.run']('lxc-info -n {0}'.format(name)).split("\n")
pid = [line.split(':')[1].strip() for line in info if re.match(r'\s*PID', line)][0]
return pid
def add_veth(name, interface_name, bridge=None, path=None):
'''
Add a veth to a container.
Note : this function doesn't update the container config, just add the interface at runtime
name
Name of the container
interface_name
Name of the interface in the container
bridge
Name of the bridge to attach the interface to (facultative)
CLI Examples:
.. code-block:: bash
salt '*' lxc.add_veth container_name eth1 br1
salt '*' lxc.add_veth container_name eth1
'''
# Get container init PID
pid = get_pid(name, path=path)
# Generate a ramdom string for veth and ensure that is isn't present on the system
while True:
random_veth = 'veth'+''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(6))
if random_veth not in __salt__['network.interfaces']().keys():
break
# Check prerequisites
if not __salt__['file.directory_exists']('/var/run/'):
raise CommandExecutionError('Directory /var/run required for lxc.add_veth doesn\'t exists')
if not __salt__['file.file_exists']('/proc/{0}/ns/net'.format(pid)):
raise CommandExecutionError('Proc file for container {0} network namespace doesn\'t exists'.format(name))
if not __salt__['file.directory_exists']('/var/run/netns'):
__salt__['file.mkdir']('/var/run/netns')
# Ensure that the symlink is up to date (change on container restart)
if __salt__['file.is_link']('/var/run/netns/{0}'.format(name)):
__salt__['file.remove']('/var/run/netns/{0}'.format(name))
__salt__['file.symlink']('/proc/{0}/ns/net'.format(pid), '/var/run/netns/{0}'.format(name))
# Ensure that interface doesn't exists
interface_exists = 0 == __salt__['cmd.retcode']('ip netns exec {netns} ip address list {interface}'.format(
netns=name,
interface=interface_name
))
if interface_exists:
raise CommandExecutionError('Interface {interface} already exists in {container}'.format(
interface=interface_name,
container=name
))
# Create veth and bring it up
if __salt__['cmd.retcode']('ip link add name {veth} type veth peer name {veth}_c'.format(veth=random_veth)) != 0:
raise CommandExecutionError('Error while creating the veth pair {0}'.format(random_veth))
if __salt__['cmd.retcode']('ip link set dev {0} up'.format(random_veth)) != 0:
raise CommandExecutionError('Error while bringing up host-side veth {0}'.format(random_veth))
# Attach it to the container
attached = 0 == __salt__['cmd.retcode']('ip link set dev {veth}_c netns {container} name {interface_name}'.format(
veth=random_veth,
container=name,
interface_name=interface_name
))
if not attached:
raise CommandExecutionError('Error while attaching the veth {veth} to container {container}'.format(
veth=random_veth,
container=name
))
__salt__['file.remove']('/var/run/netns/{0}'.format(name))
if bridge is not None:
__salt__['bridge.addif'](bridge, random_veth)
|
saltstack/salt
|
salt/modules/lxc.py
|
search_lxc_bridges
|
python
|
def search_lxc_bridges():
'''
Search which bridges are potentially available as LXC bridges
CLI Example:
.. code-block:: bash
salt '*' lxc.search_lxc_bridges
'''
bridges = __context__.get('lxc.bridges', None)
# either match not yet called or no bridges were found
# to handle the case where lxc was not installed on the first
# call
if not bridges:
bridges = set()
running_bridges = set()
bridges.add(DEFAULT_BR)
try:
output = __salt__['cmd.run_all']('brctl show')
for line in output['stdout'].splitlines()[1:]:
if not line.startswith(' '):
running_bridges.add(line.split()[0].strip())
except (SaltInvocationError, CommandExecutionError):
pass
for ifc, ip in six.iteritems(
__grains__.get('ip_interfaces', {})
):
if ifc in running_bridges:
bridges.add(ifc)
elif os.path.exists(
'/sys/devices/virtual/net/{0}/bridge'.format(ifc)
):
bridges.add(ifc)
bridges = list(bridges)
# if we found interfaces that have lxc in their names
# we filter them as being the potential lxc bridges
# we also try to default on br0 on other cases
def sort_bridges(a):
pref = 'z'
if 'lxc' in a:
pref = 'a'
elif 'br0' == a:
pref = 'c'
return '{0}_{1}'.format(pref, a)
bridges.sort(key=sort_bridges)
__context__['lxc.bridges'] = bridges
return bridges
|
Search which bridges are potentially available as LXC bridges
CLI Example:
.. code-block:: bash
salt '*' lxc.search_lxc_bridges
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/lxc.py#L156-L205
|
[
"def iteritems(d, **kw):\n return d.iteritems(**kw)\n"
] |
# -*- coding: utf-8 -*-
'''
Control Linux Containers via Salt
:depends: lxc package for distribution
lxc >= 1.0 (even beta alpha) is required
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import datetime
import copy
import string
import textwrap
import difflib
import logging
import tempfile
import os
import pipes
import time
import shutil
import re
import random
# Import salt libs
import salt.utils.args
import salt.utils.cloud
import salt.utils.data
import salt.utils.dictupdate
import salt.utils.files
import salt.utils.functools
import salt.utils.hashutils
import salt.utils.network
import salt.utils.odict
import salt.utils.path
import salt.utils.stringutils
from salt.exceptions import CommandExecutionError, SaltInvocationError
import salt.config
from salt.utils.versions import LooseVersion as _LooseVersion
# Import 3rd-party libs
from salt.ext import six
# pylint: disable=import-error,no-name-in-module
from salt.ext.six.moves import range # pylint: disable=redefined-builtin
from salt.ext.six.moves.urllib.parse import urlparse as _urlparse
# pylint: enable=import-error,no-name-in-module
# Set up logging
log = logging.getLogger(__name__)
# Don't shadow built-in's.
__func_alias__ = {
'list_': 'list',
'ls_': 'ls'
}
__virtualname__ = 'lxc'
DEFAULT_NIC = 'eth0'
DEFAULT_BR = 'br0'
SEED_MARKER = '/lxc.initial_seed'
EXEC_DRIVER = 'lxc-attach'
DEFAULT_PATH = '/var/lib/lxc'
_marker = object()
def __virtual__():
if salt.utils.path.which('lxc-start'):
return __virtualname__
# To speed up the whole thing, we decided to not use the
# subshell way and assume things are in place for lxc
# Discussion made by @kiorky and @thatch45
# lxc-version presence is not sufficient, in lxc1.0 alpha
# (precise backports), we have it and it is sufficient
# for the module to execute.
# elif salt.utils.path.which('lxc-version'):
# passed = False
# try:
# passed = subprocess.check_output(
# 'lxc-version').split(':')[1].strip() >= '1.0'
# except Exception:
# pass
# if not passed:
# log.warning('Support for lxc < 1.0 may be incomplete.')
# return 'lxc'
# return False
#
return (False, 'The lxc execution module cannot be loaded: the lxc-start binary is not in the path.')
def get_root_path(path):
'''
Get the configured lxc root for containers
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.get_root_path
'''
if not path:
path = __opts__.get('lxc.root_path', DEFAULT_PATH)
return path
def version():
'''
Return the actual lxc client version
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.version
'''
k = 'lxc.version'
if not __context__.get(k, None):
cversion = __salt__['cmd.run_all']('lxc-info --version')
if not cversion['retcode']:
ver = _LooseVersion(cversion['stdout'])
if ver < _LooseVersion('1.0'):
raise CommandExecutionError('LXC should be at least 1.0')
__context__[k] = "{0}".format(ver)
return __context__.get(k, None)
def _clear_context():
'''
Clear any lxc variables set in __context__
'''
for var in [x for x in __context__ if x.startswith('lxc.')]:
log.trace('Clearing __context__[\'%s\']', var)
__context__.pop(var, None)
def _ip_sort(ip):
'''Ip sorting'''
idx = '001'
if ip == '127.0.0.1':
idx = '200'
if ip == '::1':
idx = '201'
elif '::' in ip:
idx = '100'
return '{0}___{1}'.format(idx, ip)
def search_lxc_bridge():
'''
Search the first bridge which is potentially available as LXC bridge
CLI Example:
.. code-block:: bash
salt '*' lxc.search_lxc_bridge
'''
return search_lxc_bridges()[0]
def _get_salt_config(config, **kwargs):
if not config:
config = kwargs.get('minion', {})
if not config:
config = {}
config.setdefault('master',
kwargs.get('master',
__opts__.get('master',
__opts__['id'])))
config.setdefault(
'master_port',
kwargs.get('master_port',
__opts__.get('master_port',
__opts__.get('ret_port',
__opts__.get('4506')))))
if not config['master']:
config = {}
return config
def cloud_init_interface(name, vm_=None, **kwargs):
'''
Interface between salt.cloud.lxc driver and lxc.init
``vm_`` is a mapping of vm opts in the salt.cloud format
as documented for the lxc driver.
This can be used either:
- from the salt cloud driver
- because you find the argument to give easier here
than using directly lxc.init
.. warning::
BE REALLY CAREFUL CHANGING DEFAULTS !!!
IT'S A RETRO COMPATIBLE INTERFACE WITH
THE SALT CLOUD DRIVER (ask kiorky).
name
name of the lxc container to create
pub_key
public key to preseed the minion with.
Can be the keycontent or a filepath
priv_key
private key to preseed the minion with.
Can be the keycontent or a filepath
path
path to the container parent directory (default: /var/lib/lxc)
.. versionadded:: 2015.8.0
profile
:ref:`profile <tutorial-lxc-profiles-container>` selection
network_profile
:ref:`network profile <tutorial-lxc-profiles-network>` selection
nic_opts
per interface settings compatibles with
network profile (ipv4/ipv6/link/gateway/mac/netmask)
eg::
- {'eth0': {'mac': '00:16:3e:01:29:40',
'gateway': None, (default)
'link': 'br0', (default)
'gateway': None, (default)
'netmask': '', (default)
'ip': '22.1.4.25'}}
unconditional_install
given to lxc.bootstrap (see relative doc)
force_install
given to lxc.bootstrap (see relative doc)
config
any extra argument for the salt minion config
dnsservers
list of DNS servers to set inside the container
dns_via_dhcp
do not set the dns servers, let them be set by the dhcp.
autostart
autostart the container at boot time
password
administrative password for the container
bootstrap_delay
delay before launching bootstrap script at Container init
.. warning::
Legacy but still supported options:
from_container
which container we use as a template
when running lxc.clone
image
which template do we use when we
are using lxc.create. This is the default
mode unless you specify something in from_container
backing
which backing store to use.
Values can be: overlayfs, dir(default), lvm, zfs, brtfs
fstype
When using a blockdevice level backing store,
which filesystem to use on
size
When using a blockdevice level backing store,
which size for the filesystem to use on
snapshot
Use snapshot when cloning the container source
vgname
if using LVM: vgname
lvname
if using LVM: lvname
thinpool:
if using LVM: thinpool
ip
ip for the primary nic
mac
mac address for the primary nic
netmask
netmask for the primary nic (24)
= ``vm_.get('netmask', '24')``
bridge
bridge for the primary nic (lxcbr0)
gateway
network gateway for the container
additional_ips
additional ips which will be wired on the main bridge (br0)
which is connected to internet.
Be aware that you may use manual virtual mac addresses
providen by you provider (online, ovh, etc).
This is a list of mappings {ip: '', mac: '', netmask:''}
Set gateway to None and an interface with a gateway
to escape from another interface that eth0.
eg::
- {'mac': '00:16:3e:01:29:40',
'gateway': None, (default)
'link': 'br0', (default)
'netmask': '', (default)
'ip': '22.1.4.25'}
users
administrative users for the container
default: [root] and [root, ubuntu] on ubuntu
default_nic
name of the first interface, you should
really not override this
CLI Example:
.. code-block:: bash
salt '*' lxc.cloud_init_interface foo
'''
if vm_ is None:
vm_ = {}
vm_ = copy.deepcopy(vm_)
vm_ = salt.utils.dictupdate.update(vm_, kwargs)
profile_data = copy.deepcopy(
vm_.get('lxc_profile',
vm_.get('profile', {})))
if not isinstance(profile_data, (dict, six.string_types)):
profile_data = {}
profile = get_container_profile(profile_data)
def _cloud_get(k, default=None):
return vm_.get(k, profile.get(k, default))
if name is None:
name = vm_['name']
# if we are on ubuntu, default to ubuntu
default_template = ''
if __grains__.get('os', '') in ['Ubuntu']:
default_template = 'ubuntu'
image = _cloud_get('image')
if not image:
_cloud_get('template', default_template)
backing = _cloud_get('backing', 'dir')
if image:
profile['template'] = image
vgname = _cloud_get('vgname', None)
if vgname:
profile['vgname'] = vgname
if backing:
profile['backing'] = backing
snapshot = _cloud_get('snapshot', False)
autostart = bool(_cloud_get('autostart', True))
dnsservers = _cloud_get('dnsservers', [])
dns_via_dhcp = _cloud_get('dns_via_dhcp', True)
password = _cloud_get('password', 's3cr3t')
password_encrypted = _cloud_get('password_encrypted', False)
fstype = _cloud_get('fstype', None)
lvname = _cloud_get('lvname', None)
thinpool = _cloud_get('thinpool', None)
pub_key = _cloud_get('pub_key', None)
priv_key = _cloud_get('priv_key', None)
size = _cloud_get('size', '20G')
script = _cloud_get('script', None)
script_args = _cloud_get('script_args', None)
users = _cloud_get('users', None)
if users is None:
users = []
ssh_username = _cloud_get('ssh_username', None)
if ssh_username and (ssh_username not in users):
users.append(ssh_username)
network_profile = _cloud_get('network_profile', None)
nic_opts = kwargs.get('nic_opts', None)
netmask = _cloud_get('netmask', '24')
path = _cloud_get('path', None)
bridge = _cloud_get('bridge', None)
gateway = _cloud_get('gateway', None)
unconditional_install = _cloud_get('unconditional_install', False)
force_install = _cloud_get('force_install', True)
config = _get_salt_config(_cloud_get('config', {}), **vm_)
default_nic = _cloud_get('default_nic', DEFAULT_NIC)
# do the interface with lxc.init mainly via nic_opts
# to avoid extra and confusing extra use cases.
if not isinstance(nic_opts, dict):
nic_opts = salt.utils.odict.OrderedDict()
# have a reference to the default nic
eth0 = nic_opts.setdefault(default_nic,
salt.utils.odict.OrderedDict())
# lxc config is based of ifc order, be sure to use odicts.
if not isinstance(nic_opts, salt.utils.odict.OrderedDict):
bnic_opts = salt.utils.odict.OrderedDict()
bnic_opts.update(nic_opts)
nic_opts = bnic_opts
gw = None
# legacy salt.cloud scheme for network interfaces settings support
bridge = _cloud_get('bridge', None)
ip = _cloud_get('ip', None)
mac = _cloud_get('mac', None)
if ip:
fullip = ip
if netmask:
fullip += '/{0}'.format(netmask)
eth0['ipv4'] = fullip
if mac is not None:
eth0['mac'] = mac
for ix, iopts in enumerate(_cloud_get("additional_ips", [])):
ifh = "eth{0}".format(ix+1)
ethx = nic_opts.setdefault(ifh, {})
if gw is None:
gw = iopts.get('gateway', ethx.get('gateway', None))
if gw:
# only one and only one default gateway is allowed !
eth0.pop('gateway', None)
gateway = None
# even if the gateway if on default "eth0" nic
# and we popped it will work
# as we reinject or set it here.
ethx['gateway'] = gw
elink = iopts.get('link', ethx.get('link', None))
if elink:
ethx['link'] = elink
# allow dhcp
aip = iopts.get('ipv4', iopts.get('ip', None))
if aip:
ethx['ipv4'] = aip
nm = iopts.get('netmask', '')
if nm:
ethx['ipv4'] += '/{0}'.format(nm)
for i in ('mac', 'hwaddr'):
if i in iopts:
ethx['mac'] = iopts[i]
break
if 'mac' not in ethx:
ethx['mac'] = salt.utils.network.gen_mac()
# last round checking for unique gateway and such
gw = None
for ethx in [a for a in nic_opts]:
ndata = nic_opts[ethx]
if gw:
ndata.pop('gateway', None)
if 'gateway' in ndata:
gw = ndata['gateway']
gateway = None
# only use a default bridge / gateway if we configured them
# via the legacy salt cloud configuration style.
# On other cases, we should rely on settings provided by the new
# salt lxc network profile style configuration which can
# be also be overridden or a per interface basis via the nic_opts dict.
if bridge:
eth0['link'] = bridge
if gateway:
eth0['gateway'] = gateway
#
lxc_init_interface = {}
lxc_init_interface['name'] = name
lxc_init_interface['config'] = config
lxc_init_interface['memory'] = _cloud_get('memory', 0) # nolimit
lxc_init_interface['pub_key'] = pub_key
lxc_init_interface['priv_key'] = priv_key
lxc_init_interface['nic_opts'] = nic_opts
for clone_from in ['clone_from', 'clone', 'from_container']:
# clone_from should default to None if not available
lxc_init_interface['clone_from'] = _cloud_get(clone_from, None)
if lxc_init_interface['clone_from'] is not None:
break
lxc_init_interface['profile'] = profile
lxc_init_interface['snapshot'] = snapshot
lxc_init_interface['dnsservers'] = dnsservers
lxc_init_interface['fstype'] = fstype
lxc_init_interface['path'] = path
lxc_init_interface['vgname'] = vgname
lxc_init_interface['size'] = size
lxc_init_interface['lvname'] = lvname
lxc_init_interface['thinpool'] = thinpool
lxc_init_interface['force_install'] = force_install
lxc_init_interface['unconditional_install'] = (
unconditional_install
)
lxc_init_interface['bootstrap_url'] = script
lxc_init_interface['bootstrap_args'] = script_args
lxc_init_interface['bootstrap_shell'] = _cloud_get('bootstrap_shell', 'sh')
lxc_init_interface['bootstrap_delay'] = _cloud_get('bootstrap_delay', None)
lxc_init_interface['autostart'] = autostart
lxc_init_interface['users'] = users
lxc_init_interface['password'] = password
lxc_init_interface['password_encrypted'] = password_encrypted
# be sure not to let objects goes inside the return
# as this return will be msgpacked for use in the runner !
lxc_init_interface['network_profile'] = network_profile
for i in ['cpu', 'cpuset', 'cpushare']:
if _cloud_get(i, None):
try:
lxc_init_interface[i] = vm_[i]
except KeyError:
lxc_init_interface[i] = profile[i]
return lxc_init_interface
def _get_profile(key, name, **kwargs):
if isinstance(name, dict):
profilename = name.pop('name', None)
return _get_profile(key, profilename, **name)
if name is None:
profile_match = {}
else:
profile_match = \
__salt__['config.get'](
'lxc.{1}:{0}'.format(name, key),
default=None,
merge='recurse'
)
if profile_match is None:
# No matching profile, make the profile an empty dict so that
# overrides can be applied below.
profile_match = {}
if not isinstance(profile_match, dict):
raise CommandExecutionError('lxc.{0} must be a dictionary'.format(key))
# Overlay the kwargs to override matched profile data
overrides = salt.utils.args.clean_kwargs(**copy.deepcopy(kwargs))
profile_match = salt.utils.dictupdate.update(
copy.deepcopy(profile_match),
overrides
)
return profile_match
def get_container_profile(name=None, **kwargs):
'''
.. versionadded:: 2015.5.0
Gather a pre-configured set of container configuration parameters. If no
arguments are passed, an empty profile is returned.
Profiles can be defined in the minion or master config files, or in pillar
or grains, and are loaded using :mod:`config.get
<salt.modules.config.get>`. The key under which LXC profiles must be
configured is ``lxc.container_profile.profile_name``. An example container
profile would be as follows:
.. code-block:: yaml
lxc.container_profile:
ubuntu:
template: ubuntu
backing: lvm
vgname: lxc
size: 1G
Parameters set in a profile can be overridden by passing additional
container creation arguments (such as the ones passed to :mod:`lxc.create
<salt.modules.lxc.create>`) to this function.
A profile can be defined either as the name of the profile, or a dictionary
of variable names and values. See the :ref:`LXC Tutorial
<tutorial-lxc-profiles>` for more information on how to use LXC profiles.
CLI Example:
.. code-block:: bash
salt-call lxc.get_container_profile centos
salt-call lxc.get_container_profile ubuntu template=ubuntu backing=overlayfs
'''
profile = _get_profile('container_profile', name, **kwargs)
return profile
def get_network_profile(name=None, **kwargs):
'''
.. versionadded:: 2015.5.0
Gather a pre-configured set of network configuration parameters. If no
arguments are passed, the following default profile is returned:
.. code-block:: python
{'eth0': {'link': 'br0', 'type': 'veth', 'flags': 'up'}}
Profiles can be defined in the minion or master config files, or in pillar
or grains, and are loaded using :mod:`config.get
<salt.modules.config.get>`. The key under which LXC profiles must be
configured is ``lxc.network_profile``. An example network profile would be
as follows:
.. code-block:: yaml
lxc.network_profile.centos:
eth0:
link: br0
type: veth
flags: up
To disable networking entirely:
.. code-block:: yaml
lxc.network_profile.centos:
eth0:
disable: true
Parameters set in a profile can be overridden by passing additional
arguments to this function.
A profile can be passed either as the name of the profile, or a
dictionary of variable names and values. See the :ref:`LXC Tutorial
<tutorial-lxc-profiles>` for more information on how to use network
profiles.
.. warning::
The ``ipv4``, ``ipv6``, ``gateway``, and ``link`` (bridge) settings in
network profiles will only work if the container doesn't redefine the
network configuration (for example in
``/etc/sysconfig/network-scripts/ifcfg-<interface_name>`` on
RHEL/CentOS, or ``/etc/network/interfaces`` on Debian/Ubuntu/etc.)
CLI Example:
.. code-block:: bash
salt-call lxc.get_network_profile default
'''
profile = _get_profile('network_profile', name, **kwargs)
return profile
def _rand_cpu_str(cpu):
'''
Return a random subset of cpus for the cpuset config
'''
cpu = int(cpu)
avail = __salt__['status.nproc']()
if cpu < avail:
return '0-{0}'.format(avail)
to_set = set()
while len(to_set) < cpu:
choice = random.randint(0, avail - 1)
if choice not in to_set:
to_set.add(six.text_type(choice))
return ','.join(sorted(to_set))
def _network_conf(conf_tuples=None, **kwargs):
'''
Network configuration defaults
network_profile
as for containers, we can either call this function
either with a network_profile dict or network profile name
in the kwargs
nic_opts
overrides or extra nics in the form {nic_name: {set: tings}
'''
nic = kwargs.get('network_profile', None)
ret = []
nic_opts = kwargs.get('nic_opts', {})
if nic_opts is None:
# coming from elsewhere
nic_opts = {}
if not conf_tuples:
conf_tuples = []
old = _get_veths(conf_tuples)
if not old:
old = {}
# if we have a profile name, get the profile and load the network settings
# this will obviously by default look for a profile called "eth0"
# or by what is defined in nic_opts
# and complete each nic settings by sane defaults
if nic and isinstance(nic, (six.string_types, dict)):
nicp = get_network_profile(nic)
else:
nicp = {}
if DEFAULT_NIC not in nicp:
nicp[DEFAULT_NIC] = {}
kwargs = copy.deepcopy(kwargs)
gateway = kwargs.pop('gateway', None)
bridge = kwargs.get('bridge', None)
if nic_opts:
for dev, args in six.iteritems(nic_opts):
ethx = nicp.setdefault(dev, {})
try:
ethx = salt.utils.dictupdate.update(ethx, args)
except AttributeError:
raise SaltInvocationError('Invalid nic_opts configuration')
ifs = [a for a in nicp]
ifs += [a for a in old if a not in nicp]
ifs.sort()
gateway_set = False
for dev in ifs:
args = nicp.get(dev, {})
opts = nic_opts.get(dev, {}) if nic_opts else {}
old_if = old.get(dev, {})
disable = opts.get('disable', args.get('disable', False))
if disable:
continue
mac = opts.get('mac',
opts.get('hwaddr',
args.get('mac',
args.get('hwaddr', ''))))
type_ = opts.get('type', args.get('type', ''))
flags = opts.get('flags', args.get('flags', ''))
link = opts.get('link', args.get('link', ''))
ipv4 = opts.get('ipv4', args.get('ipv4', ''))
ipv6 = opts.get('ipv6', args.get('ipv6', ''))
infos = salt.utils.odict.OrderedDict([
('lxc.network.type', {
'test': not type_,
'value': type_,
'old': old_if.get('lxc.network.type'),
'default': 'veth'}),
('lxc.network.name', {
'test': False,
'value': dev,
'old': dev,
'default': dev}),
('lxc.network.flags', {
'test': not flags,
'value': flags,
'old': old_if.get('lxc.network.flags'),
'default': 'up'}),
('lxc.network.link', {
'test': not link,
'value': link,
'old': old_if.get('lxc.network.link'),
'default': search_lxc_bridge()}),
('lxc.network.hwaddr', {
'test': not mac,
'value': mac,
'old': old_if.get('lxc.network.hwaddr'),
'default': salt.utils.network.gen_mac()}),
('lxc.network.ipv4', {
'test': not ipv4,
'value': ipv4,
'old': old_if.get('lxc.network.ipv4', ''),
'default': None}),
('lxc.network.ipv6', {
'test': not ipv6,
'value': ipv6,
'old': old_if.get('lxc.network.ipv6', ''),
'default': None})])
# for each parameter, if not explicitly set, the
# config value present in the LXC configuration should
# take precedence over the profile configuration
for info in list(infos.keys()):
bundle = infos[info]
if bundle['test']:
if bundle['old']:
bundle['value'] = bundle['old']
elif bundle['default']:
bundle['value'] = bundle['default']
for info, data in six.iteritems(infos):
if data['value']:
ret.append({info: data['value']})
for key, val in six.iteritems(args):
if key == 'link' and bridge:
val = bridge
val = opts.get(key, val)
if key in [
'type', 'flags', 'name',
'gateway', 'mac', 'link', 'ipv4', 'ipv6'
]:
continue
ret.append({'lxc.network.{0}'.format(key): val})
# gateway (in automode) must be appended following network conf !
if not gateway:
gateway = args.get('gateway', None)
if gateway is not None and not gateway_set:
ret.append({'lxc.network.ipv4.gateway': gateway})
# only one network gateway ;)
gateway_set = True
# normally, this won't happen
# set the gateway if specified even if we did
# not managed the network underlying
if gateway is not None and not gateway_set:
ret.append({'lxc.network.ipv4.gateway': gateway})
# only one network gateway ;)
gateway_set = True
new = _get_veths(ret)
# verify that we did not loose the mac settings
for iface in [a for a in new]:
ndata = new[iface]
nmac = ndata.get('lxc.network.hwaddr', '')
ntype = ndata.get('lxc.network.type', '')
omac, otype = '', ''
if iface in old:
odata = old[iface]
omac = odata.get('lxc.network.hwaddr', '')
otype = odata.get('lxc.network.type', '')
# default for network type is setted here
# attention not to change the network type
# without a good and explicit reason to.
if otype and not ntype:
ntype = otype
if not ntype:
ntype = 'veth'
new[iface]['lxc.network.type'] = ntype
if omac and not nmac:
new[iface]['lxc.network.hwaddr'] = omac
ret = []
for val in six.itervalues(new):
for row in val:
ret.append(salt.utils.odict.OrderedDict([(row, val[row])]))
# on old versions of lxc, still support the gateway auto mode
# if we didn't explicitly say no to
# (lxc.network.ipv4.gateway: auto)
if _LooseVersion(version()) <= _LooseVersion('1.0.7') and \
True not in ['lxc.network.ipv4.gateway' in a for a in ret] and \
True in ['lxc.network.ipv4' in a for a in ret]:
ret.append({'lxc.network.ipv4.gateway': 'auto'})
return ret
def _get_lxc_default_data(**kwargs):
kwargs = copy.deepcopy(kwargs)
ret = {}
for k in ['utsname', 'rootfs']:
val = kwargs.get(k, None)
if val is not None:
ret['lxc.{0}'.format(k)] = val
autostart = kwargs.get('autostart')
# autostart can have made in kwargs, but with the None
# value which is invalid, we need an explicit boolean
# autostart = on is the default.
if autostart is None:
autostart = True
# we will set the regular lxc marker to restart container at
# machine (re)boot only if we did not explicitly ask
# not to touch to the autostart settings via
# autostart == 'keep'
if autostart != 'keep':
if autostart:
ret['lxc.start.auto'] = '1'
else:
ret['lxc.start.auto'] = '0'
memory = kwargs.get('memory')
if memory is not None:
# converting the config value from MB to bytes
ret['lxc.cgroup.memory.limit_in_bytes'] = memory * 1024 * 1024
cpuset = kwargs.get('cpuset')
if cpuset:
ret['lxc.cgroup.cpuset.cpus'] = cpuset
cpushare = kwargs.get('cpushare')
cpu = kwargs.get('cpu')
if cpushare:
ret['lxc.cgroup.cpu.shares'] = cpushare
if cpu and not cpuset:
ret['lxc.cgroup.cpuset.cpus'] = _rand_cpu_str(cpu)
return ret
def _config_list(conf_tuples=None, only_net=False, **kwargs):
'''
Return a list of dicts from the salt level configurations
conf_tuples
_LXCConfig compatible list of entries which can contain
- string line
- tuple (lxc config param,value)
- dict of one entry: {lxc config param: value)
only_net
by default we add to the tuples a reflection of both
the real config if avalaible and a certain amount of
default values like the cpu parameters, the memory
and etc.
On the other hand, we also no matter the case reflect
the network configuration computed from the actual config if
available and given values.
if no_default_loads is set, we will only
reflect the network configuration back to the conf tuples
list
'''
# explicit cast
only_net = bool(only_net)
if not conf_tuples:
conf_tuples = []
kwargs = copy.deepcopy(kwargs)
ret = []
if not only_net:
default_data = _get_lxc_default_data(**kwargs)
for k, val in six.iteritems(default_data):
ret.append({k: val})
net_datas = _network_conf(conf_tuples=conf_tuples, **kwargs)
ret.extend(net_datas)
return ret
def _get_veths(net_data):
'''
Parse the nic setup inside lxc conf tuples back to a dictionary indexed by
network interface
'''
if isinstance(net_data, dict):
net_data = list(net_data.items())
nics = salt.utils.odict.OrderedDict()
current_nic = salt.utils.odict.OrderedDict()
no_names = True
for item in net_data:
if item and isinstance(item, dict):
item = list(item.items())[0]
# skip LXC configuration comment lines, and play only with tuples conf
elif isinstance(item, six.string_types):
# deal with reflection of commented lxc configs
sitem = item.strip()
if sitem.startswith('#') or not sitem:
continue
elif '=' in item:
item = tuple([a.strip() for a in item.split('=', 1)])
if item[0] == 'lxc.network.type':
current_nic = salt.utils.odict.OrderedDict()
if item[0] == 'lxc.network.name':
no_names = False
nics[item[1].strip()] = current_nic
current_nic[item[0].strip()] = item[1].strip()
# if not ethernet card name has been collected, assuming we collected
# data for eth0
if no_names and current_nic:
nics[DEFAULT_NIC] = current_nic
return nics
class _LXCConfig(object):
'''
LXC configuration data
'''
pattern = re.compile(r'^(\S+)(\s*)(=)(\s*)(.*)')
non_interpretable_pattern = re.compile(r'^((#.*)|(\s*))$')
def __init__(self, **kwargs):
kwargs = copy.deepcopy(kwargs)
self.name = kwargs.pop('name', None)
path = get_root_path(kwargs.get('path', None))
self.data = []
if self.name:
self.path = os.path.join(path, self.name, 'config')
if os.path.isfile(self.path):
with salt.utils.files.fopen(self.path) as fhr:
for line in salt.utils.data.decode(fhr.readlines()):
match = self.pattern.findall((line.strip()))
if match:
self.data.append((match[0][0], match[0][-1]))
match = self.non_interpretable_pattern.findall(
(line.strip()))
if match:
self.data.append(('', match[0][0]))
else:
self.path = None
def _replace(key, val):
if val:
self._filter_data(key)
self.data.append((key, val))
default_data = _get_lxc_default_data(**kwargs)
for key, val in six.iteritems(default_data):
_replace(key, val)
old_net = self._filter_data('lxc.network')
net_datas = _network_conf(conf_tuples=old_net, **kwargs)
if net_datas:
for row in net_datas:
self.data.extend(list(row.items()))
# be sure to reset harmful settings
for idx in ['lxc.cgroup.memory.limit_in_bytes']:
if not default_data.get(idx):
self._filter_data(idx)
def as_string(self):
chunks = ('{0[0]}{1}{0[1]}'.format(item, (' = ' if item[0] else '')) for item in self.data)
return '\n'.join(chunks) + '\n'
def write(self):
if self.path:
content = self.as_string()
# 2 step rendering to be sure not to open/wipe the config
# before as_string succeeds.
with salt.utils.files.fopen(self.path, 'w') as fic:
fic.write(salt.utils.stringutils.to_str(content))
fic.flush()
def tempfile(self):
# this might look like the function name is shadowing the
# module, but it's not since the method belongs to the class
ntf = tempfile.NamedTemporaryFile()
ntf.write(self.as_string())
ntf.flush()
return ntf
def _filter_data(self, pattern):
'''
Removes parameters which match the pattern from the config data
'''
removed = []
filtered = []
for param in self.data:
if not param[0].startswith(pattern):
filtered.append(param)
else:
removed.append(param)
self.data = filtered
return removed
def _get_base(**kwargs):
'''
If the needed base does not exist, then create it, if it does exist
create nothing and return the name of the base lxc container so
it can be cloned.
'''
profile = get_container_profile(copy.deepcopy(kwargs.get('profile')))
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, _marker)
profile_match = profile.pop(key, default)
# let kwarg overrides be the preferred choice
if kw_overrides_match is _marker:
return profile_match
return kw_overrides_match
template = select('template')
image = select('image')
vgname = select('vgname')
path = kwargs.get('path', None)
# remove the above three variables from kwargs, if they exist, to avoid
# duplicates if create() is invoked below.
for param in ('path', 'image', 'vgname', 'template'):
kwargs.pop(param, None)
if image:
proto = _urlparse(image).scheme
img_tar = __salt__['cp.cache_file'](image)
img_name = os.path.basename(img_tar)
hash_ = salt.utils.hashutils.get_hash(
img_tar,
__salt__['config.get']('hash_type'))
name = '__base_{0}_{1}_{2}'.format(proto, img_name, hash_)
if not exists(name, path=path):
create(name, template=template, image=image,
path=path, vgname=vgname, **kwargs)
if vgname:
rootfs = os.path.join('/dev', vgname, name)
edit_conf(info(name, path=path)['config'],
out_format='commented', **{'lxc.rootfs': rootfs})
return name
elif template:
name = '__base_{0}'.format(template)
if not exists(name, path=path):
create(name, template=template, image=image, path=path,
vgname=vgname, **kwargs)
if vgname:
rootfs = os.path.join('/dev', vgname, name)
edit_conf(info(name, path=path)['config'],
out_format='commented', **{'lxc.rootfs': rootfs})
return name
return ''
def init(name,
config=None,
cpuset=None,
cpushare=None,
memory=None,
profile=None,
network_profile=None,
nic_opts=None,
cpu=None,
autostart=True,
password=None,
password_encrypted=None,
users=None,
dnsservers=None,
searchdomains=None,
bridge=None,
gateway=None,
pub_key=None,
priv_key=None,
force_install=False,
unconditional_install=False,
bootstrap_delay=None,
bootstrap_args=None,
bootstrap_shell=None,
bootstrap_url=None,
**kwargs):
'''
Initialize a new container.
This is a partial idempotent function as if it is already provisioned, we
will reset a bit the lxc configuration file but much of the hard work will
be escaped as markers will prevent re-execution of harmful tasks.
name
Name of the container
image
A tar archive to use as the rootfs for the container. Conflicts with
the ``template`` argument.
cpus
Select a random number of cpu cores and assign it to the cpuset, if the
cpuset option is set then this option will be ignored
cpuset
Explicitly define the cpus this container will be bound to
cpushare
cgroups cpu shares
autostart
autostart container on reboot
memory
cgroups memory limit, in MB
.. versionchanged:: 2015.5.0
If no value is passed, no limit is set. In earlier Salt versions,
not passing this value causes a 1024MB memory limit to be set, and
it was necessary to pass ``memory=0`` to set no limit.
gateway
the ipv4 gateway to use
the default does nothing more than lxcutils does
bridge
the bridge to use
the default does nothing more than lxcutils does
network_profile
Network profile to use for the container
.. versionadded:: 2015.5.0
nic_opts
Extra options for network interfaces, will override
``{"eth0": {"hwaddr": "aa:bb:cc:dd:ee:ff", "ipv4": "10.1.1.1", "ipv6": "2001:db8::ff00:42:8329"}}``
or
``{"eth0": {"hwaddr": "aa:bb:cc:dd:ee:ff", "ipv4": "10.1.1.1/24", "ipv6": "2001:db8::ff00:42:8329"}}``
users
Users for which the password defined in the ``password`` param should
be set. Can be passed as a comma separated list or a python list.
Defaults to just the ``root`` user.
password
Set the initial password for the users defined in the ``users``
parameter
password_encrypted : False
Set to ``True`` to denote a password hash instead of a plaintext
password
.. versionadded:: 2015.5.0
profile
A LXC profile (defined in config or pillar).
This can be either a real profile mapping or a string
to retrieve it in configuration
start
Start the newly-created container
dnsservers
list of dns servers to set in the container, default [] (no setting)
seed
Seed the container with the minion config. Default: ``True``
install
If salt-minion is not already installed, install it. Default: ``True``
config
Optional config parameters. By default, the id is set to
the name of the container.
master
salt master (default to minion's master)
master_port
salt master port (default to minion's master port)
pub_key
Explicit public key to preseed the minion with (optional).
This can be either a filepath or a string representing the key
priv_key
Explicit private key to preseed the minion with (optional).
This can be either a filepath or a string representing the key
approve_key
If explicit preseeding is not used;
Attempt to request key approval from the master. Default: ``True``
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
clone_from
Original from which to use a clone operation to create the container.
Default: ``None``
bootstrap_delay
Delay in seconds between end of container creation and bootstrapping.
Useful when waiting for container to obtain a DHCP lease.
.. versionadded:: 2015.5.0
bootstrap_url
See lxc.bootstrap
bootstrap_shell
See lxc.bootstrap
bootstrap_args
See lxc.bootstrap
force_install
Force installation even if salt-minion is detected,
this is the way to run vendor bootstrap scripts even
if a salt minion is already present in the container
unconditional_install
Run the script even if the container seems seeded
CLI Example:
.. code-block:: bash
salt 'minion' lxc.init name [cpuset=cgroups_cpuset] \\
[cpushare=cgroups_cpushare] [memory=cgroups_memory] \\
[nic=nic_profile] [profile=lxc_profile] \\
[nic_opts=nic_opts] [start=(True|False)] \\
[seed=(True|False)] [install=(True|False)] \\
[config=minion_config] [approve_key=(True|False) \\
[clone_from=original] [autostart=True] \\
[priv_key=/path_or_content] [pub_key=/path_or_content] \\
[bridge=lxcbr0] [gateway=10.0.3.1] \\
[dnsservers[dns1,dns2]] \\
[users=[foo]] [password='secret'] \\
[password_encrypted=(True|False)]
'''
ret = {'name': name,
'changes': {}}
profile = get_container_profile(copy.deepcopy(profile))
if not network_profile:
network_profile = profile.get('network_profile')
if not network_profile:
network_profile = DEFAULT_NIC
# Changes is a pointer to changes_dict['init']. This method is used so that
# we can have a list of changes as they are made, providing an ordered list
# of things that were changed.
changes_dict = {'init': []}
changes = changes_dict.get('init')
if users is None:
users = []
dusers = ['root']
for user in dusers:
if user not in users:
users.append(user)
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, _marker)
profile_match = profile.pop(key, default)
# let kwarg overrides be the preferred choice
if kw_overrides_match is _marker:
return profile_match
return kw_overrides_match
path = select('path')
bpath = get_root_path(path)
state_pre = state(name, path=path)
tvg = select('vgname')
vgname = tvg if tvg else __salt__['config.get']('lxc.vgname')
start_ = select('start', True)
autostart = select('autostart', autostart)
seed = select('seed', True)
install = select('install', True)
seed_cmd = select('seed_cmd')
salt_config = _get_salt_config(config, **kwargs)
approve_key = select('approve_key', True)
clone_from = select('clone_from')
# If using a volume group then set up to make snapshot cow clones
if vgname and not clone_from:
try:
kwargs['vgname'] = vgname
clone_from = _get_base(profile=profile, **kwargs)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = exc.strerror
if changes:
ret['changes'] = changes_dict
return ret
if not kwargs.get('snapshot') is False:
kwargs['snapshot'] = True
does_exist = exists(name, path=path)
to_reboot = False
remove_seed_marker = False
if does_exist:
pass
elif clone_from:
remove_seed_marker = True
try:
clone(name, clone_from, profile=profile, **kwargs)
changes.append({'create': 'Container cloned'})
except (SaltInvocationError, CommandExecutionError) as exc:
if 'already exists' in exc.strerror:
changes.append({'create': 'Container already exists'})
else:
ret['result'] = False
ret['comment'] = exc.strerror
if changes:
ret['changes'] = changes_dict
return ret
cfg = _LXCConfig(name=name, network_profile=network_profile,
nic_opts=nic_opts, bridge=bridge, path=path,
gateway=gateway, autostart=autostart,
cpuset=cpuset, cpushare=cpushare, memory=memory)
old_chunks = read_conf(cfg.path, out_format='commented')
cfg.write()
chunks = read_conf(cfg.path, out_format='commented')
if old_chunks != chunks:
to_reboot = True
else:
remove_seed_marker = True
cfg = _LXCConfig(network_profile=network_profile,
nic_opts=nic_opts, cpuset=cpuset, path=path,
bridge=bridge, gateway=gateway,
autostart=autostart,
cpushare=cpushare, memory=memory)
with cfg.tempfile() as cfile:
try:
create(name, config=cfile.name, profile=profile, **kwargs)
changes.append({'create': 'Container created'})
except (SaltInvocationError, CommandExecutionError) as exc:
if 'already exists' in exc.strerror:
changes.append({'create': 'Container already exists'})
else:
ret['comment'] = exc.strerror
if changes:
ret['changes'] = changes_dict
return ret
cpath = os.path.join(bpath, name, 'config')
old_chunks = []
if os.path.exists(cpath):
old_chunks = read_conf(cpath, out_format='commented')
new_cfg = _config_list(conf_tuples=old_chunks,
cpu=cpu,
network_profile=network_profile,
nic_opts=nic_opts, bridge=bridge,
cpuset=cpuset, cpushare=cpushare,
memory=memory)
if new_cfg:
edit_conf(cpath, out_format='commented', lxc_config=new_cfg)
chunks = read_conf(cpath, out_format='commented')
if old_chunks != chunks:
to_reboot = True
# last time to be sure any of our property is correctly applied
cfg = _LXCConfig(name=name, network_profile=network_profile,
nic_opts=nic_opts, bridge=bridge, path=path,
gateway=gateway, autostart=autostart,
cpuset=cpuset, cpushare=cpushare, memory=memory)
old_chunks = []
if os.path.exists(cfg.path):
old_chunks = read_conf(cfg.path, out_format='commented')
cfg.write()
chunks = read_conf(cfg.path, out_format='commented')
if old_chunks != chunks:
changes.append({'config': 'Container configuration updated'})
to_reboot = True
if to_reboot:
try:
stop(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
if changes:
ret['changes'] = changes_dict
return ret
if not does_exist or (does_exist and state(name, path=path) != 'running'):
try:
start(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
if changes:
ret['changes'] = changes_dict
return ret
if remove_seed_marker:
run(name,
'rm -f \'{0}\''.format(SEED_MARKER),
path=path,
chroot_fallback=False,
python_shell=False)
# set the default user/password, only the first time
if ret.get('result', True) and password:
gid = '/.lxc.initial_pass'
gids = [gid,
'/lxc.initial_pass',
'/.lxc.{0}.initial_pass'.format(name)]
if not any(retcode(name,
'test -e "{0}"'.format(x),
chroot_fallback=True,
path=path,
ignore_retcode=True) == 0
for x in gids):
# think to touch the default user generated by default templates
# which has a really unsecure passwords...
# root is defined as a member earlier in the code
for default_user in ['ubuntu']:
if (
default_user not in users and
retcode(name,
'id {0}'.format(default_user),
python_shell=False,
path=path,
chroot_fallback=True,
ignore_retcode=True) == 0
):
users.append(default_user)
for user in users:
try:
cret = set_password(name,
users=[user],
path=path,
password=password,
encrypted=password_encrypted)
except (SaltInvocationError, CommandExecutionError) as exc:
msg = '{0}: Failed to set password'.format(
user) + exc.strerror
# only hardfail in unrecoverable situation:
# root cannot be setted up
if user == 'root':
ret['comment'] = msg
ret['result'] = False
else:
log.debug(msg)
if ret.get('result', True):
changes.append({'password': 'Password(s) updated'})
if retcode(name,
('sh -c \'touch "{0}"; test -e "{0}"\''
.format(gid)),
path=path,
chroot_fallback=True,
ignore_retcode=True) != 0:
ret['comment'] = 'Failed to set password marker'
changes[-1]['password'] += '. ' + ret['comment'] + '.'
ret['result'] = False
# set dns servers if any, only the first time
if ret.get('result', True) and dnsservers:
# retro compatibility, test also old markers
gid = '/.lxc.initial_dns'
gids = [gid,
'/lxc.initial_dns',
'/lxc.{0}.initial_dns'.format(name)]
if not any(retcode(name,
'test -e "{0}"'.format(x),
chroot_fallback=True,
path=path,
ignore_retcode=True) == 0
for x in gids):
try:
set_dns(name,
path=path,
dnsservers=dnsservers,
searchdomains=searchdomains)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Failed to set DNS: ' + exc.strerror
ret['result'] = False
else:
changes.append({'dns': 'DNS updated'})
if retcode(name,
('sh -c \'touch "{0}"; test -e "{0}"\''
.format(gid)),
chroot_fallback=True,
path=path,
ignore_retcode=True) != 0:
ret['comment'] = 'Failed to set DNS marker'
changes[-1]['dns'] += '. ' + ret['comment'] + '.'
ret['result'] = False
# retro compatibility, test also old markers
if remove_seed_marker:
run(name,
'rm -f \'{0}\''.format(SEED_MARKER),
path=path,
python_shell=False)
gid = '/.lxc.initial_seed'
gids = [gid, '/lxc.initial_seed']
if (
any(retcode(name,
'test -e {0}'.format(x),
path=path,
chroot_fallback=True,
ignore_retcode=True) == 0
for x in gids) or not ret.get('result', True)
):
pass
elif seed or seed_cmd:
if seed:
try:
result = bootstrap(
name, config=salt_config, path=path,
approve_key=approve_key,
pub_key=pub_key, priv_key=priv_key,
install=install,
force_install=force_install,
unconditional_install=unconditional_install,
bootstrap_delay=bootstrap_delay,
bootstrap_url=bootstrap_url,
bootstrap_shell=bootstrap_shell,
bootstrap_args=bootstrap_args)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Bootstrap failed: ' + exc.strerror
ret['result'] = False
else:
if not result:
ret['comment'] = ('Bootstrap failed, see minion log for '
'more information')
ret['result'] = False
else:
changes.append(
{'bootstrap': 'Container successfully bootstrapped'}
)
elif seed_cmd:
try:
result = __salt__[seed_cmd](info(name, path=path)['rootfs'],
name,
salt_config)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = ('Bootstrap via seed_cmd \'{0}\' failed: {1}'
.format(seed_cmd, exc.strerror))
ret['result'] = False
else:
if not result:
ret['comment'] = ('Bootstrap via seed_cmd \'{0}\' failed, '
'see minion log for more information '
.format(seed_cmd))
ret['result'] = False
else:
changes.append(
{'bootstrap': 'Container successfully bootstrapped '
'using seed_cmd \'{0}\''
.format(seed_cmd)}
)
if ret.get('result', True) and not start_:
try:
stop(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
ret['result'] = False
state_post = state(name, path=path)
if state_pre != state_post:
changes.append({'state': {'old': state_pre, 'new': state_post}})
if ret.get('result', True):
ret['comment'] = ('Container \'{0}\' successfully initialized'
.format(name))
ret['result'] = True
if changes:
ret['changes'] = changes_dict
return ret
def cloud_init(name, vm_=None, **kwargs):
'''
Thin wrapper to lxc.init to be used from the saltcloud lxc driver
name
Name of the container
may be None and then guessed from saltcloud mapping
`vm_`
saltcloud mapping defaults for the vm
CLI Example:
.. code-block:: bash
salt '*' lxc.cloud_init foo
'''
init_interface = cloud_init_interface(name, vm_, **kwargs)
name = init_interface.pop('name', name)
return init(name, **init_interface)
def images(dist=None):
'''
.. versionadded:: 2015.5.0
List the available images for LXC's ``download`` template.
dist : None
Filter results to a single Linux distribution
CLI Examples:
.. code-block:: bash
salt myminion lxc.images
salt myminion lxc.images dist=centos
'''
out = __salt__['cmd.run_stdout'](
'lxc-create -n __imgcheck -t download -- --list',
ignore_retcode=True
)
if 'DIST' not in out:
raise CommandExecutionError(
'Unable to run the \'download\' template script. Is it installed?'
)
ret = {}
passed_header = False
for line in out.splitlines():
try:
distro, release, arch, variant, build_time = line.split()
except ValueError:
continue
if not passed_header:
if distro == 'DIST':
passed_header = True
continue
dist_list = ret.setdefault(distro, [])
dist_list.append({
'release': release,
'arch': arch,
'variant': variant,
'build_time': build_time,
})
if dist is not None:
return dict([(dist, ret.get(dist, []))])
return ret
def templates():
'''
.. versionadded:: 2015.5.0
List the available LXC template scripts installed on the minion
CLI Examples:
.. code-block:: bash
salt myminion lxc.templates
'''
try:
template_scripts = os.listdir('/usr/share/lxc/templates')
except OSError:
return []
else:
return [x[4:] for x in template_scripts if x.startswith('lxc-')]
def _after_ignition_network_profile(cmd,
ret,
name,
network_profile,
path,
nic_opts):
_clear_context()
if ret['retcode'] == 0 and exists(name, path=path):
if network_profile:
network_changes = apply_network_profile(name,
network_profile,
path=path,
nic_opts=nic_opts)
if network_changes:
log.info(
'Network changes from applying network profile \'%s\' '
'to newly-created container \'%s\':\n%s',
network_profile, name, network_changes
)
c_state = state(name, path=path)
return {'result': True,
'state': {'old': None, 'new': c_state}}
else:
if exists(name, path=path):
# destroy the container if it was partially created
cmd = 'lxc-destroy'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0}'.format(name)
__salt__['cmd.retcode'](cmd, python_shell=False)
raise CommandExecutionError(
'Container could not be created with cmd \'{0}\': {1}'
.format(cmd, ret['stderr'])
)
def create(name,
config=None,
profile=None,
network_profile=None,
nic_opts=None,
**kwargs):
'''
Create a new container.
name
Name of the container
config
The config file to use for the container. Defaults to system-wide
config (usually in /etc/lxc/lxc.conf).
profile
Profile to use in container creation (see
:mod:`lxc.get_container_profile
<salt.modules.lxc.get_container_profile>`). Values in a profile will be
overridden by the **Container Creation Arguments** listed below.
network_profile
Network profile to use for container
.. versionadded:: 2015.5.0
**Container Creation Arguments**
template
The template to use. For example, ``ubuntu`` or ``fedora``.
For a full list of available templates, check out
the :mod:`lxc.templates <salt.modules.lxc.templates>` function.
Conflicts with the ``image`` argument.
.. note::
The ``download`` template requires the following three parameters
to be defined in ``options``:
* **dist** - The name of the distribution
* **release** - Release name/version
* **arch** - Architecture of the container
The available images can be listed using the :mod:`lxc.images
<salt.modules.lxc.images>` function.
options
Template-specific options to pass to the lxc-create command. These
correspond to the long options (ones beginning with two dashes) that
the template script accepts. For example:
.. code-block:: bash
options='{"dist": "centos", "release": "6", "arch": "amd64"}'
For available template options, refer to the lxc template scripts
which are ususally located under ``/usr/share/lxc/templates``,
or run ``lxc-create -t <template> -h``.
image
A tar archive to use as the rootfs for the container. Conflicts with
the ``template`` argument.
backing
The type of storage to use. Set to ``lvm`` to use an LVM group.
Defaults to filesystem within /var/lib/lxc.
fstype
Filesystem type to use on LVM logical volume
size : 1G
Size of the volume to create. Only applicable if ``backing=lvm``.
vgname : lxc
Name of the LVM volume group in which to create the volume for this
container. Only applicable if ``backing=lvm``.
lvname
Name of the LVM logical volume in which to create the volume for this
container. Only applicable if ``backing=lvm``.
thinpool
Name of a pool volume that will be used for thin-provisioning this
container. Only applicable if ``backing=lvm``.
nic_opts
give extra opts overriding network profile values
path
parent path for the container creation (default: /var/lib/lxc)
zfsroot
Name of the ZFS root in which to create the volume for this container.
Only applicable if ``backing=zfs``. (default: tank/lxc)
.. versionadded:: 2015.8.0
'''
# Required params for 'download' template
download_template_deps = ('dist', 'release', 'arch')
cmd = 'lxc-create -n {0}'.format(name)
profile = get_container_profile(copy.deepcopy(profile))
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, None)
profile_match = profile.pop(key, default)
# Return the profile match if the the kwarg match was None, as the
# lxc.present state will pass these kwargs set to None by default.
if kw_overrides_match is None:
return profile_match
return kw_overrides_match
path = select('path')
if exists(name, path=path):
raise CommandExecutionError(
'Container \'{0}\' already exists'.format(name)
)
tvg = select('vgname')
vgname = tvg if tvg else __salt__['config.get']('lxc.vgname')
# The 'template' and 'image' params conflict
template = select('template')
image = select('image')
if template and image:
raise SaltInvocationError(
'Only one of \'template\' and \'image\' is permitted'
)
elif not any((template, image, profile)):
raise SaltInvocationError(
'At least one of \'template\', \'image\', and \'profile\' is '
'required'
)
options = select('options') or {}
backing = select('backing')
if vgname and not backing:
backing = 'lvm'
lvname = select('lvname')
thinpool = select('thinpool')
fstype = select('fstype')
size = select('size', '1G')
zfsroot = select('zfsroot')
if backing in ('dir', 'overlayfs', 'btrfs', 'zfs'):
fstype = None
size = None
# some backends won't support some parameters
if backing in ('aufs', 'dir', 'overlayfs', 'btrfs'):
lvname = vgname = thinpool = None
if image:
img_tar = __salt__['cp.cache_file'](image)
template = os.path.join(
os.path.dirname(salt.__file__),
'templates',
'lxc',
'salt_tarball')
options['imgtar'] = img_tar
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
if not os.path.exists(path):
os.makedirs(path)
if config:
cmd += ' -f {0}'.format(config)
if template:
cmd += ' -t {0}'.format(template)
if backing:
backing = backing.lower()
cmd += ' -B {0}'.format(backing)
if backing in ('zfs',):
if zfsroot:
cmd += ' --zfsroot {0}'.format(zfsroot)
if backing in ('lvm',):
if lvname:
cmd += ' --lvname {0}'.format(lvname)
if vgname:
cmd += ' --vgname {0}'.format(vgname)
if thinpool:
cmd += ' --thinpool {0}'.format(thinpool)
if backing not in ('dir', 'overlayfs'):
if fstype:
cmd += ' --fstype {0}'.format(fstype)
if size:
cmd += ' --fssize {0}'.format(size)
if options:
if template == 'download':
missing_deps = [x for x in download_template_deps
if x not in options]
if missing_deps:
raise SaltInvocationError(
'Missing params in \'options\' dict: {0}'
.format(', '.join(missing_deps))
)
cmd += ' --'
for key, val in six.iteritems(options):
cmd += ' --{0} {1}'.format(key, val)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
# please do not merge extra conflicting stuff
# inside those two line (ret =, return)
return _after_ignition_network_profile(cmd,
ret,
name,
network_profile,
path,
nic_opts)
def clone(name,
orig,
profile=None,
network_profile=None,
nic_opts=None,
**kwargs):
'''
Create a new container as a clone of another container
name
Name of the container
orig
Name of the original container to be cloned
profile
Profile to use in container cloning (see
:mod:`lxc.get_container_profile
<salt.modules.lxc.get_container_profile>`). Values in a profile will be
overridden by the **Container Cloning Arguments** listed below.
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
**Container Cloning Arguments**
snapshot
Use Copy On Write snapshots (LVM)
size : 1G
Size of the volume to create. Only applicable if ``backing=lvm``.
backing
The type of storage to use. Set to ``lvm`` to use an LVM group.
Defaults to filesystem within /var/lib/lxc.
network_profile
Network profile to use for container
.. versionadded:: 2015.8.0
nic_opts
give extra opts overriding network profile values
.. versionadded:: 2015.8.0
CLI Examples:
.. code-block:: bash
salt '*' lxc.clone myclone orig=orig_container
salt '*' lxc.clone myclone orig=orig_container snapshot=True
'''
profile = get_container_profile(copy.deepcopy(profile))
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, None)
profile_match = profile.pop(key, default)
# let kwarg overrides be the preferred choice
if kw_overrides_match is None:
return profile_match
return kw_overrides_match
path = select('path')
if exists(name, path=path):
raise CommandExecutionError(
'Container \'{0}\' already exists'.format(name)
)
_ensure_exists(orig, path=path)
if state(orig, path=path) != 'stopped':
raise CommandExecutionError(
'Container \'{0}\' must be stopped to be cloned'.format(orig)
)
backing = select('backing')
snapshot = select('snapshot')
if backing in ('dir',):
snapshot = False
if not snapshot:
snapshot = ''
else:
snapshot = '-s'
size = select('size', '1G')
if backing in ('dir', 'overlayfs', 'btrfs'):
size = None
# LXC commands and options changed in 2.0 - CF issue #34086 for details
if _LooseVersion(version()) >= _LooseVersion('2.0'):
# https://linuxcontainers.org/lxc/manpages//man1/lxc-copy.1.html
cmd = 'lxc-copy'
cmd += ' {0} -n {1} -N {2}'.format(snapshot, orig, name)
else:
# https://linuxcontainers.org/lxc/manpages//man1/lxc-clone.1.html
cmd = 'lxc-clone'
cmd += ' {0} -o {1} -n {2}'.format(snapshot, orig, name)
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
if not os.path.exists(path):
os.makedirs(path)
if backing:
backing = backing.lower()
cmd += ' -B {0}'.format(backing)
if backing not in ('dir', 'overlayfs'):
if size:
cmd += ' -L {0}'.format(size)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
# please do not merge extra conflicting stuff
# inside those two line (ret =, return)
return _after_ignition_network_profile(cmd,
ret,
name,
network_profile,
path,
nic_opts)
def ls_(active=None, cache=True, path=None):
'''
Return a list of the containers available on the minion
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
active
If ``True``, return only active (i.e. running) containers
.. versionadded:: 2015.5.0
CLI Example:
.. code-block:: bash
salt '*' lxc.ls
salt '*' lxc.ls active=True
'''
contextvar = 'lxc.ls{0}'.format(path)
if active:
contextvar += '.active'
if cache and (contextvar in __context__):
return __context__[contextvar]
else:
ret = []
cmd = 'lxc-ls'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
if active:
cmd += ' --active'
output = __salt__['cmd.run_stdout'](cmd, python_shell=False)
for line in output.splitlines():
ret.extend(line.split())
__context__[contextvar] = ret
return ret
def list_(extra=False, limit=None, path=None):
'''
List containers classified by state
extra
Also get per-container specific info. This will change the return data.
Instead of returning a list of containers, a dictionary of containers
and each container's output from :mod:`lxc.info
<salt.modules.lxc.info>`.
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
limit
Return output matching a specific state (**frozen**, **running**, or
**stopped**).
.. versionadded:: 2015.5.0
CLI Examples:
.. code-block:: bash
salt '*' lxc.list
salt '*' lxc.list extra=True
salt '*' lxc.list limit=running
'''
ctnrs = ls_(path=path)
if extra:
stopped = {}
frozen = {}
running = {}
else:
stopped = []
frozen = []
running = []
ret = {'running': running,
'stopped': stopped,
'frozen': frozen}
for container in ctnrs:
cmd = 'lxc-info'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0}'.format(container)
c_info = __salt__['cmd.run'](
cmd,
python_shell=False,
output_loglevel='debug'
)
c_state = None
for line in c_info.splitlines():
stat = line.split(':')
if stat[0] in ('State', 'state'):
c_state = stat[1].strip()
break
if not c_state or (limit is not None and c_state.lower() != limit):
continue
if extra:
infos = info(container, path=path)
method = 'update'
value = {container: infos}
else:
method = 'append'
value = container
if c_state == 'STOPPED':
getattr(stopped, method)(value)
continue
if c_state == 'FROZEN':
getattr(frozen, method)(value)
continue
if c_state == 'RUNNING':
getattr(running, method)(value)
continue
if limit is not None:
return ret.get(limit, {} if extra else [])
return ret
def _change_state(cmd,
name,
expected,
stdin=_marker,
stdout=_marker,
stderr=_marker,
with_communicate=_marker,
use_vt=_marker,
path=None):
pre = state(name, path=path)
if pre == expected:
return {'result': True,
'state': {'old': expected, 'new': expected},
'comment': 'Container \'{0}\' already {1}'
.format(name, expected)}
if cmd == 'lxc-destroy':
# Kill the container first
scmd = 'lxc-stop'
if path:
scmd += ' -P {0}'.format(pipes.quote(path))
scmd += ' -k -n {0}'.format(name)
__salt__['cmd.run'](scmd,
python_shell=False)
if path and ' -P ' not in cmd:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0}'.format(name)
# certain lxc commands need to be taken with care (lxc-start)
# as te command itself mess with double forks; we must not
# communicate with it, but just wait for the exit status
pkwargs = {'python_shell': False,
'redirect_stderr': True,
'with_communicate': with_communicate,
'use_vt': use_vt,
'stdin': stdin,
'stdout': stdout}
for i in [a for a in pkwargs]:
val = pkwargs[i]
if val is _marker:
pkwargs.pop(i, None)
_cmdout = __salt__['cmd.run_all'](cmd, **pkwargs)
if _cmdout['retcode'] != 0:
raise CommandExecutionError(
'Error changing state for container \'{0}\' using command '
'\'{1}\': {2}'.format(name, cmd, _cmdout['stdout'])
)
if expected is not None:
# some commands do not wait, so we will
rcmd = 'lxc-wait'
if path:
rcmd += ' -P {0}'.format(pipes.quote(path))
rcmd += ' -n {0} -s {1}'.format(name, expected.upper())
__salt__['cmd.run'](rcmd, python_shell=False, timeout=30)
_clear_context()
post = state(name, path=path)
ret = {'result': post == expected,
'state': {'old': pre, 'new': post}}
return ret
def _ensure_exists(name, path=None):
'''
Raise an exception if the container does not exist
'''
if not exists(name, path=path):
raise CommandExecutionError(
'Container \'{0}\' does not exist'.format(name)
)
def _ensure_running(name, no_start=False, path=None):
'''
If the container is not currently running, start it. This function returns
the state that the container was in before changing
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
'''
_ensure_exists(name, path=path)
pre = state(name, path=path)
if pre == 'running':
# This will be a no-op but running the function will give us a pretty
# return dict.
return start(name, path=path)
elif pre == 'stopped':
if no_start:
raise CommandExecutionError(
'Container \'{0}\' is not running'.format(name)
)
return start(name, path=path)
elif pre == 'frozen':
if no_start:
raise CommandExecutionError(
'Container \'{0}\' is not running'.format(name)
)
return unfreeze(name, path=path)
def restart(name, path=None, lxc_config=None, force=False):
'''
.. versionadded:: 2015.5.0
Restart the named container. If the container was not running, the
container will merely be started.
name
The name of the container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
lxc_config
path to a lxc config file
config file will be guessed from container name otherwise
.. versionadded:: 2015.8.0
force : False
If ``True``, the container will be force-stopped instead of gracefully
shut down
CLI Example:
.. code-block:: bash
salt myminion lxc.restart name
'''
_ensure_exists(name, path=path)
orig_state = state(name, path=path)
if orig_state != 'stopped':
stop(name, kill=force, path=path)
ret = start(name, path=path, lxc_config=lxc_config)
ret['state']['old'] = orig_state
if orig_state != 'stopped':
ret['restarted'] = True
return ret
def start(name, **kwargs):
'''
Start the named container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
lxc_config
path to a lxc config file
config file will be guessed from container name otherwise
.. versionadded:: 2015.8.0
use_vt
run the command through VT
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.start name
'''
path = kwargs.get('path', None)
cpath = get_root_path(path)
lxc_config = kwargs.get('lxc_config', None)
cmd = 'lxc-start'
if not lxc_config:
lxc_config = os.path.join(cpath, name, 'config')
# we try to start, even without config, if global opts are there
if os.path.exists(lxc_config):
cmd += ' -f {0}'.format(pipes.quote(lxc_config))
cmd += ' -d'
_ensure_exists(name, path=path)
if state(name, path=path) == 'frozen':
raise CommandExecutionError(
'Container \'{0}\' is frozen, use lxc.unfreeze'.format(name)
)
# lxc-start daemonize itself violently, we must not communicate with it
use_vt = kwargs.get('use_vt', None)
with_communicate = kwargs.get('with_communicate', False)
return _change_state(cmd, name, 'running',
stdout=None,
stderr=None,
stdin=None,
with_communicate=with_communicate,
path=path,
use_vt=use_vt)
def stop(name, kill=False, path=None, use_vt=None):
'''
Stop the named container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
kill: False
Do not wait for the container to stop, kill all tasks in the container.
Older LXC versions will stop containers like this irrespective of this
argument.
.. versionchanged:: 2015.5.0
Default value changed to ``False``
use_vt
run the command through VT
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.stop name
'''
_ensure_exists(name, path=path)
orig_state = state(name, path=path)
if orig_state == 'frozen' and not kill:
# Gracefully stopping a frozen container is slower than unfreezing and
# then stopping it (at least in my testing), so if we're not
# force-stopping the container, unfreeze it first.
unfreeze(name, path=path)
cmd = 'lxc-stop'
if kill:
cmd += ' -k'
ret = _change_state(cmd, name, 'stopped', use_vt=use_vt, path=path)
ret['state']['old'] = orig_state
return ret
def freeze(name, **kwargs):
'''
Freeze the named container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
start : False
If ``True`` and the container is stopped, the container will be started
before attempting to freeze.
.. versionadded:: 2015.5.0
use_vt
run the command through VT
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.freeze name
'''
use_vt = kwargs.get('use_vt', None)
path = kwargs.get('path', None)
_ensure_exists(name, path=path)
orig_state = state(name, path=path)
start_ = kwargs.get('start', False)
if orig_state == 'stopped':
if not start_:
raise CommandExecutionError(
'Container \'{0}\' is stopped'.format(name)
)
start(name, path=path)
cmd = 'lxc-freeze'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
ret = _change_state(cmd, name, 'frozen', use_vt=use_vt, path=path)
if orig_state == 'stopped' and start_:
ret['state']['old'] = orig_state
ret['started'] = True
ret['state']['new'] = state(name, path=path)
return ret
def unfreeze(name, path=None, use_vt=None):
'''
Unfreeze the named container.
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
use_vt
run the command through VT
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.unfreeze name
'''
_ensure_exists(name, path=path)
if state(name, path=path) == 'stopped':
raise CommandExecutionError(
'Container \'{0}\' is stopped'.format(name)
)
cmd = 'lxc-unfreeze'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
return _change_state(cmd, name, 'running', path=path, use_vt=use_vt)
def destroy(name, stop=False, path=None):
'''
Destroy the named container.
.. warning::
Destroys all data associated with the container.
path
path to the container parent directory (default: /var/lib/lxc)
.. versionadded:: 2015.8.0
stop : False
If ``True``, the container will be destroyed even if it is
running/frozen.
.. versionchanged:: 2015.5.0
Default value changed to ``False``. This more closely matches the
behavior of ``lxc-destroy(1)``, and also makes it less likely that
an accidental command will destroy a running container that was
being used for important things.
CLI Examples:
.. code-block:: bash
salt '*' lxc.destroy foo
salt '*' lxc.destroy foo stop=True
'''
_ensure_exists(name, path=path)
if not stop and state(name, path=path) != 'stopped':
raise CommandExecutionError(
'Container \'{0}\' is not stopped'.format(name)
)
return _change_state('lxc-destroy', name, None, path=path)
# Compatibility between LXC and nspawn
remove = salt.utils.functools.alias_function(destroy, 'remove')
def exists(name, path=None):
'''
Returns whether the named container exists.
path
path to the container parent directory (default: /var/lib/lxc)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.exists name
'''
_exists = name in ls_(path=path)
# container may be just created but we did cached earlier the
# lxc-ls results
if not _exists:
_exists = name in ls_(cache=False, path=path)
return _exists
def state(name, path=None):
'''
Returns the state of a container.
path
path to the container parent directory (default: /var/lib/lxc)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.state name
'''
# Don't use _ensure_exists() here, it will mess with _change_state()
cachekey = 'lxc.state.{0}{1}'.format(name, path)
try:
return __context__[cachekey]
except KeyError:
if not exists(name, path=path):
__context__[cachekey] = None
else:
cmd = 'lxc-info'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0}'.format(name)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
if ret['retcode'] != 0:
_clear_context()
raise CommandExecutionError(
'Unable to get state of container \'{0}\''.format(name)
)
c_infos = ret['stdout'].splitlines()
c_state = None
for c_info in c_infos:
stat = c_info.split(':')
if stat[0].lower() == 'state':
c_state = stat[1].strip().lower()
break
__context__[cachekey] = c_state
return __context__[cachekey]
def get_parameter(name, parameter, path=None):
'''
Returns the value of a cgroup parameter for a container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.get_parameter container_name memory.limit_in_bytes
'''
_ensure_exists(name, path=path)
cmd = 'lxc-cgroup'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0} {1}'.format(name, parameter)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
if ret['retcode'] != 0:
raise CommandExecutionError(
'Unable to retrieve value for \'{0}\''.format(parameter)
)
return ret['stdout'].strip()
def set_parameter(name, parameter, value, path=None):
'''
Set the value of a cgroup parameter for a container.
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.set_parameter name parameter value
'''
if not exists(name, path=path):
return None
cmd = 'lxc-cgroup'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0} {1} {2}'.format(name, parameter, value)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
if ret['retcode'] != 0:
return False
else:
return True
def info(name, path=None):
'''
Returns information about a container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.info name
'''
cachekey = 'lxc.info.{0}{1}'.format(name, path)
try:
return __context__[cachekey]
except KeyError:
_ensure_exists(name, path=path)
cpath = get_root_path(path)
try:
conf_file = os.path.join(cpath, name, 'config')
except AttributeError:
conf_file = os.path.join(cpath, six.text_type(name), 'config')
if not os.path.isfile(conf_file):
raise CommandExecutionError(
'LXC config file {0} does not exist'.format(conf_file)
)
ret = {}
config = []
with salt.utils.files.fopen(conf_file) as fp_:
for line in fp_:
line = salt.utils.stringutils.to_unicode(line)
comps = [x.strip() for x in
line.split('#', 1)[0].strip().split('=', 1)]
if len(comps) == 2:
config.append(tuple(comps))
ifaces = []
current = None
for key, val in config:
if key == 'lxc.network.type':
current = {'type': val}
ifaces.append(current)
elif not current:
continue
elif key.startswith('lxc.network.'):
current[key.replace('lxc.network.', '', 1)] = val
if ifaces:
ret['nics'] = ifaces
ret['rootfs'] = next(
(x[1] for x in config if x[0] == 'lxc.rootfs'),
None
)
ret['state'] = state(name, path=path)
ret['ips'] = []
ret['public_ips'] = []
ret['private_ips'] = []
ret['public_ipv4_ips'] = []
ret['public_ipv6_ips'] = []
ret['private_ipv4_ips'] = []
ret['private_ipv6_ips'] = []
ret['ipv4_ips'] = []
ret['ipv6_ips'] = []
ret['size'] = None
ret['config'] = conf_file
if ret['state'] == 'running':
try:
limit = int(get_parameter(name, 'memory.limit_in_bytes'))
except (CommandExecutionError, TypeError, ValueError):
limit = 0
try:
usage = int(get_parameter(name, 'memory.usage_in_bytes'))
except (CommandExecutionError, TypeError, ValueError):
usage = 0
free = limit - usage
ret['memory_limit'] = limit
ret['memory_free'] = free
size = run_stdout(name, 'df /', path=path, python_shell=False)
# The size is the 2nd column of the last line
ret['size'] = size.splitlines()[-1].split()[1]
# First try iproute2
ip_cmd = run_all(
name, 'ip link show', path=path, python_shell=False)
if ip_cmd['retcode'] == 0:
ip_data = ip_cmd['stdout']
ip_cmd = run_all(
name, 'ip addr show', path=path, python_shell=False)
ip_data += '\n' + ip_cmd['stdout']
ip_data = salt.utils.network._interfaces_ip(ip_data)
else:
# That didn't work, try ifconfig
ip_cmd = run_all(
name, 'ifconfig', path=path, python_shell=False)
if ip_cmd['retcode'] == 0:
ip_data = \
salt.utils.network._interfaces_ifconfig(
ip_cmd['stdout'])
else:
# Neither was successful, give up
log.warning(
'Unable to run ip or ifconfig in container \'%s\'', name
)
ip_data = {}
ret['ipv4_ips'] = salt.utils.network.ip_addrs(
include_loopback=True,
interface_data=ip_data
)
ret['ipv6_ips'] = salt.utils.network.ip_addrs6(
include_loopback=True,
interface_data=ip_data
)
ret['ips'] = ret['ipv4_ips'] + ret['ipv6_ips']
for address in ret['ipv4_ips']:
if address == '127.0.0.1':
ret['private_ips'].append(address)
ret['private_ipv4_ips'].append(address)
elif salt.utils.cloud.is_public_ip(address):
ret['public_ips'].append(address)
ret['public_ipv4_ips'].append(address)
else:
ret['private_ips'].append(address)
ret['private_ipv4_ips'].append(address)
for address in ret['ipv6_ips']:
if address == '::1' or address.startswith('fe80'):
ret['private_ips'].append(address)
ret['private_ipv6_ips'].append(address)
else:
ret['public_ips'].append(address)
ret['public_ipv6_ips'].append(address)
for key in [x for x in ret if x == 'ips' or x.endswith('ips')]:
ret[key].sort(key=_ip_sort)
__context__[cachekey] = ret
return __context__[cachekey]
def set_password(name, users, password, encrypted=True, path=None):
'''
.. versionchanged:: 2015.5.0
Function renamed from ``set_pass`` to ``set_password``. Additionally,
this function now supports (and defaults to using) a password hash
instead of a plaintext password.
Set the password of one or more system users inside containers
users
Comma-separated list (or python list) of users to change password
password
Password to set for the specified user(s)
encrypted : True
If true, ``password`` must be a password hash. Set to ``False`` to set
a plaintext password (not recommended).
.. versionadded:: 2015.5.0
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.set_pass container-name root '$6$uJ2uAyLU$KoI67t8As/0fXtJOPcHKGXmUpcoYUcVR2K6x93walnShTCQvjRwq25yIkiCBOqgbfdKQSFnAo28/ek6716vEV1'
salt '*' lxc.set_pass container-name root foo encrypted=False
'''
def _bad_user_input():
raise SaltInvocationError('Invalid input for \'users\' parameter')
if not isinstance(users, list):
try:
users = users.split(',')
except AttributeError:
_bad_user_input()
if not users:
_bad_user_input()
failed_users = []
for user in users:
result = retcode(name,
'chpasswd{0}'.format(' -e' if encrypted else ''),
stdin=':'.join((user, password)),
python_shell=False,
path=path,
chroot_fallback=True,
output_loglevel='quiet')
if result != 0:
failed_users.append(user)
if failed_users:
raise CommandExecutionError(
'Password change failed for the following user(s): {0}'
.format(', '.join(failed_users))
)
return True
set_pass = salt.utils.functools.alias_function(set_password, 'set_pass')
def update_lxc_conf(name, lxc_conf, lxc_conf_unset, path=None):
'''
Edit LXC configuration options
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.update_lxc_conf ubuntu \\
lxc_conf="[{'network.ipv4.ip':'10.0.3.5'}]" \\
lxc_conf_unset="['lxc.utsname']"
'''
_ensure_exists(name, path=path)
cpath = get_root_path(path)
lxc_conf_p = os.path.join(cpath, name, 'config')
if not os.path.exists(lxc_conf_p):
raise SaltInvocationError(
'Configuration file {0} does not exist'.format(lxc_conf_p)
)
changes = {'edited': [], 'added': [], 'removed': []}
ret = {'changes': changes, 'result': True, 'comment': ''}
# do not use salt.utils.files.fopen !
with salt.utils.files.fopen(lxc_conf_p, 'r') as fic:
filtered_lxc_conf = []
for row in lxc_conf:
if not row:
continue
for conf in row:
filtered_lxc_conf.append((conf.strip(),
row[conf].strip()))
ret['comment'] = 'lxc.conf is up to date'
lines = []
orig_config = salt.utils.stringutils.to_unicode(fic.read())
for line in orig_config.splitlines():
if line.startswith('#') or not line.strip():
lines.append([line, ''])
else:
line = line.split('=')
index = line.pop(0)
val = (index.strip(), '='.join(line).strip())
if val not in lines:
lines.append(val)
for key, item in filtered_lxc_conf:
matched = False
for idx, line in enumerate(lines[:]):
if line[0] == key:
matched = True
lines[idx] = (key, item)
if '='.join(line[1:]).strip() != item.strip():
changes['edited'].append(
({line[0]: line[1:]}, {key: item}))
break
if not matched:
if (key, item) not in lines:
lines.append((key, item))
changes['added'].append({key: item})
dest_lxc_conf = []
# filter unset
if lxc_conf_unset:
for line in lines:
for opt in lxc_conf_unset:
if (
not line[0].startswith(opt) and
line not in dest_lxc_conf
):
dest_lxc_conf.append(line)
else:
changes['removed'].append(opt)
else:
dest_lxc_conf = lines
conf = ''
for key, val in dest_lxc_conf:
if not val:
conf += '{0}\n'.format(key)
else:
conf += '{0} = {1}\n'.format(key.strip(), val.strip())
conf_changed = conf != orig_config
chrono = datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S')
if conf_changed:
# DO NOT USE salt.utils.files.fopen here, i got (kiorky)
# problems with lxc configs which were wiped !
with salt.utils.files.fopen('{0}.{1}'.format(lxc_conf_p, chrono), 'w') as wfic:
wfic.write(salt.utils.stringutils.to_str(conf))
with salt.utils.files.fopen(lxc_conf_p, 'w') as wfic:
wfic.write(salt.utils.stringutils.to_str(conf))
ret['comment'] = 'Updated'
ret['result'] = True
if not any(changes[x] for x in changes):
# Ensure an empty changes dict if nothing was modified
ret['changes'] = {}
return ret
def set_dns(name, dnsservers=None, searchdomains=None, path=None):
'''
.. versionchanged:: 2015.5.0
The ``dnsservers`` and ``searchdomains`` parameters can now be passed
as a comma-separated list.
Update /etc/resolv.confo
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.set_dns ubuntu "['8.8.8.8', '4.4.4.4']"
'''
if dnsservers is None:
dnsservers = ['8.8.8.8', '4.4.4.4']
elif not isinstance(dnsservers, list):
try:
dnsservers = dnsservers.split(',')
except AttributeError:
raise SaltInvocationError(
'Invalid input for \'dnsservers\' parameter'
)
if searchdomains is None:
searchdomains = []
elif not isinstance(searchdomains, list):
try:
searchdomains = searchdomains.split(',')
except AttributeError:
raise SaltInvocationError(
'Invalid input for \'searchdomains\' parameter'
)
dns = ['nameserver {0}'.format(x) for x in dnsservers]
dns.extend(['search {0}'.format(x) for x in searchdomains])
dns = '\n'.join(dns) + '\n'
# we may be using resolvconf in the container
# We need to handle that case with care:
# - we create the resolv.conf runtime directory (the
# linked directory) as anyway it will be shadowed when the real
# runned tmpfs mountpoint will be mounted.
# ( /etc/resolv.conf -> ../run/resolvconf/resolv.conf)
# Indeed, it can save us in any other case (running, eg, in a
# bare chroot when repairing or preparing the container for
# operation.
# - We also teach resolvconf to use the aforementioned dns.
# - We finally also set /etc/resolv.conf in all cases
rstr = __salt__['test.random_hash']()
# no tmp here, apparmor won't let us execute !
script = '/sbin/{0}_dns.sh'.format(rstr)
DNS_SCRIPT = "\n".join([
# 'set -x',
'#!/usr/bin/env bash',
'if [ -h /etc/resolv.conf ];then',
' if [ "x$(readlink /etc/resolv.conf)"'
' = "x../run/resolvconf/resolv.conf" ];then',
' if [ ! -d /run/resolvconf/ ];then',
' mkdir -p /run/resolvconf',
' fi',
' cat > /etc/resolvconf/resolv.conf.d/head <<EOF',
dns,
'EOF',
'',
' fi',
'fi',
'cat > /etc/resolv.conf <<EOF',
dns,
'EOF',
''])
result = run_all(
name, 'tee {0}'.format(script), path=path,
stdin=DNS_SCRIPT, python_shell=True)
if result['retcode'] == 0:
result = run_all(
name, 'sh -c "chmod +x {0};{0}"'.format(script),
path=path, python_shell=True)
# blindly delete the setter file
run_all(name,
'sh -c \'if [ -f "{0}" ];then rm -f "{0}";fi\''.format(script),
path=path, python_shell=True)
if result['retcode'] != 0:
error = ('Unable to write to /etc/resolv.conf in container \'{0}\''
.format(name))
if result['stderr']:
error += ': {0}'.format(result['stderr'])
raise CommandExecutionError(error)
return True
def running_systemd(name, cache=True, path=None):
'''
Determine if systemD is running
path
path to the container parent
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.running_systemd ubuntu
'''
k = 'lxc.systemd.test.{0}{1}'.format(name, path)
ret = __context__.get(k, None)
if ret is None or not cache:
rstr = __salt__['test.random_hash']()
# no tmp here, apparmor won't let us execute !
script = '/sbin/{0}_testsystemd.sh'.format(rstr)
# ubuntu already had since trusty some bits of systemd but was
# still using upstart ...
# we need to be a bit more careful that just testing that systemd
# is present
_script = textwrap.dedent(
'''\
#!/usr/bin/env bash
set -x
if ! command -v systemctl 1>/dev/null 2>/dev/null;then exit 2;fi
for i in \\
/run/systemd/journal/dev-log\\
/run/systemd/journal/flushed\\
/run/systemd/journal/kernel-seqnum\\
/run/systemd/journal/socket\\
/run/systemd/journal/stdout\\
/var/run/systemd/journal/dev-log\\
/var/run/systemd/journal/flushed\\
/var/run/systemd/journal/kernel-seqnum\\
/var/run/systemd/journal/socket\\
/var/run/systemd/journal/stdout\\
;do\\
if test -e ${i};then exit 0;fi
done
if test -d /var/systemd/system;then exit 0;fi
exit 2
''')
result = run_all(
name, 'tee {0}'.format(script), path=path,
stdin=_script, python_shell=True)
if result['retcode'] == 0:
result = run_all(name,
'sh -c "chmod +x {0};{0}"'''.format(script),
path=path,
python_shell=True)
else:
raise CommandExecutionError(
'lxc {0} failed to copy initd tester'.format(name))
run_all(name,
'sh -c \'if [ -f "{0}" ];then rm -f "{0}";fi\''
''.format(script),
path=path,
ignore_retcode=True,
python_shell=True)
if result['retcode'] != 0:
error = ('Unable to determine if the container \'{0}\''
' was running systemd, assmuming it is not.'
''.format(name))
if result['stderr']:
error += ': {0}'.format(result['stderr'])
# only cache result if we got a known exit code
if result['retcode'] in (0, 2):
__context__[k] = ret = not result['retcode']
return ret
def systemd_running_state(name, path=None):
'''
Get the operational state of a systemd based container
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.systemd_running_state ubuntu
'''
try:
ret = run_all(name,
'systemctl is-system-running',
path=path,
ignore_retcode=True)['stdout']
except CommandExecutionError:
ret = ''
return ret
def test_sd_started_state(name, path=None):
'''
Test if a systemd container is fully started
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.test_sd_started_state ubuntu
'''
qstate = systemd_running_state(name, path=path)
if qstate in ('initializing', 'starting'):
return False
elif qstate == '':
return None
else:
return True
def test_bare_started_state(name, path=None):
'''
Test if a non systemd container is fully started
For now, it consists only to test if the container is attachable
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.test_bare_started_state ubuntu
'''
try:
ret = run_all(
name, 'ls', path=path, ignore_retcode=True
)['retcode'] == 0
except (CommandExecutionError,):
ret = None
return ret
def wait_started(name, path=None, timeout=300):
'''
Check that the system has fully inited
This is actually very important for systemD based containers
see https://github.com/saltstack/salt/issues/23847
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.wait_started ubuntu
'''
if not exists(name, path=path):
raise CommandExecutionError(
'Container {0} does does exists'.format(name))
if not state(name, path=path) == 'running':
raise CommandExecutionError(
'Container {0} is not running'.format(name))
ret = False
if running_systemd(name, path=path):
test_started = test_sd_started_state
logger = log.error
else:
test_started = test_bare_started_state
logger = log.debug
now = time.time()
expire = now + timeout
now = time.time()
started = test_started(name, path=path)
while time.time() < expire and not started:
time.sleep(0.3)
started = test_started(name, path=path)
if started is None:
logger(
'Assuming %s is started, although we failed to detect that'
' is fully started correctly', name)
ret = True
else:
ret = started
return ret
def _needs_install(name, path=None):
ret = 0
has_minion = retcode(name,
'which salt-minion',
path=path,
ignore_retcode=True)
# we assume that installing is when no minion is running
# but testing the executable presence is not enougth for custom
# installs where the bootstrap can do much more than installing
# the bare salt binaries.
if has_minion:
processes = run_stdout(name, "ps aux", path=path)
if 'salt-minion' not in processes:
ret = 1
else:
retcode(name, 'salt-call --local service.stop salt-minion')
else:
ret = 1
return ret
def bootstrap(name,
config=None,
approve_key=True,
install=True,
pub_key=None,
priv_key=None,
bootstrap_url=None,
force_install=False,
unconditional_install=False,
path=None,
bootstrap_delay=None,
bootstrap_args=None,
bootstrap_shell=None):
'''
Install and configure salt in a container.
config
Minion configuration options. By default, the ``master`` option is set
to the target host's master.
approve_key
Request a pre-approval of the generated minion key. Requires
that the salt-master be configured to either auto-accept all keys or
expect a signing request from the target host. Default: ``True``
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
pub_key
Explicit public key to pressed the minion with (optional).
This can be either a filepath or a string representing the key
priv_key
Explicit private key to pressed the minion with (optional).
This can be either a filepath or a string representing the key
bootstrap_delay
Delay in seconds between end of container creation and bootstrapping.
Useful when waiting for container to obtain a DHCP lease.
.. versionadded:: 2015.5.0
bootstrap_url
url, content or filepath to the salt bootstrap script
bootstrap_args
salt bootstrap script arguments
bootstrap_shell
shell to execute the script into
install
Whether to attempt a full installation of salt-minion if needed.
force_install
Force installation even if salt-minion is detected,
this is the way to run vendor bootstrap scripts even
if a salt minion is already present in the container
unconditional_install
Run the script even if the container seems seeded
CLI Examples:
.. code-block:: bash
salt 'minion' lxc.bootstrap container_name [config=config_data] \\
[approve_key=(True|False)] [install=(True|False)]
'''
wait_started(name, path=path)
if bootstrap_delay is not None:
try:
log.info('LXC %s: bootstrap_delay: %s', name, bootstrap_delay)
time.sleep(bootstrap_delay)
except TypeError:
# Bad input, but assume since a value was passed that
# a delay was desired, and sleep for 5 seconds
time.sleep(5)
c_info = info(name, path=path)
if not c_info:
return None
# default set here as we cannot set them
# in def as it can come from a chain of procedures.
if bootstrap_args:
# custom bootstrap args can be totally customized, and user could
# have inserted the placeholder for the config directory.
# For example, some salt bootstrap script do not use at all -c
if '{0}' not in bootstrap_args:
bootstrap_args += ' -c {0}'
else:
bootstrap_args = '-c {0}'
if not bootstrap_shell:
bootstrap_shell = 'sh'
orig_state = _ensure_running(name, path=path)
if not orig_state:
return orig_state
if not force_install:
needs_install = _needs_install(name, path=path)
else:
needs_install = True
seeded = retcode(name,
'test -e \'{0}\''.format(SEED_MARKER),
path=path,
chroot_fallback=True,
ignore_retcode=True) == 0
tmp = tempfile.mkdtemp()
if seeded and not unconditional_install:
ret = True
else:
ret = False
cfg_files = __salt__['seed.mkconfig'](
config, tmp=tmp, id_=name, approve_key=approve_key,
pub_key=pub_key, priv_key=priv_key)
if needs_install or force_install or unconditional_install:
if install:
rstr = __salt__['test.random_hash']()
configdir = '/var/tmp/.c_{0}'.format(rstr)
cmd = 'install -m 0700 -d {0}'.format(configdir)
if run_all(
name, cmd, path=path, python_shell=False
)['retcode'] != 0:
log.error('tmpdir %s creation failed %s', configdir, cmd)
return False
bs_ = __salt__['config.gather_bootstrap_script'](
bootstrap=bootstrap_url)
script = '/sbin/{0}_bootstrap.sh'.format(rstr)
copy_to(name, bs_, script, path=path)
result = run_all(name,
'sh -c "chmod +x {0}"'.format(script),
path=path,
python_shell=True)
copy_to(name, cfg_files['config'],
os.path.join(configdir, 'minion'),
path=path)
copy_to(name, cfg_files['privkey'],
os.path.join(configdir, 'minion.pem'),
path=path)
copy_to(name, cfg_files['pubkey'],
os.path.join(configdir, 'minion.pub'),
path=path)
bootstrap_args = bootstrap_args.format(configdir)
cmd = ('{0} {2} {1}'
.format(bootstrap_shell,
bootstrap_args.replace("'", "''"),
script))
# log ASAP the forged bootstrap command which can be wrapped
# out of the output in case of unexpected problem
log.info('Running %s in LXC container \'%s\'', cmd, name)
ret = retcode(name, cmd, output_loglevel='info',
path=path, use_vt=True) == 0
run_all(name,
'sh -c \'if [ -f "{0}" ];then rm -f "{0}";fi\''
''.format(script),
path=path,
ignore_retcode=True,
python_shell=True)
else:
ret = False
else:
minion_config = salt.config.minion_config(cfg_files['config'])
pki_dir = minion_config['pki_dir']
copy_to(name,
cfg_files['config'],
'/etc/salt/minion',
path=path)
copy_to(name,
cfg_files['privkey'],
os.path.join(pki_dir, 'minion.pem'),
path=path)
copy_to(name,
cfg_files['pubkey'],
os.path.join(pki_dir, 'minion.pub'),
path=path)
run(name,
'salt-call --local service.enable salt-minion',
path=path,
python_shell=False)
ret = True
shutil.rmtree(tmp)
if orig_state == 'stopped':
stop(name, path=path)
elif orig_state == 'frozen':
freeze(name, path=path)
# mark seeded upon successful install
if ret:
run(name,
'touch \'{0}\''.format(SEED_MARKER),
path=path,
python_shell=False)
return ret
def attachable(name, path=None):
'''
Return True if the named container can be attached to via the lxc-attach
command
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt 'minion' lxc.attachable ubuntu
'''
cachekey = 'lxc.attachable{0}{1}'.format(name, path)
try:
return __context__[cachekey]
except KeyError:
_ensure_exists(name, path=path)
# Can't use run() here because it uses attachable() and would
# endlessly recurse, resulting in a traceback
log.debug('Checking if LXC container %s is attachable', name)
cmd = 'lxc-attach'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' --clear-env -n {0} -- /usr/bin/env'.format(name)
result = __salt__['cmd.retcode'](cmd,
python_shell=False,
output_loglevel='quiet',
ignore_retcode=True) == 0
__context__[cachekey] = result
return __context__[cachekey]
def _run(name,
cmd,
output=None,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=None,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
Common logic for lxc.run functions
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
'''
orig_state = state(name, path=path)
try:
if attachable(name, path=path):
ret = __salt__['container_resource.run'](
name,
cmd,
path=path,
container_type=__virtualname__,
exec_driver=EXEC_DRIVER,
output=output,
no_start=no_start,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
ignore_retcode=ignore_retcode,
use_vt=use_vt,
keep_env=keep_env)
else:
if not chroot_fallback:
raise CommandExecutionError(
'{0} is not attachable.'.format(name))
rootfs = info(name, path=path).get('rootfs')
# Set context var to make cmd.run_chroot run cmd.run instead of
# cmd.run_all.
__context__['cmd.run_chroot.func'] = __salt__['cmd.run']
ret = __salt__['cmd.run_chroot'](rootfs,
cmd,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
ignore_retcode=ignore_retcode)
except Exception:
raise
finally:
# Make sure we honor preserve_state, even if there was an exception
new_state = state(name, path=path)
if preserve_state:
if orig_state == 'stopped' and new_state != 'stopped':
stop(name, path=path)
elif orig_state == 'frozen' and new_state != 'frozen':
freeze(name, start=True, path=path)
if output in (None, 'all'):
return ret
else:
return ret[output]
def run(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.8.0
Run :mod:`cmd.run <salt.modules.cmdmod.run>` within a container
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed in stderr if the command being run
does not exist. If no output is returned using this function, try using
:mod:`lxc.run_stderr <salt.modules.lxc.run_stderr>` or
:mod:`lxc.run_all <salt.modules.lxc.run_all>`.
name
Name of the container in which to run the command
cmd
Command to run
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console. Assumes
``output=all``.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
CLI Example:
.. code-block:: bash
salt myminion lxc.run mycontainer 'ifconfig -a'
'''
return _run(name,
cmd,
path=path,
output=None,
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def run_stdout(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.5.0
Run :mod:`cmd.run_stdout <salt.modules.cmdmod.run_stdout>` within a container
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed in stderr if the command being run
does not exist. If no output is returned using this function, try using
:mod:`lxc.run_stderr <salt.modules.lxc.run_stderr>` or
:mod:`lxc.run_all <salt.modules.lxc.run_all>`.
name
Name of the container in which to run the command
cmd
Command to run
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console
``output=all``.
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
CLI Example:
.. code-block:: bash
salt myminion lxc.run_stdout mycontainer 'ifconfig -a'
'''
return _run(name,
cmd,
path=path,
output='stdout',
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def run_stderr(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.5.0
Run :mod:`cmd.run_stderr <salt.modules.cmdmod.run_stderr>` within a container
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed if the command being run does not
exist.
name
Name of the container in which to run the command
cmd
Command to run
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console
``output=all``.
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
CLI Example:
.. code-block:: bash
salt myminion lxc.run_stderr mycontainer 'ip addr show'
'''
return _run(name,
cmd,
path=path,
output='stderr',
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def retcode(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.5.0
Run :mod:`cmd.retcode <salt.modules.cmdmod.retcode>` within a container
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed in stderr if the command being run
does not exist. If the retcode is nonzero and not what was expected,
try using :mod:`lxc.run_stderr <salt.modules.lxc.run_stderr>`
or :mod:`lxc.run_all <salt.modules.lxc.run_all>`.
name
Name of the container in which to run the command
cmd
Command to run
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console
``output=all``.
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
CLI Example:
.. code-block:: bash
salt myminion lxc.retcode mycontainer 'ip addr show'
'''
return _run(name,
cmd,
output='retcode',
path=path,
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def run_all(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.5.0
Run :mod:`cmd.run_all <salt.modules.cmdmod.run_all>` within a container
.. note::
While the command is run within the container, it is initiated from the
host. Therefore, the PID in the return dict is from the host, not from
the container.
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed in stderr if the command being run
does not exist.
name
Name of the container in which to run the command
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
cmd
Command to run
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console
``output=all``.
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
CLI Example:
.. code-block:: bash
salt myminion lxc.run_all mycontainer 'ip addr show'
'''
return _run(name,
cmd,
output='all',
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
path=path,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def _get_md5(name, path):
'''
Get the MD5 checksum of a file from a container
'''
output = run_stdout(name, 'md5sum "{0}"'.format(path),
chroot_fallback=True,
ignore_retcode=True)
try:
return output.split()[0]
except IndexError:
# Destination file does not exist or could not be accessed
return None
def copy_to(name, source, dest, overwrite=False, makedirs=False, path=None):
'''
.. versionchanged:: 2015.8.0
Function renamed from ``lxc.cp`` to ``lxc.copy_to`` for consistency
with other container types. ``lxc.cp`` will continue to work, however.
For versions 2015.2.x and earlier, use ``lxc.cp``.
Copy a file or directory from the host into a container
name
Container name
source
File to be copied to the container
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
dest
Destination on the container. Must be an absolute path.
.. versionchanged:: 2015.5.0
If the destination is a directory, the file will be copied into
that directory.
overwrite : False
Unless this option is set to ``True``, then if a file exists at the
location specified by the ``dest`` argument, an error will be raised.
.. versionadded:: 2015.8.0
makedirs : False
Create the parent directory on the container if it does not already
exist.
.. versionadded:: 2015.5.0
CLI Example:
.. code-block:: bash
salt 'minion' lxc.copy_to /tmp/foo /root/foo
salt 'minion' lxc.cp /tmp/foo /root/foo
'''
_ensure_running(name, no_start=True, path=path)
return __salt__['container_resource.copy_to'](
name,
source,
dest,
container_type=__virtualname__,
path=path,
exec_driver=EXEC_DRIVER,
overwrite=overwrite,
makedirs=makedirs)
cp = salt.utils.functools.alias_function(copy_to, 'cp')
def read_conf(conf_file, out_format='simple'):
'''
Read in an LXC configuration file. By default returns a simple, unsorted
dict, but can also return a more detailed structure including blank lines
and comments.
out_format:
set to 'simple' if you need the old and unsupported behavior.
This won't support the multiple lxc values (eg: multiple network nics)
CLI Examples:
.. code-block:: bash
salt 'minion' lxc.read_conf /etc/lxc/mycontainer.conf
salt 'minion' lxc.read_conf /etc/lxc/mycontainer.conf out_format=commented
'''
ret_commented = []
ret_simple = {}
with salt.utils.files.fopen(conf_file, 'r') as fp_:
for line in salt.utils.data.decode(fp_.readlines()):
if '=' not in line:
ret_commented.append(line)
continue
comps = line.split('=')
value = '='.join(comps[1:]).strip()
comment = None
if value.strip().startswith('#'):
vcomps = value.strip().split('#')
value = vcomps[1].strip()
comment = '#'.join(vcomps[1:]).strip()
ret_commented.append({comps[0].strip(): {
'value': value,
'comment': comment,
}})
else:
ret_commented.append({comps[0].strip(): value})
ret_simple[comps[0].strip()] = value
if out_format == 'simple':
return ret_simple
return ret_commented
def write_conf(conf_file, conf):
'''
Write out an LXC configuration file
This is normally only used internally. The format of the data structure
must match that which is returned from ``lxc.read_conf()``, with
``out_format`` set to ``commented``.
An example might look like:
.. code-block:: python
[
{'lxc.utsname': '$CONTAINER_NAME'},
'# This is a commented line\\n',
'\\n',
{'lxc.mount': '$CONTAINER_FSTAB'},
{'lxc.rootfs': {'comment': 'This is another test',
'value': 'This is another test'}},
'\\n',
{'lxc.network.type': 'veth'},
{'lxc.network.flags': 'up'},
{'lxc.network.link': 'br0'},
{'lxc.network.mac': '$CONTAINER_MACADDR'},
{'lxc.network.ipv4': '$CONTAINER_IPADDR'},
{'lxc.network.name': '$CONTAINER_DEVICENAME'},
]
CLI Example:
.. code-block:: bash
salt 'minion' lxc.write_conf /etc/lxc/mycontainer.conf \\
out_format=commented
'''
if not isinstance(conf, list):
raise SaltInvocationError('Configuration must be passed as a list')
# construct the content prior to write to the file
# to avoid half written configs
content = ''
for line in conf:
if isinstance(line, (six.text_type, six.string_types)):
content += line
elif isinstance(line, dict):
for key in list(line.keys()):
out_line = None
if isinstance(
line[key],
(six.text_type, six.string_types, six.integer_types, float)
):
out_line = ' = '.join((key, "{0}".format(line[key])))
elif isinstance(line[key], dict):
out_line = ' = '.join((key, line[key]['value']))
if 'comment' in line[key]:
out_line = ' # '.join((out_line, line[key]['comment']))
if out_line:
content += out_line
content += '\n'
with salt.utils.files.fopen(conf_file, 'w') as fp_:
fp_.write(salt.utils.stringutils.to_str(content))
return {}
def edit_conf(conf_file,
out_format='simple',
read_only=False,
lxc_config=None,
**kwargs):
'''
Edit an LXC configuration file. If a setting is already present inside the
file, its value will be replaced. If it does not exist, it will be appended
to the end of the file. Comments and blank lines will be kept in-tact if
they already exist in the file.
out_format:
Set to simple if you need backward compatibility (multiple items for a
simple key is not supported)
read_only:
return only the edited configuration without applying it
to the underlying lxc configuration file
lxc_config:
List of dict containning lxc configuration items
For network configuration, you also need to add the device it belongs
to, otherwise it will default to eth0.
Also, any change to a network parameter will result in the whole
network reconfiguration to avoid mismatchs, be aware of that !
After the file is edited, its contents will be returned. By default, it
will be returned in ``simple`` format, meaning an unordered dict (which
may not represent the actual file order). Passing in an ``out_format`` of
``commented`` will return a data structure which accurately represents the
order and content of the file.
CLI Example:
.. code-block:: bash
salt 'minion' lxc.edit_conf /etc/lxc/mycontainer.conf \\
out_format=commented lxc.network.type=veth
salt 'minion' lxc.edit_conf /etc/lxc/mycontainer.conf \\
out_format=commented \\
lxc_config="[{'lxc.network.name': 'eth0', \\
'lxc.network.ipv4': '1.2.3.4'},
{'lxc.network.name': 'eth2', \\
'lxc.network.ipv4': '1.2.3.5',\\
'lxc.network.gateway': '1.2.3.1'}]"
'''
data = []
try:
conf = read_conf(conf_file, out_format=out_format)
except Exception:
conf = []
if not lxc_config:
lxc_config = []
lxc_config = copy.deepcopy(lxc_config)
# search if we want to access net config
# in that case, we will replace all the net configuration
net_config = []
for lxc_kws in lxc_config + [kwargs]:
net_params = {}
for kwarg in [a for a in lxc_kws]:
if kwarg.startswith('__'):
continue
if kwarg.startswith('lxc.network.'):
net_params[kwarg] = lxc_kws[kwarg]
lxc_kws.pop(kwarg, None)
if net_params:
net_config.append(net_params)
nic_opts = salt.utils.odict.OrderedDict()
for params in net_config:
dev = params.get('lxc.network.name', DEFAULT_NIC)
dev_opts = nic_opts.setdefault(dev, salt.utils.odict.OrderedDict())
for param in params:
opt = param.replace('lxc.network.', '')
opt = {'hwaddr': 'mac'}.get(opt, opt)
dev_opts[opt] = params[param]
net_changes = []
if nic_opts:
net_changes = _config_list(conf, only_net=True,
**{'network_profile': DEFAULT_NIC,
'nic_opts': nic_opts})
if net_changes:
lxc_config.extend(net_changes)
for line in conf:
if not isinstance(line, dict):
data.append(line)
continue
else:
for key in list(line.keys()):
val = line[key]
if net_changes and key.startswith('lxc.network.'):
continue
found = False
for ix in range(len(lxc_config)):
kw = lxc_config[ix]
if key in kw:
found = True
data.append({key: kw[key]})
del kw[key]
if not found:
data.append({key: val})
for lxc_kws in lxc_config:
for kwarg in lxc_kws:
data.append({kwarg: lxc_kws[kwarg]})
if read_only:
return data
write_conf(conf_file, data)
return read_conf(conf_file, out_format)
def reboot(name, path=None):
'''
Reboot a container.
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Examples:
.. code-block:: bash
salt 'minion' lxc.reboot myvm
'''
ret = {'result': True,
'changes': {},
'comment': '{0} rebooted'.format(name)}
does_exist = exists(name, path=path)
if does_exist and (state(name, path=path) == 'running'):
try:
stop(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
ret['result'] = False
return ret
if does_exist and (state(name, path=path) != 'running'):
try:
start(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
ret['result'] = False
return ret
ret['changes'][name] = 'rebooted'
return ret
def reconfigure(name,
cpu=None,
cpuset=None,
cpushare=None,
memory=None,
profile=None,
network_profile=None,
nic_opts=None,
bridge=None,
gateway=None,
autostart=None,
utsname=None,
rootfs=None,
path=None,
**kwargs):
'''
Reconfigure a container.
This only applies to a few property
name
Name of the container.
utsname
utsname of the container.
.. versionadded:: 2016.3.0
rootfs
rootfs of the container.
.. versionadded:: 2016.3.0
cpu
Select a random number of cpu cores and assign it to the cpuset, if the
cpuset option is set then this option will be ignored
cpuset
Explicitly define the cpus this container will be bound to
cpushare
cgroups cpu shares.
autostart
autostart container on reboot
memory
cgroups memory limit, in MB.
(0 for nolimit, None for old default 1024MB)
gateway
the ipv4 gateway to use
the default does nothing more than lxcutils does
bridge
the bridge to use
the default does nothing more than lxcutils does
nic
Network interfaces profile (defined in config or pillar).
nic_opts
Extra options for network interfaces, will override
``{"eth0": {"mac": "aa:bb:cc:dd:ee:ff", "ipv4": "10.1.1.1", "ipv6": "2001:db8::ff00:42:8329"}}``
or
``{"eth0": {"mac": "aa:bb:cc:dd:ee:ff", "ipv4": "10.1.1.1/24", "ipv6": "2001:db8::ff00:42:8329"}}``
path
path to the container parent
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt-call -lall mc_lxc_fork.reconfigure foobar nic_opts="{'eth1': {'mac': '00:16:3e:dd:ee:44'}}" memory=4
'''
changes = {}
cpath = get_root_path(path)
path = os.path.join(cpath, name, 'config')
ret = {'name': name,
'comment': 'config for {0} up to date'.format(name),
'result': True,
'changes': changes}
profile = get_container_profile(copy.deepcopy(profile))
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, _marker)
profile_match = profile.pop(key, default)
# let kwarg overrides be the preferred choice
if kw_overrides_match is _marker:
return profile_match
return kw_overrides_match
if nic_opts is not None and not network_profile:
network_profile = DEFAULT_NIC
if autostart is not None:
autostart = select('autostart', autostart)
else:
autostart = 'keep'
if not utsname:
utsname = select('utsname', utsname)
if os.path.exists(path):
old_chunks = read_conf(path, out_format='commented')
make_kw = salt.utils.odict.OrderedDict([
('utsname', utsname),
('rootfs', rootfs),
('autostart', autostart),
('cpu', cpu),
('gateway', gateway),
('cpuset', cpuset),
('cpushare', cpushare),
('network_profile', network_profile),
('nic_opts', nic_opts),
('bridge', bridge)])
# match 0 and none as memory = 0 in lxc config is harmful
if memory:
make_kw['memory'] = memory
kw = salt.utils.odict.OrderedDict()
for key, val in six.iteritems(make_kw):
if val is not None:
kw[key] = val
new_cfg = _config_list(conf_tuples=old_chunks, **kw)
if new_cfg:
edit_conf(path, out_format='commented', lxc_config=new_cfg)
chunks = read_conf(path, out_format='commented')
if old_chunks != chunks:
ret['comment'] = '{0} lxc config updated'.format(name)
if state(name, path=path) == 'running':
cret = reboot(name, path=path)
ret['result'] = cret['result']
return ret
def apply_network_profile(name, network_profile, nic_opts=None, path=None):
'''
.. versionadded:: 2015.5.0
Apply a network profile to a container
network_profile
profile name or default values (dict)
nic_opts
values to override in defaults (dict)
indexed by nic card names
path
path to the container parent
.. versionadded:: 2015.8.0
CLI Examples:
.. code-block:: bash
salt 'minion' lxc.apply_network_profile web1 centos
salt 'minion' lxc.apply_network_profile web1 centos \\
nic_opts="{'eth0': {'mac': 'xx:xx:xx:xx:xx:xx'}}"
salt 'minion' lxc.apply_network_profile web1 \\
"{'eth0': {'mac': 'xx:xx:xx:xx:xx:yy'}}"
nic_opts="{'eth0': {'mac': 'xx:xx:xx:xx:xx:xx'}}"
The special case to disable use of ethernet nics:
.. code-block:: bash
salt 'minion' lxc.apply_network_profile web1 centos \\
"{eth0: {disable: true}}"
'''
cpath = get_root_path(path)
cfgpath = os.path.join(cpath, name, 'config')
before = []
with salt.utils.files.fopen(cfgpath, 'r') as fp_:
for line in fp_:
before.append(line)
lxcconfig = _LXCConfig(name=name, path=path)
old_net = lxcconfig._filter_data('lxc.network')
network_params = {}
for param in _network_conf(
conf_tuples=old_net,
network_profile=network_profile, nic_opts=nic_opts
):
network_params.update(param)
if network_params:
edit_conf(cfgpath, out_format='commented', **network_params)
after = []
with salt.utils.files.fopen(cfgpath, 'r') as fp_:
for line in fp_:
after.append(line)
diff = ''
for line in difflib.unified_diff(before,
after,
fromfile='before',
tofile='after'):
diff += line
return diff
def get_pid(name, path=None):
'''
Returns a container pid.
Throw an exception if the container isn't running.
CLI Example:
.. code-block:: bash
salt '*' lxc.get_pid name
'''
if name not in list_(limit='running', path=path):
raise CommandExecutionError('Container {0} is not running, can\'t determine PID'.format(name))
info = __salt__['cmd.run']('lxc-info -n {0}'.format(name)).split("\n")
pid = [line.split(':')[1].strip() for line in info if re.match(r'\s*PID', line)][0]
return pid
def add_veth(name, interface_name, bridge=None, path=None):
'''
Add a veth to a container.
Note : this function doesn't update the container config, just add the interface at runtime
name
Name of the container
interface_name
Name of the interface in the container
bridge
Name of the bridge to attach the interface to (facultative)
CLI Examples:
.. code-block:: bash
salt '*' lxc.add_veth container_name eth1 br1
salt '*' lxc.add_veth container_name eth1
'''
# Get container init PID
pid = get_pid(name, path=path)
# Generate a ramdom string for veth and ensure that is isn't present on the system
while True:
random_veth = 'veth'+''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(6))
if random_veth not in __salt__['network.interfaces']().keys():
break
# Check prerequisites
if not __salt__['file.directory_exists']('/var/run/'):
raise CommandExecutionError('Directory /var/run required for lxc.add_veth doesn\'t exists')
if not __salt__['file.file_exists']('/proc/{0}/ns/net'.format(pid)):
raise CommandExecutionError('Proc file for container {0} network namespace doesn\'t exists'.format(name))
if not __salt__['file.directory_exists']('/var/run/netns'):
__salt__['file.mkdir']('/var/run/netns')
# Ensure that the symlink is up to date (change on container restart)
if __salt__['file.is_link']('/var/run/netns/{0}'.format(name)):
__salt__['file.remove']('/var/run/netns/{0}'.format(name))
__salt__['file.symlink']('/proc/{0}/ns/net'.format(pid), '/var/run/netns/{0}'.format(name))
# Ensure that interface doesn't exists
interface_exists = 0 == __salt__['cmd.retcode']('ip netns exec {netns} ip address list {interface}'.format(
netns=name,
interface=interface_name
))
if interface_exists:
raise CommandExecutionError('Interface {interface} already exists in {container}'.format(
interface=interface_name,
container=name
))
# Create veth and bring it up
if __salt__['cmd.retcode']('ip link add name {veth} type veth peer name {veth}_c'.format(veth=random_veth)) != 0:
raise CommandExecutionError('Error while creating the veth pair {0}'.format(random_veth))
if __salt__['cmd.retcode']('ip link set dev {0} up'.format(random_veth)) != 0:
raise CommandExecutionError('Error while bringing up host-side veth {0}'.format(random_veth))
# Attach it to the container
attached = 0 == __salt__['cmd.retcode']('ip link set dev {veth}_c netns {container} name {interface_name}'.format(
veth=random_veth,
container=name,
interface_name=interface_name
))
if not attached:
raise CommandExecutionError('Error while attaching the veth {veth} to container {container}'.format(
veth=random_veth,
container=name
))
__salt__['file.remove']('/var/run/netns/{0}'.format(name))
if bridge is not None:
__salt__['bridge.addif'](bridge, random_veth)
|
saltstack/salt
|
salt/modules/lxc.py
|
cloud_init_interface
|
python
|
def cloud_init_interface(name, vm_=None, **kwargs):
'''
Interface between salt.cloud.lxc driver and lxc.init
``vm_`` is a mapping of vm opts in the salt.cloud format
as documented for the lxc driver.
This can be used either:
- from the salt cloud driver
- because you find the argument to give easier here
than using directly lxc.init
.. warning::
BE REALLY CAREFUL CHANGING DEFAULTS !!!
IT'S A RETRO COMPATIBLE INTERFACE WITH
THE SALT CLOUD DRIVER (ask kiorky).
name
name of the lxc container to create
pub_key
public key to preseed the minion with.
Can be the keycontent or a filepath
priv_key
private key to preseed the minion with.
Can be the keycontent or a filepath
path
path to the container parent directory (default: /var/lib/lxc)
.. versionadded:: 2015.8.0
profile
:ref:`profile <tutorial-lxc-profiles-container>` selection
network_profile
:ref:`network profile <tutorial-lxc-profiles-network>` selection
nic_opts
per interface settings compatibles with
network profile (ipv4/ipv6/link/gateway/mac/netmask)
eg::
- {'eth0': {'mac': '00:16:3e:01:29:40',
'gateway': None, (default)
'link': 'br0', (default)
'gateway': None, (default)
'netmask': '', (default)
'ip': '22.1.4.25'}}
unconditional_install
given to lxc.bootstrap (see relative doc)
force_install
given to lxc.bootstrap (see relative doc)
config
any extra argument for the salt minion config
dnsservers
list of DNS servers to set inside the container
dns_via_dhcp
do not set the dns servers, let them be set by the dhcp.
autostart
autostart the container at boot time
password
administrative password for the container
bootstrap_delay
delay before launching bootstrap script at Container init
.. warning::
Legacy but still supported options:
from_container
which container we use as a template
when running lxc.clone
image
which template do we use when we
are using lxc.create. This is the default
mode unless you specify something in from_container
backing
which backing store to use.
Values can be: overlayfs, dir(default), lvm, zfs, brtfs
fstype
When using a blockdevice level backing store,
which filesystem to use on
size
When using a blockdevice level backing store,
which size for the filesystem to use on
snapshot
Use snapshot when cloning the container source
vgname
if using LVM: vgname
lvname
if using LVM: lvname
thinpool:
if using LVM: thinpool
ip
ip for the primary nic
mac
mac address for the primary nic
netmask
netmask for the primary nic (24)
= ``vm_.get('netmask', '24')``
bridge
bridge for the primary nic (lxcbr0)
gateway
network gateway for the container
additional_ips
additional ips which will be wired on the main bridge (br0)
which is connected to internet.
Be aware that you may use manual virtual mac addresses
providen by you provider (online, ovh, etc).
This is a list of mappings {ip: '', mac: '', netmask:''}
Set gateway to None and an interface with a gateway
to escape from another interface that eth0.
eg::
- {'mac': '00:16:3e:01:29:40',
'gateway': None, (default)
'link': 'br0', (default)
'netmask': '', (default)
'ip': '22.1.4.25'}
users
administrative users for the container
default: [root] and [root, ubuntu] on ubuntu
default_nic
name of the first interface, you should
really not override this
CLI Example:
.. code-block:: bash
salt '*' lxc.cloud_init_interface foo
'''
if vm_ is None:
vm_ = {}
vm_ = copy.deepcopy(vm_)
vm_ = salt.utils.dictupdate.update(vm_, kwargs)
profile_data = copy.deepcopy(
vm_.get('lxc_profile',
vm_.get('profile', {})))
if not isinstance(profile_data, (dict, six.string_types)):
profile_data = {}
profile = get_container_profile(profile_data)
def _cloud_get(k, default=None):
return vm_.get(k, profile.get(k, default))
if name is None:
name = vm_['name']
# if we are on ubuntu, default to ubuntu
default_template = ''
if __grains__.get('os', '') in ['Ubuntu']:
default_template = 'ubuntu'
image = _cloud_get('image')
if not image:
_cloud_get('template', default_template)
backing = _cloud_get('backing', 'dir')
if image:
profile['template'] = image
vgname = _cloud_get('vgname', None)
if vgname:
profile['vgname'] = vgname
if backing:
profile['backing'] = backing
snapshot = _cloud_get('snapshot', False)
autostart = bool(_cloud_get('autostart', True))
dnsservers = _cloud_get('dnsservers', [])
dns_via_dhcp = _cloud_get('dns_via_dhcp', True)
password = _cloud_get('password', 's3cr3t')
password_encrypted = _cloud_get('password_encrypted', False)
fstype = _cloud_get('fstype', None)
lvname = _cloud_get('lvname', None)
thinpool = _cloud_get('thinpool', None)
pub_key = _cloud_get('pub_key', None)
priv_key = _cloud_get('priv_key', None)
size = _cloud_get('size', '20G')
script = _cloud_get('script', None)
script_args = _cloud_get('script_args', None)
users = _cloud_get('users', None)
if users is None:
users = []
ssh_username = _cloud_get('ssh_username', None)
if ssh_username and (ssh_username not in users):
users.append(ssh_username)
network_profile = _cloud_get('network_profile', None)
nic_opts = kwargs.get('nic_opts', None)
netmask = _cloud_get('netmask', '24')
path = _cloud_get('path', None)
bridge = _cloud_get('bridge', None)
gateway = _cloud_get('gateway', None)
unconditional_install = _cloud_get('unconditional_install', False)
force_install = _cloud_get('force_install', True)
config = _get_salt_config(_cloud_get('config', {}), **vm_)
default_nic = _cloud_get('default_nic', DEFAULT_NIC)
# do the interface with lxc.init mainly via nic_opts
# to avoid extra and confusing extra use cases.
if not isinstance(nic_opts, dict):
nic_opts = salt.utils.odict.OrderedDict()
# have a reference to the default nic
eth0 = nic_opts.setdefault(default_nic,
salt.utils.odict.OrderedDict())
# lxc config is based of ifc order, be sure to use odicts.
if not isinstance(nic_opts, salt.utils.odict.OrderedDict):
bnic_opts = salt.utils.odict.OrderedDict()
bnic_opts.update(nic_opts)
nic_opts = bnic_opts
gw = None
# legacy salt.cloud scheme for network interfaces settings support
bridge = _cloud_get('bridge', None)
ip = _cloud_get('ip', None)
mac = _cloud_get('mac', None)
if ip:
fullip = ip
if netmask:
fullip += '/{0}'.format(netmask)
eth0['ipv4'] = fullip
if mac is not None:
eth0['mac'] = mac
for ix, iopts in enumerate(_cloud_get("additional_ips", [])):
ifh = "eth{0}".format(ix+1)
ethx = nic_opts.setdefault(ifh, {})
if gw is None:
gw = iopts.get('gateway', ethx.get('gateway', None))
if gw:
# only one and only one default gateway is allowed !
eth0.pop('gateway', None)
gateway = None
# even if the gateway if on default "eth0" nic
# and we popped it will work
# as we reinject or set it here.
ethx['gateway'] = gw
elink = iopts.get('link', ethx.get('link', None))
if elink:
ethx['link'] = elink
# allow dhcp
aip = iopts.get('ipv4', iopts.get('ip', None))
if aip:
ethx['ipv4'] = aip
nm = iopts.get('netmask', '')
if nm:
ethx['ipv4'] += '/{0}'.format(nm)
for i in ('mac', 'hwaddr'):
if i in iopts:
ethx['mac'] = iopts[i]
break
if 'mac' not in ethx:
ethx['mac'] = salt.utils.network.gen_mac()
# last round checking for unique gateway and such
gw = None
for ethx in [a for a in nic_opts]:
ndata = nic_opts[ethx]
if gw:
ndata.pop('gateway', None)
if 'gateway' in ndata:
gw = ndata['gateway']
gateway = None
# only use a default bridge / gateway if we configured them
# via the legacy salt cloud configuration style.
# On other cases, we should rely on settings provided by the new
# salt lxc network profile style configuration which can
# be also be overridden or a per interface basis via the nic_opts dict.
if bridge:
eth0['link'] = bridge
if gateway:
eth0['gateway'] = gateway
#
lxc_init_interface = {}
lxc_init_interface['name'] = name
lxc_init_interface['config'] = config
lxc_init_interface['memory'] = _cloud_get('memory', 0) # nolimit
lxc_init_interface['pub_key'] = pub_key
lxc_init_interface['priv_key'] = priv_key
lxc_init_interface['nic_opts'] = nic_opts
for clone_from in ['clone_from', 'clone', 'from_container']:
# clone_from should default to None if not available
lxc_init_interface['clone_from'] = _cloud_get(clone_from, None)
if lxc_init_interface['clone_from'] is not None:
break
lxc_init_interface['profile'] = profile
lxc_init_interface['snapshot'] = snapshot
lxc_init_interface['dnsservers'] = dnsservers
lxc_init_interface['fstype'] = fstype
lxc_init_interface['path'] = path
lxc_init_interface['vgname'] = vgname
lxc_init_interface['size'] = size
lxc_init_interface['lvname'] = lvname
lxc_init_interface['thinpool'] = thinpool
lxc_init_interface['force_install'] = force_install
lxc_init_interface['unconditional_install'] = (
unconditional_install
)
lxc_init_interface['bootstrap_url'] = script
lxc_init_interface['bootstrap_args'] = script_args
lxc_init_interface['bootstrap_shell'] = _cloud_get('bootstrap_shell', 'sh')
lxc_init_interface['bootstrap_delay'] = _cloud_get('bootstrap_delay', None)
lxc_init_interface['autostart'] = autostart
lxc_init_interface['users'] = users
lxc_init_interface['password'] = password
lxc_init_interface['password_encrypted'] = password_encrypted
# be sure not to let objects goes inside the return
# as this return will be msgpacked for use in the runner !
lxc_init_interface['network_profile'] = network_profile
for i in ['cpu', 'cpuset', 'cpushare']:
if _cloud_get(i, None):
try:
lxc_init_interface[i] = vm_[i]
except KeyError:
lxc_init_interface[i] = profile[i]
return lxc_init_interface
|
Interface between salt.cloud.lxc driver and lxc.init
``vm_`` is a mapping of vm opts in the salt.cloud format
as documented for the lxc driver.
This can be used either:
- from the salt cloud driver
- because you find the argument to give easier here
than using directly lxc.init
.. warning::
BE REALLY CAREFUL CHANGING DEFAULTS !!!
IT'S A RETRO COMPATIBLE INTERFACE WITH
THE SALT CLOUD DRIVER (ask kiorky).
name
name of the lxc container to create
pub_key
public key to preseed the minion with.
Can be the keycontent or a filepath
priv_key
private key to preseed the minion with.
Can be the keycontent or a filepath
path
path to the container parent directory (default: /var/lib/lxc)
.. versionadded:: 2015.8.0
profile
:ref:`profile <tutorial-lxc-profiles-container>` selection
network_profile
:ref:`network profile <tutorial-lxc-profiles-network>` selection
nic_opts
per interface settings compatibles with
network profile (ipv4/ipv6/link/gateway/mac/netmask)
eg::
- {'eth0': {'mac': '00:16:3e:01:29:40',
'gateway': None, (default)
'link': 'br0', (default)
'gateway': None, (default)
'netmask': '', (default)
'ip': '22.1.4.25'}}
unconditional_install
given to lxc.bootstrap (see relative doc)
force_install
given to lxc.bootstrap (see relative doc)
config
any extra argument for the salt minion config
dnsservers
list of DNS servers to set inside the container
dns_via_dhcp
do not set the dns servers, let them be set by the dhcp.
autostart
autostart the container at boot time
password
administrative password for the container
bootstrap_delay
delay before launching bootstrap script at Container init
.. warning::
Legacy but still supported options:
from_container
which container we use as a template
when running lxc.clone
image
which template do we use when we
are using lxc.create. This is the default
mode unless you specify something in from_container
backing
which backing store to use.
Values can be: overlayfs, dir(default), lvm, zfs, brtfs
fstype
When using a blockdevice level backing store,
which filesystem to use on
size
When using a blockdevice level backing store,
which size for the filesystem to use on
snapshot
Use snapshot when cloning the container source
vgname
if using LVM: vgname
lvname
if using LVM: lvname
thinpool:
if using LVM: thinpool
ip
ip for the primary nic
mac
mac address for the primary nic
netmask
netmask for the primary nic (24)
= ``vm_.get('netmask', '24')``
bridge
bridge for the primary nic (lxcbr0)
gateway
network gateway for the container
additional_ips
additional ips which will be wired on the main bridge (br0)
which is connected to internet.
Be aware that you may use manual virtual mac addresses
providen by you provider (online, ovh, etc).
This is a list of mappings {ip: '', mac: '', netmask:''}
Set gateway to None and an interface with a gateway
to escape from another interface that eth0.
eg::
- {'mac': '00:16:3e:01:29:40',
'gateway': None, (default)
'link': 'br0', (default)
'netmask': '', (default)
'ip': '22.1.4.25'}
users
administrative users for the container
default: [root] and [root, ubuntu] on ubuntu
default_nic
name of the first interface, you should
really not override this
CLI Example:
.. code-block:: bash
salt '*' lxc.cloud_init_interface foo
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/lxc.py#L242-L551
|
[
"def update(dest, upd, recursive_update=True, merge_lists=False):\n '''\n Recursive version of the default dict.update\n\n Merges upd recursively into dest\n\n If recursive_update=False, will use the classic dict.update, or fall back\n on a manual merge (helpful for non-dict types like FunctionWrapper)\n\n If merge_lists=True, will aggregate list object types instead of replace.\n The list in ``upd`` is added to the list in ``dest``, so the resulting list\n is ``dest[key] + upd[key]``. This behavior is only activated when\n recursive_update=True. By default merge_lists=False.\n\n .. versionchanged: 2016.11.6\n When merging lists, duplicate values are removed. Values already\n present in the ``dest`` list are not added from the ``upd`` list.\n '''\n if (not isinstance(dest, Mapping)) \\\n or (not isinstance(upd, Mapping)):\n raise TypeError('Cannot update using non-dict types in dictupdate.update()')\n updkeys = list(upd.keys())\n if not set(list(dest.keys())) & set(updkeys):\n recursive_update = False\n if recursive_update:\n for key in updkeys:\n val = upd[key]\n try:\n dest_subkey = dest.get(key, None)\n except AttributeError:\n dest_subkey = None\n if isinstance(dest_subkey, Mapping) \\\n and isinstance(val, Mapping):\n ret = update(dest_subkey, val, merge_lists=merge_lists)\n dest[key] = ret\n elif isinstance(dest_subkey, list) and isinstance(val, list):\n if merge_lists:\n merged = copy.deepcopy(dest_subkey)\n merged.extend([x for x in val if x not in merged])\n dest[key] = merged\n else:\n dest[key] = upd[key]\n else:\n dest[key] = upd[key]\n return dest\n try:\n for k in upd:\n dest[k] = upd[k]\n except AttributeError:\n # this mapping is not a dict\n for k in upd:\n dest[k] = upd[k]\n return dest\n",
"def _get_salt_config(config, **kwargs):\n if not config:\n config = kwargs.get('minion', {})\n if not config:\n config = {}\n config.setdefault('master',\n kwargs.get('master',\n __opts__.get('master',\n __opts__['id'])))\n config.setdefault(\n 'master_port',\n kwargs.get('master_port',\n __opts__.get('master_port',\n __opts__.get('ret_port',\n __opts__.get('4506')))))\n if not config['master']:\n config = {}\n return config\n",
"def get_container_profile(name=None, **kwargs):\n '''\n .. versionadded:: 2015.5.0\n\n Gather a pre-configured set of container configuration parameters. If no\n arguments are passed, an empty profile is returned.\n\n Profiles can be defined in the minion or master config files, or in pillar\n or grains, and are loaded using :mod:`config.get\n <salt.modules.config.get>`. The key under which LXC profiles must be\n configured is ``lxc.container_profile.profile_name``. An example container\n profile would be as follows:\n\n .. code-block:: yaml\n\n lxc.container_profile:\n ubuntu:\n template: ubuntu\n backing: lvm\n vgname: lxc\n size: 1G\n\n Parameters set in a profile can be overridden by passing additional\n container creation arguments (such as the ones passed to :mod:`lxc.create\n <salt.modules.lxc.create>`) to this function.\n\n A profile can be defined either as the name of the profile, or a dictionary\n of variable names and values. See the :ref:`LXC Tutorial\n <tutorial-lxc-profiles>` for more information on how to use LXC profiles.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt-call lxc.get_container_profile centos\n salt-call lxc.get_container_profile ubuntu template=ubuntu backing=overlayfs\n '''\n profile = _get_profile('container_profile', name, **kwargs)\n return profile\n",
"def _cloud_get(k, default=None):\n return vm_.get(k, profile.get(k, default))\n",
"def setdefault(self, key, default=None):\n 'od.setdefault(k[,d]) -> od.get(k,d), also set od[k]=d if k not in od'\n if key in self:\n return self[key]\n self[key] = default\n return default\n"
] |
# -*- coding: utf-8 -*-
'''
Control Linux Containers via Salt
:depends: lxc package for distribution
lxc >= 1.0 (even beta alpha) is required
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import datetime
import copy
import string
import textwrap
import difflib
import logging
import tempfile
import os
import pipes
import time
import shutil
import re
import random
# Import salt libs
import salt.utils.args
import salt.utils.cloud
import salt.utils.data
import salt.utils.dictupdate
import salt.utils.files
import salt.utils.functools
import salt.utils.hashutils
import salt.utils.network
import salt.utils.odict
import salt.utils.path
import salt.utils.stringutils
from salt.exceptions import CommandExecutionError, SaltInvocationError
import salt.config
from salt.utils.versions import LooseVersion as _LooseVersion
# Import 3rd-party libs
from salt.ext import six
# pylint: disable=import-error,no-name-in-module
from salt.ext.six.moves import range # pylint: disable=redefined-builtin
from salt.ext.six.moves.urllib.parse import urlparse as _urlparse
# pylint: enable=import-error,no-name-in-module
# Set up logging
log = logging.getLogger(__name__)
# Don't shadow built-in's.
__func_alias__ = {
'list_': 'list',
'ls_': 'ls'
}
__virtualname__ = 'lxc'
DEFAULT_NIC = 'eth0'
DEFAULT_BR = 'br0'
SEED_MARKER = '/lxc.initial_seed'
EXEC_DRIVER = 'lxc-attach'
DEFAULT_PATH = '/var/lib/lxc'
_marker = object()
def __virtual__():
if salt.utils.path.which('lxc-start'):
return __virtualname__
# To speed up the whole thing, we decided to not use the
# subshell way and assume things are in place for lxc
# Discussion made by @kiorky and @thatch45
# lxc-version presence is not sufficient, in lxc1.0 alpha
# (precise backports), we have it and it is sufficient
# for the module to execute.
# elif salt.utils.path.which('lxc-version'):
# passed = False
# try:
# passed = subprocess.check_output(
# 'lxc-version').split(':')[1].strip() >= '1.0'
# except Exception:
# pass
# if not passed:
# log.warning('Support for lxc < 1.0 may be incomplete.')
# return 'lxc'
# return False
#
return (False, 'The lxc execution module cannot be loaded: the lxc-start binary is not in the path.')
def get_root_path(path):
'''
Get the configured lxc root for containers
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.get_root_path
'''
if not path:
path = __opts__.get('lxc.root_path', DEFAULT_PATH)
return path
def version():
'''
Return the actual lxc client version
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.version
'''
k = 'lxc.version'
if not __context__.get(k, None):
cversion = __salt__['cmd.run_all']('lxc-info --version')
if not cversion['retcode']:
ver = _LooseVersion(cversion['stdout'])
if ver < _LooseVersion('1.0'):
raise CommandExecutionError('LXC should be at least 1.0')
__context__[k] = "{0}".format(ver)
return __context__.get(k, None)
def _clear_context():
'''
Clear any lxc variables set in __context__
'''
for var in [x for x in __context__ if x.startswith('lxc.')]:
log.trace('Clearing __context__[\'%s\']', var)
__context__.pop(var, None)
def _ip_sort(ip):
'''Ip sorting'''
idx = '001'
if ip == '127.0.0.1':
idx = '200'
if ip == '::1':
idx = '201'
elif '::' in ip:
idx = '100'
return '{0}___{1}'.format(idx, ip)
def search_lxc_bridges():
'''
Search which bridges are potentially available as LXC bridges
CLI Example:
.. code-block:: bash
salt '*' lxc.search_lxc_bridges
'''
bridges = __context__.get('lxc.bridges', None)
# either match not yet called or no bridges were found
# to handle the case where lxc was not installed on the first
# call
if not bridges:
bridges = set()
running_bridges = set()
bridges.add(DEFAULT_BR)
try:
output = __salt__['cmd.run_all']('brctl show')
for line in output['stdout'].splitlines()[1:]:
if not line.startswith(' '):
running_bridges.add(line.split()[0].strip())
except (SaltInvocationError, CommandExecutionError):
pass
for ifc, ip in six.iteritems(
__grains__.get('ip_interfaces', {})
):
if ifc in running_bridges:
bridges.add(ifc)
elif os.path.exists(
'/sys/devices/virtual/net/{0}/bridge'.format(ifc)
):
bridges.add(ifc)
bridges = list(bridges)
# if we found interfaces that have lxc in their names
# we filter them as being the potential lxc bridges
# we also try to default on br0 on other cases
def sort_bridges(a):
pref = 'z'
if 'lxc' in a:
pref = 'a'
elif 'br0' == a:
pref = 'c'
return '{0}_{1}'.format(pref, a)
bridges.sort(key=sort_bridges)
__context__['lxc.bridges'] = bridges
return bridges
def search_lxc_bridge():
'''
Search the first bridge which is potentially available as LXC bridge
CLI Example:
.. code-block:: bash
salt '*' lxc.search_lxc_bridge
'''
return search_lxc_bridges()[0]
def _get_salt_config(config, **kwargs):
if not config:
config = kwargs.get('minion', {})
if not config:
config = {}
config.setdefault('master',
kwargs.get('master',
__opts__.get('master',
__opts__['id'])))
config.setdefault(
'master_port',
kwargs.get('master_port',
__opts__.get('master_port',
__opts__.get('ret_port',
__opts__.get('4506')))))
if not config['master']:
config = {}
return config
def _get_profile(key, name, **kwargs):
if isinstance(name, dict):
profilename = name.pop('name', None)
return _get_profile(key, profilename, **name)
if name is None:
profile_match = {}
else:
profile_match = \
__salt__['config.get'](
'lxc.{1}:{0}'.format(name, key),
default=None,
merge='recurse'
)
if profile_match is None:
# No matching profile, make the profile an empty dict so that
# overrides can be applied below.
profile_match = {}
if not isinstance(profile_match, dict):
raise CommandExecutionError('lxc.{0} must be a dictionary'.format(key))
# Overlay the kwargs to override matched profile data
overrides = salt.utils.args.clean_kwargs(**copy.deepcopy(kwargs))
profile_match = salt.utils.dictupdate.update(
copy.deepcopy(profile_match),
overrides
)
return profile_match
def get_container_profile(name=None, **kwargs):
'''
.. versionadded:: 2015.5.0
Gather a pre-configured set of container configuration parameters. If no
arguments are passed, an empty profile is returned.
Profiles can be defined in the minion or master config files, or in pillar
or grains, and are loaded using :mod:`config.get
<salt.modules.config.get>`. The key under which LXC profiles must be
configured is ``lxc.container_profile.profile_name``. An example container
profile would be as follows:
.. code-block:: yaml
lxc.container_profile:
ubuntu:
template: ubuntu
backing: lvm
vgname: lxc
size: 1G
Parameters set in a profile can be overridden by passing additional
container creation arguments (such as the ones passed to :mod:`lxc.create
<salt.modules.lxc.create>`) to this function.
A profile can be defined either as the name of the profile, or a dictionary
of variable names and values. See the :ref:`LXC Tutorial
<tutorial-lxc-profiles>` for more information on how to use LXC profiles.
CLI Example:
.. code-block:: bash
salt-call lxc.get_container_profile centos
salt-call lxc.get_container_profile ubuntu template=ubuntu backing=overlayfs
'''
profile = _get_profile('container_profile', name, **kwargs)
return profile
def get_network_profile(name=None, **kwargs):
'''
.. versionadded:: 2015.5.0
Gather a pre-configured set of network configuration parameters. If no
arguments are passed, the following default profile is returned:
.. code-block:: python
{'eth0': {'link': 'br0', 'type': 'veth', 'flags': 'up'}}
Profiles can be defined in the minion or master config files, or in pillar
or grains, and are loaded using :mod:`config.get
<salt.modules.config.get>`. The key under which LXC profiles must be
configured is ``lxc.network_profile``. An example network profile would be
as follows:
.. code-block:: yaml
lxc.network_profile.centos:
eth0:
link: br0
type: veth
flags: up
To disable networking entirely:
.. code-block:: yaml
lxc.network_profile.centos:
eth0:
disable: true
Parameters set in a profile can be overridden by passing additional
arguments to this function.
A profile can be passed either as the name of the profile, or a
dictionary of variable names and values. See the :ref:`LXC Tutorial
<tutorial-lxc-profiles>` for more information on how to use network
profiles.
.. warning::
The ``ipv4``, ``ipv6``, ``gateway``, and ``link`` (bridge) settings in
network profiles will only work if the container doesn't redefine the
network configuration (for example in
``/etc/sysconfig/network-scripts/ifcfg-<interface_name>`` on
RHEL/CentOS, or ``/etc/network/interfaces`` on Debian/Ubuntu/etc.)
CLI Example:
.. code-block:: bash
salt-call lxc.get_network_profile default
'''
profile = _get_profile('network_profile', name, **kwargs)
return profile
def _rand_cpu_str(cpu):
'''
Return a random subset of cpus for the cpuset config
'''
cpu = int(cpu)
avail = __salt__['status.nproc']()
if cpu < avail:
return '0-{0}'.format(avail)
to_set = set()
while len(to_set) < cpu:
choice = random.randint(0, avail - 1)
if choice not in to_set:
to_set.add(six.text_type(choice))
return ','.join(sorted(to_set))
def _network_conf(conf_tuples=None, **kwargs):
'''
Network configuration defaults
network_profile
as for containers, we can either call this function
either with a network_profile dict or network profile name
in the kwargs
nic_opts
overrides or extra nics in the form {nic_name: {set: tings}
'''
nic = kwargs.get('network_profile', None)
ret = []
nic_opts = kwargs.get('nic_opts', {})
if nic_opts is None:
# coming from elsewhere
nic_opts = {}
if not conf_tuples:
conf_tuples = []
old = _get_veths(conf_tuples)
if not old:
old = {}
# if we have a profile name, get the profile and load the network settings
# this will obviously by default look for a profile called "eth0"
# or by what is defined in nic_opts
# and complete each nic settings by sane defaults
if nic and isinstance(nic, (six.string_types, dict)):
nicp = get_network_profile(nic)
else:
nicp = {}
if DEFAULT_NIC not in nicp:
nicp[DEFAULT_NIC] = {}
kwargs = copy.deepcopy(kwargs)
gateway = kwargs.pop('gateway', None)
bridge = kwargs.get('bridge', None)
if nic_opts:
for dev, args in six.iteritems(nic_opts):
ethx = nicp.setdefault(dev, {})
try:
ethx = salt.utils.dictupdate.update(ethx, args)
except AttributeError:
raise SaltInvocationError('Invalid nic_opts configuration')
ifs = [a for a in nicp]
ifs += [a for a in old if a not in nicp]
ifs.sort()
gateway_set = False
for dev in ifs:
args = nicp.get(dev, {})
opts = nic_opts.get(dev, {}) if nic_opts else {}
old_if = old.get(dev, {})
disable = opts.get('disable', args.get('disable', False))
if disable:
continue
mac = opts.get('mac',
opts.get('hwaddr',
args.get('mac',
args.get('hwaddr', ''))))
type_ = opts.get('type', args.get('type', ''))
flags = opts.get('flags', args.get('flags', ''))
link = opts.get('link', args.get('link', ''))
ipv4 = opts.get('ipv4', args.get('ipv4', ''))
ipv6 = opts.get('ipv6', args.get('ipv6', ''))
infos = salt.utils.odict.OrderedDict([
('lxc.network.type', {
'test': not type_,
'value': type_,
'old': old_if.get('lxc.network.type'),
'default': 'veth'}),
('lxc.network.name', {
'test': False,
'value': dev,
'old': dev,
'default': dev}),
('lxc.network.flags', {
'test': not flags,
'value': flags,
'old': old_if.get('lxc.network.flags'),
'default': 'up'}),
('lxc.network.link', {
'test': not link,
'value': link,
'old': old_if.get('lxc.network.link'),
'default': search_lxc_bridge()}),
('lxc.network.hwaddr', {
'test': not mac,
'value': mac,
'old': old_if.get('lxc.network.hwaddr'),
'default': salt.utils.network.gen_mac()}),
('lxc.network.ipv4', {
'test': not ipv4,
'value': ipv4,
'old': old_if.get('lxc.network.ipv4', ''),
'default': None}),
('lxc.network.ipv6', {
'test': not ipv6,
'value': ipv6,
'old': old_if.get('lxc.network.ipv6', ''),
'default': None})])
# for each parameter, if not explicitly set, the
# config value present in the LXC configuration should
# take precedence over the profile configuration
for info in list(infos.keys()):
bundle = infos[info]
if bundle['test']:
if bundle['old']:
bundle['value'] = bundle['old']
elif bundle['default']:
bundle['value'] = bundle['default']
for info, data in six.iteritems(infos):
if data['value']:
ret.append({info: data['value']})
for key, val in six.iteritems(args):
if key == 'link' and bridge:
val = bridge
val = opts.get(key, val)
if key in [
'type', 'flags', 'name',
'gateway', 'mac', 'link', 'ipv4', 'ipv6'
]:
continue
ret.append({'lxc.network.{0}'.format(key): val})
# gateway (in automode) must be appended following network conf !
if not gateway:
gateway = args.get('gateway', None)
if gateway is not None and not gateway_set:
ret.append({'lxc.network.ipv4.gateway': gateway})
# only one network gateway ;)
gateway_set = True
# normally, this won't happen
# set the gateway if specified even if we did
# not managed the network underlying
if gateway is not None and not gateway_set:
ret.append({'lxc.network.ipv4.gateway': gateway})
# only one network gateway ;)
gateway_set = True
new = _get_veths(ret)
# verify that we did not loose the mac settings
for iface in [a for a in new]:
ndata = new[iface]
nmac = ndata.get('lxc.network.hwaddr', '')
ntype = ndata.get('lxc.network.type', '')
omac, otype = '', ''
if iface in old:
odata = old[iface]
omac = odata.get('lxc.network.hwaddr', '')
otype = odata.get('lxc.network.type', '')
# default for network type is setted here
# attention not to change the network type
# without a good and explicit reason to.
if otype and not ntype:
ntype = otype
if not ntype:
ntype = 'veth'
new[iface]['lxc.network.type'] = ntype
if omac and not nmac:
new[iface]['lxc.network.hwaddr'] = omac
ret = []
for val in six.itervalues(new):
for row in val:
ret.append(salt.utils.odict.OrderedDict([(row, val[row])]))
# on old versions of lxc, still support the gateway auto mode
# if we didn't explicitly say no to
# (lxc.network.ipv4.gateway: auto)
if _LooseVersion(version()) <= _LooseVersion('1.0.7') and \
True not in ['lxc.network.ipv4.gateway' in a for a in ret] and \
True in ['lxc.network.ipv4' in a for a in ret]:
ret.append({'lxc.network.ipv4.gateway': 'auto'})
return ret
def _get_lxc_default_data(**kwargs):
kwargs = copy.deepcopy(kwargs)
ret = {}
for k in ['utsname', 'rootfs']:
val = kwargs.get(k, None)
if val is not None:
ret['lxc.{0}'.format(k)] = val
autostart = kwargs.get('autostart')
# autostart can have made in kwargs, but with the None
# value which is invalid, we need an explicit boolean
# autostart = on is the default.
if autostart is None:
autostart = True
# we will set the regular lxc marker to restart container at
# machine (re)boot only if we did not explicitly ask
# not to touch to the autostart settings via
# autostart == 'keep'
if autostart != 'keep':
if autostart:
ret['lxc.start.auto'] = '1'
else:
ret['lxc.start.auto'] = '0'
memory = kwargs.get('memory')
if memory is not None:
# converting the config value from MB to bytes
ret['lxc.cgroup.memory.limit_in_bytes'] = memory * 1024 * 1024
cpuset = kwargs.get('cpuset')
if cpuset:
ret['lxc.cgroup.cpuset.cpus'] = cpuset
cpushare = kwargs.get('cpushare')
cpu = kwargs.get('cpu')
if cpushare:
ret['lxc.cgroup.cpu.shares'] = cpushare
if cpu and not cpuset:
ret['lxc.cgroup.cpuset.cpus'] = _rand_cpu_str(cpu)
return ret
def _config_list(conf_tuples=None, only_net=False, **kwargs):
'''
Return a list of dicts from the salt level configurations
conf_tuples
_LXCConfig compatible list of entries which can contain
- string line
- tuple (lxc config param,value)
- dict of one entry: {lxc config param: value)
only_net
by default we add to the tuples a reflection of both
the real config if avalaible and a certain amount of
default values like the cpu parameters, the memory
and etc.
On the other hand, we also no matter the case reflect
the network configuration computed from the actual config if
available and given values.
if no_default_loads is set, we will only
reflect the network configuration back to the conf tuples
list
'''
# explicit cast
only_net = bool(only_net)
if not conf_tuples:
conf_tuples = []
kwargs = copy.deepcopy(kwargs)
ret = []
if not only_net:
default_data = _get_lxc_default_data(**kwargs)
for k, val in six.iteritems(default_data):
ret.append({k: val})
net_datas = _network_conf(conf_tuples=conf_tuples, **kwargs)
ret.extend(net_datas)
return ret
def _get_veths(net_data):
'''
Parse the nic setup inside lxc conf tuples back to a dictionary indexed by
network interface
'''
if isinstance(net_data, dict):
net_data = list(net_data.items())
nics = salt.utils.odict.OrderedDict()
current_nic = salt.utils.odict.OrderedDict()
no_names = True
for item in net_data:
if item and isinstance(item, dict):
item = list(item.items())[0]
# skip LXC configuration comment lines, and play only with tuples conf
elif isinstance(item, six.string_types):
# deal with reflection of commented lxc configs
sitem = item.strip()
if sitem.startswith('#') or not sitem:
continue
elif '=' in item:
item = tuple([a.strip() for a in item.split('=', 1)])
if item[0] == 'lxc.network.type':
current_nic = salt.utils.odict.OrderedDict()
if item[0] == 'lxc.network.name':
no_names = False
nics[item[1].strip()] = current_nic
current_nic[item[0].strip()] = item[1].strip()
# if not ethernet card name has been collected, assuming we collected
# data for eth0
if no_names and current_nic:
nics[DEFAULT_NIC] = current_nic
return nics
class _LXCConfig(object):
'''
LXC configuration data
'''
pattern = re.compile(r'^(\S+)(\s*)(=)(\s*)(.*)')
non_interpretable_pattern = re.compile(r'^((#.*)|(\s*))$')
def __init__(self, **kwargs):
kwargs = copy.deepcopy(kwargs)
self.name = kwargs.pop('name', None)
path = get_root_path(kwargs.get('path', None))
self.data = []
if self.name:
self.path = os.path.join(path, self.name, 'config')
if os.path.isfile(self.path):
with salt.utils.files.fopen(self.path) as fhr:
for line in salt.utils.data.decode(fhr.readlines()):
match = self.pattern.findall((line.strip()))
if match:
self.data.append((match[0][0], match[0][-1]))
match = self.non_interpretable_pattern.findall(
(line.strip()))
if match:
self.data.append(('', match[0][0]))
else:
self.path = None
def _replace(key, val):
if val:
self._filter_data(key)
self.data.append((key, val))
default_data = _get_lxc_default_data(**kwargs)
for key, val in six.iteritems(default_data):
_replace(key, val)
old_net = self._filter_data('lxc.network')
net_datas = _network_conf(conf_tuples=old_net, **kwargs)
if net_datas:
for row in net_datas:
self.data.extend(list(row.items()))
# be sure to reset harmful settings
for idx in ['lxc.cgroup.memory.limit_in_bytes']:
if not default_data.get(idx):
self._filter_data(idx)
def as_string(self):
chunks = ('{0[0]}{1}{0[1]}'.format(item, (' = ' if item[0] else '')) for item in self.data)
return '\n'.join(chunks) + '\n'
def write(self):
if self.path:
content = self.as_string()
# 2 step rendering to be sure not to open/wipe the config
# before as_string succeeds.
with salt.utils.files.fopen(self.path, 'w') as fic:
fic.write(salt.utils.stringutils.to_str(content))
fic.flush()
def tempfile(self):
# this might look like the function name is shadowing the
# module, but it's not since the method belongs to the class
ntf = tempfile.NamedTemporaryFile()
ntf.write(self.as_string())
ntf.flush()
return ntf
def _filter_data(self, pattern):
'''
Removes parameters which match the pattern from the config data
'''
removed = []
filtered = []
for param in self.data:
if not param[0].startswith(pattern):
filtered.append(param)
else:
removed.append(param)
self.data = filtered
return removed
def _get_base(**kwargs):
'''
If the needed base does not exist, then create it, if it does exist
create nothing and return the name of the base lxc container so
it can be cloned.
'''
profile = get_container_profile(copy.deepcopy(kwargs.get('profile')))
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, _marker)
profile_match = profile.pop(key, default)
# let kwarg overrides be the preferred choice
if kw_overrides_match is _marker:
return profile_match
return kw_overrides_match
template = select('template')
image = select('image')
vgname = select('vgname')
path = kwargs.get('path', None)
# remove the above three variables from kwargs, if they exist, to avoid
# duplicates if create() is invoked below.
for param in ('path', 'image', 'vgname', 'template'):
kwargs.pop(param, None)
if image:
proto = _urlparse(image).scheme
img_tar = __salt__['cp.cache_file'](image)
img_name = os.path.basename(img_tar)
hash_ = salt.utils.hashutils.get_hash(
img_tar,
__salt__['config.get']('hash_type'))
name = '__base_{0}_{1}_{2}'.format(proto, img_name, hash_)
if not exists(name, path=path):
create(name, template=template, image=image,
path=path, vgname=vgname, **kwargs)
if vgname:
rootfs = os.path.join('/dev', vgname, name)
edit_conf(info(name, path=path)['config'],
out_format='commented', **{'lxc.rootfs': rootfs})
return name
elif template:
name = '__base_{0}'.format(template)
if not exists(name, path=path):
create(name, template=template, image=image, path=path,
vgname=vgname, **kwargs)
if vgname:
rootfs = os.path.join('/dev', vgname, name)
edit_conf(info(name, path=path)['config'],
out_format='commented', **{'lxc.rootfs': rootfs})
return name
return ''
def init(name,
config=None,
cpuset=None,
cpushare=None,
memory=None,
profile=None,
network_profile=None,
nic_opts=None,
cpu=None,
autostart=True,
password=None,
password_encrypted=None,
users=None,
dnsservers=None,
searchdomains=None,
bridge=None,
gateway=None,
pub_key=None,
priv_key=None,
force_install=False,
unconditional_install=False,
bootstrap_delay=None,
bootstrap_args=None,
bootstrap_shell=None,
bootstrap_url=None,
**kwargs):
'''
Initialize a new container.
This is a partial idempotent function as if it is already provisioned, we
will reset a bit the lxc configuration file but much of the hard work will
be escaped as markers will prevent re-execution of harmful tasks.
name
Name of the container
image
A tar archive to use as the rootfs for the container. Conflicts with
the ``template`` argument.
cpus
Select a random number of cpu cores and assign it to the cpuset, if the
cpuset option is set then this option will be ignored
cpuset
Explicitly define the cpus this container will be bound to
cpushare
cgroups cpu shares
autostart
autostart container on reboot
memory
cgroups memory limit, in MB
.. versionchanged:: 2015.5.0
If no value is passed, no limit is set. In earlier Salt versions,
not passing this value causes a 1024MB memory limit to be set, and
it was necessary to pass ``memory=0`` to set no limit.
gateway
the ipv4 gateway to use
the default does nothing more than lxcutils does
bridge
the bridge to use
the default does nothing more than lxcutils does
network_profile
Network profile to use for the container
.. versionadded:: 2015.5.0
nic_opts
Extra options for network interfaces, will override
``{"eth0": {"hwaddr": "aa:bb:cc:dd:ee:ff", "ipv4": "10.1.1.1", "ipv6": "2001:db8::ff00:42:8329"}}``
or
``{"eth0": {"hwaddr": "aa:bb:cc:dd:ee:ff", "ipv4": "10.1.1.1/24", "ipv6": "2001:db8::ff00:42:8329"}}``
users
Users for which the password defined in the ``password`` param should
be set. Can be passed as a comma separated list or a python list.
Defaults to just the ``root`` user.
password
Set the initial password for the users defined in the ``users``
parameter
password_encrypted : False
Set to ``True`` to denote a password hash instead of a plaintext
password
.. versionadded:: 2015.5.0
profile
A LXC profile (defined in config or pillar).
This can be either a real profile mapping or a string
to retrieve it in configuration
start
Start the newly-created container
dnsservers
list of dns servers to set in the container, default [] (no setting)
seed
Seed the container with the minion config. Default: ``True``
install
If salt-minion is not already installed, install it. Default: ``True``
config
Optional config parameters. By default, the id is set to
the name of the container.
master
salt master (default to minion's master)
master_port
salt master port (default to minion's master port)
pub_key
Explicit public key to preseed the minion with (optional).
This can be either a filepath or a string representing the key
priv_key
Explicit private key to preseed the minion with (optional).
This can be either a filepath or a string representing the key
approve_key
If explicit preseeding is not used;
Attempt to request key approval from the master. Default: ``True``
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
clone_from
Original from which to use a clone operation to create the container.
Default: ``None``
bootstrap_delay
Delay in seconds between end of container creation and bootstrapping.
Useful when waiting for container to obtain a DHCP lease.
.. versionadded:: 2015.5.0
bootstrap_url
See lxc.bootstrap
bootstrap_shell
See lxc.bootstrap
bootstrap_args
See lxc.bootstrap
force_install
Force installation even if salt-minion is detected,
this is the way to run vendor bootstrap scripts even
if a salt minion is already present in the container
unconditional_install
Run the script even if the container seems seeded
CLI Example:
.. code-block:: bash
salt 'minion' lxc.init name [cpuset=cgroups_cpuset] \\
[cpushare=cgroups_cpushare] [memory=cgroups_memory] \\
[nic=nic_profile] [profile=lxc_profile] \\
[nic_opts=nic_opts] [start=(True|False)] \\
[seed=(True|False)] [install=(True|False)] \\
[config=minion_config] [approve_key=(True|False) \\
[clone_from=original] [autostart=True] \\
[priv_key=/path_or_content] [pub_key=/path_or_content] \\
[bridge=lxcbr0] [gateway=10.0.3.1] \\
[dnsservers[dns1,dns2]] \\
[users=[foo]] [password='secret'] \\
[password_encrypted=(True|False)]
'''
ret = {'name': name,
'changes': {}}
profile = get_container_profile(copy.deepcopy(profile))
if not network_profile:
network_profile = profile.get('network_profile')
if not network_profile:
network_profile = DEFAULT_NIC
# Changes is a pointer to changes_dict['init']. This method is used so that
# we can have a list of changes as they are made, providing an ordered list
# of things that were changed.
changes_dict = {'init': []}
changes = changes_dict.get('init')
if users is None:
users = []
dusers = ['root']
for user in dusers:
if user not in users:
users.append(user)
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, _marker)
profile_match = profile.pop(key, default)
# let kwarg overrides be the preferred choice
if kw_overrides_match is _marker:
return profile_match
return kw_overrides_match
path = select('path')
bpath = get_root_path(path)
state_pre = state(name, path=path)
tvg = select('vgname')
vgname = tvg if tvg else __salt__['config.get']('lxc.vgname')
start_ = select('start', True)
autostart = select('autostart', autostart)
seed = select('seed', True)
install = select('install', True)
seed_cmd = select('seed_cmd')
salt_config = _get_salt_config(config, **kwargs)
approve_key = select('approve_key', True)
clone_from = select('clone_from')
# If using a volume group then set up to make snapshot cow clones
if vgname and not clone_from:
try:
kwargs['vgname'] = vgname
clone_from = _get_base(profile=profile, **kwargs)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = exc.strerror
if changes:
ret['changes'] = changes_dict
return ret
if not kwargs.get('snapshot') is False:
kwargs['snapshot'] = True
does_exist = exists(name, path=path)
to_reboot = False
remove_seed_marker = False
if does_exist:
pass
elif clone_from:
remove_seed_marker = True
try:
clone(name, clone_from, profile=profile, **kwargs)
changes.append({'create': 'Container cloned'})
except (SaltInvocationError, CommandExecutionError) as exc:
if 'already exists' in exc.strerror:
changes.append({'create': 'Container already exists'})
else:
ret['result'] = False
ret['comment'] = exc.strerror
if changes:
ret['changes'] = changes_dict
return ret
cfg = _LXCConfig(name=name, network_profile=network_profile,
nic_opts=nic_opts, bridge=bridge, path=path,
gateway=gateway, autostart=autostart,
cpuset=cpuset, cpushare=cpushare, memory=memory)
old_chunks = read_conf(cfg.path, out_format='commented')
cfg.write()
chunks = read_conf(cfg.path, out_format='commented')
if old_chunks != chunks:
to_reboot = True
else:
remove_seed_marker = True
cfg = _LXCConfig(network_profile=network_profile,
nic_opts=nic_opts, cpuset=cpuset, path=path,
bridge=bridge, gateway=gateway,
autostart=autostart,
cpushare=cpushare, memory=memory)
with cfg.tempfile() as cfile:
try:
create(name, config=cfile.name, profile=profile, **kwargs)
changes.append({'create': 'Container created'})
except (SaltInvocationError, CommandExecutionError) as exc:
if 'already exists' in exc.strerror:
changes.append({'create': 'Container already exists'})
else:
ret['comment'] = exc.strerror
if changes:
ret['changes'] = changes_dict
return ret
cpath = os.path.join(bpath, name, 'config')
old_chunks = []
if os.path.exists(cpath):
old_chunks = read_conf(cpath, out_format='commented')
new_cfg = _config_list(conf_tuples=old_chunks,
cpu=cpu,
network_profile=network_profile,
nic_opts=nic_opts, bridge=bridge,
cpuset=cpuset, cpushare=cpushare,
memory=memory)
if new_cfg:
edit_conf(cpath, out_format='commented', lxc_config=new_cfg)
chunks = read_conf(cpath, out_format='commented')
if old_chunks != chunks:
to_reboot = True
# last time to be sure any of our property is correctly applied
cfg = _LXCConfig(name=name, network_profile=network_profile,
nic_opts=nic_opts, bridge=bridge, path=path,
gateway=gateway, autostart=autostart,
cpuset=cpuset, cpushare=cpushare, memory=memory)
old_chunks = []
if os.path.exists(cfg.path):
old_chunks = read_conf(cfg.path, out_format='commented')
cfg.write()
chunks = read_conf(cfg.path, out_format='commented')
if old_chunks != chunks:
changes.append({'config': 'Container configuration updated'})
to_reboot = True
if to_reboot:
try:
stop(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
if changes:
ret['changes'] = changes_dict
return ret
if not does_exist or (does_exist and state(name, path=path) != 'running'):
try:
start(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
if changes:
ret['changes'] = changes_dict
return ret
if remove_seed_marker:
run(name,
'rm -f \'{0}\''.format(SEED_MARKER),
path=path,
chroot_fallback=False,
python_shell=False)
# set the default user/password, only the first time
if ret.get('result', True) and password:
gid = '/.lxc.initial_pass'
gids = [gid,
'/lxc.initial_pass',
'/.lxc.{0}.initial_pass'.format(name)]
if not any(retcode(name,
'test -e "{0}"'.format(x),
chroot_fallback=True,
path=path,
ignore_retcode=True) == 0
for x in gids):
# think to touch the default user generated by default templates
# which has a really unsecure passwords...
# root is defined as a member earlier in the code
for default_user in ['ubuntu']:
if (
default_user not in users and
retcode(name,
'id {0}'.format(default_user),
python_shell=False,
path=path,
chroot_fallback=True,
ignore_retcode=True) == 0
):
users.append(default_user)
for user in users:
try:
cret = set_password(name,
users=[user],
path=path,
password=password,
encrypted=password_encrypted)
except (SaltInvocationError, CommandExecutionError) as exc:
msg = '{0}: Failed to set password'.format(
user) + exc.strerror
# only hardfail in unrecoverable situation:
# root cannot be setted up
if user == 'root':
ret['comment'] = msg
ret['result'] = False
else:
log.debug(msg)
if ret.get('result', True):
changes.append({'password': 'Password(s) updated'})
if retcode(name,
('sh -c \'touch "{0}"; test -e "{0}"\''
.format(gid)),
path=path,
chroot_fallback=True,
ignore_retcode=True) != 0:
ret['comment'] = 'Failed to set password marker'
changes[-1]['password'] += '. ' + ret['comment'] + '.'
ret['result'] = False
# set dns servers if any, only the first time
if ret.get('result', True) and dnsservers:
# retro compatibility, test also old markers
gid = '/.lxc.initial_dns'
gids = [gid,
'/lxc.initial_dns',
'/lxc.{0}.initial_dns'.format(name)]
if not any(retcode(name,
'test -e "{0}"'.format(x),
chroot_fallback=True,
path=path,
ignore_retcode=True) == 0
for x in gids):
try:
set_dns(name,
path=path,
dnsservers=dnsservers,
searchdomains=searchdomains)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Failed to set DNS: ' + exc.strerror
ret['result'] = False
else:
changes.append({'dns': 'DNS updated'})
if retcode(name,
('sh -c \'touch "{0}"; test -e "{0}"\''
.format(gid)),
chroot_fallback=True,
path=path,
ignore_retcode=True) != 0:
ret['comment'] = 'Failed to set DNS marker'
changes[-1]['dns'] += '. ' + ret['comment'] + '.'
ret['result'] = False
# retro compatibility, test also old markers
if remove_seed_marker:
run(name,
'rm -f \'{0}\''.format(SEED_MARKER),
path=path,
python_shell=False)
gid = '/.lxc.initial_seed'
gids = [gid, '/lxc.initial_seed']
if (
any(retcode(name,
'test -e {0}'.format(x),
path=path,
chroot_fallback=True,
ignore_retcode=True) == 0
for x in gids) or not ret.get('result', True)
):
pass
elif seed or seed_cmd:
if seed:
try:
result = bootstrap(
name, config=salt_config, path=path,
approve_key=approve_key,
pub_key=pub_key, priv_key=priv_key,
install=install,
force_install=force_install,
unconditional_install=unconditional_install,
bootstrap_delay=bootstrap_delay,
bootstrap_url=bootstrap_url,
bootstrap_shell=bootstrap_shell,
bootstrap_args=bootstrap_args)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Bootstrap failed: ' + exc.strerror
ret['result'] = False
else:
if not result:
ret['comment'] = ('Bootstrap failed, see minion log for '
'more information')
ret['result'] = False
else:
changes.append(
{'bootstrap': 'Container successfully bootstrapped'}
)
elif seed_cmd:
try:
result = __salt__[seed_cmd](info(name, path=path)['rootfs'],
name,
salt_config)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = ('Bootstrap via seed_cmd \'{0}\' failed: {1}'
.format(seed_cmd, exc.strerror))
ret['result'] = False
else:
if not result:
ret['comment'] = ('Bootstrap via seed_cmd \'{0}\' failed, '
'see minion log for more information '
.format(seed_cmd))
ret['result'] = False
else:
changes.append(
{'bootstrap': 'Container successfully bootstrapped '
'using seed_cmd \'{0}\''
.format(seed_cmd)}
)
if ret.get('result', True) and not start_:
try:
stop(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
ret['result'] = False
state_post = state(name, path=path)
if state_pre != state_post:
changes.append({'state': {'old': state_pre, 'new': state_post}})
if ret.get('result', True):
ret['comment'] = ('Container \'{0}\' successfully initialized'
.format(name))
ret['result'] = True
if changes:
ret['changes'] = changes_dict
return ret
def cloud_init(name, vm_=None, **kwargs):
'''
Thin wrapper to lxc.init to be used from the saltcloud lxc driver
name
Name of the container
may be None and then guessed from saltcloud mapping
`vm_`
saltcloud mapping defaults for the vm
CLI Example:
.. code-block:: bash
salt '*' lxc.cloud_init foo
'''
init_interface = cloud_init_interface(name, vm_, **kwargs)
name = init_interface.pop('name', name)
return init(name, **init_interface)
def images(dist=None):
'''
.. versionadded:: 2015.5.0
List the available images for LXC's ``download`` template.
dist : None
Filter results to a single Linux distribution
CLI Examples:
.. code-block:: bash
salt myminion lxc.images
salt myminion lxc.images dist=centos
'''
out = __salt__['cmd.run_stdout'](
'lxc-create -n __imgcheck -t download -- --list',
ignore_retcode=True
)
if 'DIST' not in out:
raise CommandExecutionError(
'Unable to run the \'download\' template script. Is it installed?'
)
ret = {}
passed_header = False
for line in out.splitlines():
try:
distro, release, arch, variant, build_time = line.split()
except ValueError:
continue
if not passed_header:
if distro == 'DIST':
passed_header = True
continue
dist_list = ret.setdefault(distro, [])
dist_list.append({
'release': release,
'arch': arch,
'variant': variant,
'build_time': build_time,
})
if dist is not None:
return dict([(dist, ret.get(dist, []))])
return ret
def templates():
'''
.. versionadded:: 2015.5.0
List the available LXC template scripts installed on the minion
CLI Examples:
.. code-block:: bash
salt myminion lxc.templates
'''
try:
template_scripts = os.listdir('/usr/share/lxc/templates')
except OSError:
return []
else:
return [x[4:] for x in template_scripts if x.startswith('lxc-')]
def _after_ignition_network_profile(cmd,
ret,
name,
network_profile,
path,
nic_opts):
_clear_context()
if ret['retcode'] == 0 and exists(name, path=path):
if network_profile:
network_changes = apply_network_profile(name,
network_profile,
path=path,
nic_opts=nic_opts)
if network_changes:
log.info(
'Network changes from applying network profile \'%s\' '
'to newly-created container \'%s\':\n%s',
network_profile, name, network_changes
)
c_state = state(name, path=path)
return {'result': True,
'state': {'old': None, 'new': c_state}}
else:
if exists(name, path=path):
# destroy the container if it was partially created
cmd = 'lxc-destroy'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0}'.format(name)
__salt__['cmd.retcode'](cmd, python_shell=False)
raise CommandExecutionError(
'Container could not be created with cmd \'{0}\': {1}'
.format(cmd, ret['stderr'])
)
def create(name,
config=None,
profile=None,
network_profile=None,
nic_opts=None,
**kwargs):
'''
Create a new container.
name
Name of the container
config
The config file to use for the container. Defaults to system-wide
config (usually in /etc/lxc/lxc.conf).
profile
Profile to use in container creation (see
:mod:`lxc.get_container_profile
<salt.modules.lxc.get_container_profile>`). Values in a profile will be
overridden by the **Container Creation Arguments** listed below.
network_profile
Network profile to use for container
.. versionadded:: 2015.5.0
**Container Creation Arguments**
template
The template to use. For example, ``ubuntu`` or ``fedora``.
For a full list of available templates, check out
the :mod:`lxc.templates <salt.modules.lxc.templates>` function.
Conflicts with the ``image`` argument.
.. note::
The ``download`` template requires the following three parameters
to be defined in ``options``:
* **dist** - The name of the distribution
* **release** - Release name/version
* **arch** - Architecture of the container
The available images can be listed using the :mod:`lxc.images
<salt.modules.lxc.images>` function.
options
Template-specific options to pass to the lxc-create command. These
correspond to the long options (ones beginning with two dashes) that
the template script accepts. For example:
.. code-block:: bash
options='{"dist": "centos", "release": "6", "arch": "amd64"}'
For available template options, refer to the lxc template scripts
which are ususally located under ``/usr/share/lxc/templates``,
or run ``lxc-create -t <template> -h``.
image
A tar archive to use as the rootfs for the container. Conflicts with
the ``template`` argument.
backing
The type of storage to use. Set to ``lvm`` to use an LVM group.
Defaults to filesystem within /var/lib/lxc.
fstype
Filesystem type to use on LVM logical volume
size : 1G
Size of the volume to create. Only applicable if ``backing=lvm``.
vgname : lxc
Name of the LVM volume group in which to create the volume for this
container. Only applicable if ``backing=lvm``.
lvname
Name of the LVM logical volume in which to create the volume for this
container. Only applicable if ``backing=lvm``.
thinpool
Name of a pool volume that will be used for thin-provisioning this
container. Only applicable if ``backing=lvm``.
nic_opts
give extra opts overriding network profile values
path
parent path for the container creation (default: /var/lib/lxc)
zfsroot
Name of the ZFS root in which to create the volume for this container.
Only applicable if ``backing=zfs``. (default: tank/lxc)
.. versionadded:: 2015.8.0
'''
# Required params for 'download' template
download_template_deps = ('dist', 'release', 'arch')
cmd = 'lxc-create -n {0}'.format(name)
profile = get_container_profile(copy.deepcopy(profile))
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, None)
profile_match = profile.pop(key, default)
# Return the profile match if the the kwarg match was None, as the
# lxc.present state will pass these kwargs set to None by default.
if kw_overrides_match is None:
return profile_match
return kw_overrides_match
path = select('path')
if exists(name, path=path):
raise CommandExecutionError(
'Container \'{0}\' already exists'.format(name)
)
tvg = select('vgname')
vgname = tvg if tvg else __salt__['config.get']('lxc.vgname')
# The 'template' and 'image' params conflict
template = select('template')
image = select('image')
if template and image:
raise SaltInvocationError(
'Only one of \'template\' and \'image\' is permitted'
)
elif not any((template, image, profile)):
raise SaltInvocationError(
'At least one of \'template\', \'image\', and \'profile\' is '
'required'
)
options = select('options') or {}
backing = select('backing')
if vgname and not backing:
backing = 'lvm'
lvname = select('lvname')
thinpool = select('thinpool')
fstype = select('fstype')
size = select('size', '1G')
zfsroot = select('zfsroot')
if backing in ('dir', 'overlayfs', 'btrfs', 'zfs'):
fstype = None
size = None
# some backends won't support some parameters
if backing in ('aufs', 'dir', 'overlayfs', 'btrfs'):
lvname = vgname = thinpool = None
if image:
img_tar = __salt__['cp.cache_file'](image)
template = os.path.join(
os.path.dirname(salt.__file__),
'templates',
'lxc',
'salt_tarball')
options['imgtar'] = img_tar
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
if not os.path.exists(path):
os.makedirs(path)
if config:
cmd += ' -f {0}'.format(config)
if template:
cmd += ' -t {0}'.format(template)
if backing:
backing = backing.lower()
cmd += ' -B {0}'.format(backing)
if backing in ('zfs',):
if zfsroot:
cmd += ' --zfsroot {0}'.format(zfsroot)
if backing in ('lvm',):
if lvname:
cmd += ' --lvname {0}'.format(lvname)
if vgname:
cmd += ' --vgname {0}'.format(vgname)
if thinpool:
cmd += ' --thinpool {0}'.format(thinpool)
if backing not in ('dir', 'overlayfs'):
if fstype:
cmd += ' --fstype {0}'.format(fstype)
if size:
cmd += ' --fssize {0}'.format(size)
if options:
if template == 'download':
missing_deps = [x for x in download_template_deps
if x not in options]
if missing_deps:
raise SaltInvocationError(
'Missing params in \'options\' dict: {0}'
.format(', '.join(missing_deps))
)
cmd += ' --'
for key, val in six.iteritems(options):
cmd += ' --{0} {1}'.format(key, val)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
# please do not merge extra conflicting stuff
# inside those two line (ret =, return)
return _after_ignition_network_profile(cmd,
ret,
name,
network_profile,
path,
nic_opts)
def clone(name,
orig,
profile=None,
network_profile=None,
nic_opts=None,
**kwargs):
'''
Create a new container as a clone of another container
name
Name of the container
orig
Name of the original container to be cloned
profile
Profile to use in container cloning (see
:mod:`lxc.get_container_profile
<salt.modules.lxc.get_container_profile>`). Values in a profile will be
overridden by the **Container Cloning Arguments** listed below.
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
**Container Cloning Arguments**
snapshot
Use Copy On Write snapshots (LVM)
size : 1G
Size of the volume to create. Only applicable if ``backing=lvm``.
backing
The type of storage to use. Set to ``lvm`` to use an LVM group.
Defaults to filesystem within /var/lib/lxc.
network_profile
Network profile to use for container
.. versionadded:: 2015.8.0
nic_opts
give extra opts overriding network profile values
.. versionadded:: 2015.8.0
CLI Examples:
.. code-block:: bash
salt '*' lxc.clone myclone orig=orig_container
salt '*' lxc.clone myclone orig=orig_container snapshot=True
'''
profile = get_container_profile(copy.deepcopy(profile))
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, None)
profile_match = profile.pop(key, default)
# let kwarg overrides be the preferred choice
if kw_overrides_match is None:
return profile_match
return kw_overrides_match
path = select('path')
if exists(name, path=path):
raise CommandExecutionError(
'Container \'{0}\' already exists'.format(name)
)
_ensure_exists(orig, path=path)
if state(orig, path=path) != 'stopped':
raise CommandExecutionError(
'Container \'{0}\' must be stopped to be cloned'.format(orig)
)
backing = select('backing')
snapshot = select('snapshot')
if backing in ('dir',):
snapshot = False
if not snapshot:
snapshot = ''
else:
snapshot = '-s'
size = select('size', '1G')
if backing in ('dir', 'overlayfs', 'btrfs'):
size = None
# LXC commands and options changed in 2.0 - CF issue #34086 for details
if _LooseVersion(version()) >= _LooseVersion('2.0'):
# https://linuxcontainers.org/lxc/manpages//man1/lxc-copy.1.html
cmd = 'lxc-copy'
cmd += ' {0} -n {1} -N {2}'.format(snapshot, orig, name)
else:
# https://linuxcontainers.org/lxc/manpages//man1/lxc-clone.1.html
cmd = 'lxc-clone'
cmd += ' {0} -o {1} -n {2}'.format(snapshot, orig, name)
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
if not os.path.exists(path):
os.makedirs(path)
if backing:
backing = backing.lower()
cmd += ' -B {0}'.format(backing)
if backing not in ('dir', 'overlayfs'):
if size:
cmd += ' -L {0}'.format(size)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
# please do not merge extra conflicting stuff
# inside those two line (ret =, return)
return _after_ignition_network_profile(cmd,
ret,
name,
network_profile,
path,
nic_opts)
def ls_(active=None, cache=True, path=None):
'''
Return a list of the containers available on the minion
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
active
If ``True``, return only active (i.e. running) containers
.. versionadded:: 2015.5.0
CLI Example:
.. code-block:: bash
salt '*' lxc.ls
salt '*' lxc.ls active=True
'''
contextvar = 'lxc.ls{0}'.format(path)
if active:
contextvar += '.active'
if cache and (contextvar in __context__):
return __context__[contextvar]
else:
ret = []
cmd = 'lxc-ls'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
if active:
cmd += ' --active'
output = __salt__['cmd.run_stdout'](cmd, python_shell=False)
for line in output.splitlines():
ret.extend(line.split())
__context__[contextvar] = ret
return ret
def list_(extra=False, limit=None, path=None):
'''
List containers classified by state
extra
Also get per-container specific info. This will change the return data.
Instead of returning a list of containers, a dictionary of containers
and each container's output from :mod:`lxc.info
<salt.modules.lxc.info>`.
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
limit
Return output matching a specific state (**frozen**, **running**, or
**stopped**).
.. versionadded:: 2015.5.0
CLI Examples:
.. code-block:: bash
salt '*' lxc.list
salt '*' lxc.list extra=True
salt '*' lxc.list limit=running
'''
ctnrs = ls_(path=path)
if extra:
stopped = {}
frozen = {}
running = {}
else:
stopped = []
frozen = []
running = []
ret = {'running': running,
'stopped': stopped,
'frozen': frozen}
for container in ctnrs:
cmd = 'lxc-info'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0}'.format(container)
c_info = __salt__['cmd.run'](
cmd,
python_shell=False,
output_loglevel='debug'
)
c_state = None
for line in c_info.splitlines():
stat = line.split(':')
if stat[0] in ('State', 'state'):
c_state = stat[1].strip()
break
if not c_state or (limit is not None and c_state.lower() != limit):
continue
if extra:
infos = info(container, path=path)
method = 'update'
value = {container: infos}
else:
method = 'append'
value = container
if c_state == 'STOPPED':
getattr(stopped, method)(value)
continue
if c_state == 'FROZEN':
getattr(frozen, method)(value)
continue
if c_state == 'RUNNING':
getattr(running, method)(value)
continue
if limit is not None:
return ret.get(limit, {} if extra else [])
return ret
def _change_state(cmd,
name,
expected,
stdin=_marker,
stdout=_marker,
stderr=_marker,
with_communicate=_marker,
use_vt=_marker,
path=None):
pre = state(name, path=path)
if pre == expected:
return {'result': True,
'state': {'old': expected, 'new': expected},
'comment': 'Container \'{0}\' already {1}'
.format(name, expected)}
if cmd == 'lxc-destroy':
# Kill the container first
scmd = 'lxc-stop'
if path:
scmd += ' -P {0}'.format(pipes.quote(path))
scmd += ' -k -n {0}'.format(name)
__salt__['cmd.run'](scmd,
python_shell=False)
if path and ' -P ' not in cmd:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0}'.format(name)
# certain lxc commands need to be taken with care (lxc-start)
# as te command itself mess with double forks; we must not
# communicate with it, but just wait for the exit status
pkwargs = {'python_shell': False,
'redirect_stderr': True,
'with_communicate': with_communicate,
'use_vt': use_vt,
'stdin': stdin,
'stdout': stdout}
for i in [a for a in pkwargs]:
val = pkwargs[i]
if val is _marker:
pkwargs.pop(i, None)
_cmdout = __salt__['cmd.run_all'](cmd, **pkwargs)
if _cmdout['retcode'] != 0:
raise CommandExecutionError(
'Error changing state for container \'{0}\' using command '
'\'{1}\': {2}'.format(name, cmd, _cmdout['stdout'])
)
if expected is not None:
# some commands do not wait, so we will
rcmd = 'lxc-wait'
if path:
rcmd += ' -P {0}'.format(pipes.quote(path))
rcmd += ' -n {0} -s {1}'.format(name, expected.upper())
__salt__['cmd.run'](rcmd, python_shell=False, timeout=30)
_clear_context()
post = state(name, path=path)
ret = {'result': post == expected,
'state': {'old': pre, 'new': post}}
return ret
def _ensure_exists(name, path=None):
'''
Raise an exception if the container does not exist
'''
if not exists(name, path=path):
raise CommandExecutionError(
'Container \'{0}\' does not exist'.format(name)
)
def _ensure_running(name, no_start=False, path=None):
'''
If the container is not currently running, start it. This function returns
the state that the container was in before changing
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
'''
_ensure_exists(name, path=path)
pre = state(name, path=path)
if pre == 'running':
# This will be a no-op but running the function will give us a pretty
# return dict.
return start(name, path=path)
elif pre == 'stopped':
if no_start:
raise CommandExecutionError(
'Container \'{0}\' is not running'.format(name)
)
return start(name, path=path)
elif pre == 'frozen':
if no_start:
raise CommandExecutionError(
'Container \'{0}\' is not running'.format(name)
)
return unfreeze(name, path=path)
def restart(name, path=None, lxc_config=None, force=False):
'''
.. versionadded:: 2015.5.0
Restart the named container. If the container was not running, the
container will merely be started.
name
The name of the container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
lxc_config
path to a lxc config file
config file will be guessed from container name otherwise
.. versionadded:: 2015.8.0
force : False
If ``True``, the container will be force-stopped instead of gracefully
shut down
CLI Example:
.. code-block:: bash
salt myminion lxc.restart name
'''
_ensure_exists(name, path=path)
orig_state = state(name, path=path)
if orig_state != 'stopped':
stop(name, kill=force, path=path)
ret = start(name, path=path, lxc_config=lxc_config)
ret['state']['old'] = orig_state
if orig_state != 'stopped':
ret['restarted'] = True
return ret
def start(name, **kwargs):
'''
Start the named container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
lxc_config
path to a lxc config file
config file will be guessed from container name otherwise
.. versionadded:: 2015.8.0
use_vt
run the command through VT
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.start name
'''
path = kwargs.get('path', None)
cpath = get_root_path(path)
lxc_config = kwargs.get('lxc_config', None)
cmd = 'lxc-start'
if not lxc_config:
lxc_config = os.path.join(cpath, name, 'config')
# we try to start, even without config, if global opts are there
if os.path.exists(lxc_config):
cmd += ' -f {0}'.format(pipes.quote(lxc_config))
cmd += ' -d'
_ensure_exists(name, path=path)
if state(name, path=path) == 'frozen':
raise CommandExecutionError(
'Container \'{0}\' is frozen, use lxc.unfreeze'.format(name)
)
# lxc-start daemonize itself violently, we must not communicate with it
use_vt = kwargs.get('use_vt', None)
with_communicate = kwargs.get('with_communicate', False)
return _change_state(cmd, name, 'running',
stdout=None,
stderr=None,
stdin=None,
with_communicate=with_communicate,
path=path,
use_vt=use_vt)
def stop(name, kill=False, path=None, use_vt=None):
'''
Stop the named container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
kill: False
Do not wait for the container to stop, kill all tasks in the container.
Older LXC versions will stop containers like this irrespective of this
argument.
.. versionchanged:: 2015.5.0
Default value changed to ``False``
use_vt
run the command through VT
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.stop name
'''
_ensure_exists(name, path=path)
orig_state = state(name, path=path)
if orig_state == 'frozen' and not kill:
# Gracefully stopping a frozen container is slower than unfreezing and
# then stopping it (at least in my testing), so if we're not
# force-stopping the container, unfreeze it first.
unfreeze(name, path=path)
cmd = 'lxc-stop'
if kill:
cmd += ' -k'
ret = _change_state(cmd, name, 'stopped', use_vt=use_vt, path=path)
ret['state']['old'] = orig_state
return ret
def freeze(name, **kwargs):
'''
Freeze the named container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
start : False
If ``True`` and the container is stopped, the container will be started
before attempting to freeze.
.. versionadded:: 2015.5.0
use_vt
run the command through VT
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.freeze name
'''
use_vt = kwargs.get('use_vt', None)
path = kwargs.get('path', None)
_ensure_exists(name, path=path)
orig_state = state(name, path=path)
start_ = kwargs.get('start', False)
if orig_state == 'stopped':
if not start_:
raise CommandExecutionError(
'Container \'{0}\' is stopped'.format(name)
)
start(name, path=path)
cmd = 'lxc-freeze'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
ret = _change_state(cmd, name, 'frozen', use_vt=use_vt, path=path)
if orig_state == 'stopped' and start_:
ret['state']['old'] = orig_state
ret['started'] = True
ret['state']['new'] = state(name, path=path)
return ret
def unfreeze(name, path=None, use_vt=None):
'''
Unfreeze the named container.
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
use_vt
run the command through VT
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.unfreeze name
'''
_ensure_exists(name, path=path)
if state(name, path=path) == 'stopped':
raise CommandExecutionError(
'Container \'{0}\' is stopped'.format(name)
)
cmd = 'lxc-unfreeze'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
return _change_state(cmd, name, 'running', path=path, use_vt=use_vt)
def destroy(name, stop=False, path=None):
'''
Destroy the named container.
.. warning::
Destroys all data associated with the container.
path
path to the container parent directory (default: /var/lib/lxc)
.. versionadded:: 2015.8.0
stop : False
If ``True``, the container will be destroyed even if it is
running/frozen.
.. versionchanged:: 2015.5.0
Default value changed to ``False``. This more closely matches the
behavior of ``lxc-destroy(1)``, and also makes it less likely that
an accidental command will destroy a running container that was
being used for important things.
CLI Examples:
.. code-block:: bash
salt '*' lxc.destroy foo
salt '*' lxc.destroy foo stop=True
'''
_ensure_exists(name, path=path)
if not stop and state(name, path=path) != 'stopped':
raise CommandExecutionError(
'Container \'{0}\' is not stopped'.format(name)
)
return _change_state('lxc-destroy', name, None, path=path)
# Compatibility between LXC and nspawn
remove = salt.utils.functools.alias_function(destroy, 'remove')
def exists(name, path=None):
'''
Returns whether the named container exists.
path
path to the container parent directory (default: /var/lib/lxc)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.exists name
'''
_exists = name in ls_(path=path)
# container may be just created but we did cached earlier the
# lxc-ls results
if not _exists:
_exists = name in ls_(cache=False, path=path)
return _exists
def state(name, path=None):
'''
Returns the state of a container.
path
path to the container parent directory (default: /var/lib/lxc)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.state name
'''
# Don't use _ensure_exists() here, it will mess with _change_state()
cachekey = 'lxc.state.{0}{1}'.format(name, path)
try:
return __context__[cachekey]
except KeyError:
if not exists(name, path=path):
__context__[cachekey] = None
else:
cmd = 'lxc-info'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0}'.format(name)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
if ret['retcode'] != 0:
_clear_context()
raise CommandExecutionError(
'Unable to get state of container \'{0}\''.format(name)
)
c_infos = ret['stdout'].splitlines()
c_state = None
for c_info in c_infos:
stat = c_info.split(':')
if stat[0].lower() == 'state':
c_state = stat[1].strip().lower()
break
__context__[cachekey] = c_state
return __context__[cachekey]
def get_parameter(name, parameter, path=None):
'''
Returns the value of a cgroup parameter for a container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.get_parameter container_name memory.limit_in_bytes
'''
_ensure_exists(name, path=path)
cmd = 'lxc-cgroup'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0} {1}'.format(name, parameter)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
if ret['retcode'] != 0:
raise CommandExecutionError(
'Unable to retrieve value for \'{0}\''.format(parameter)
)
return ret['stdout'].strip()
def set_parameter(name, parameter, value, path=None):
'''
Set the value of a cgroup parameter for a container.
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.set_parameter name parameter value
'''
if not exists(name, path=path):
return None
cmd = 'lxc-cgroup'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0} {1} {2}'.format(name, parameter, value)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
if ret['retcode'] != 0:
return False
else:
return True
def info(name, path=None):
'''
Returns information about a container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.info name
'''
cachekey = 'lxc.info.{0}{1}'.format(name, path)
try:
return __context__[cachekey]
except KeyError:
_ensure_exists(name, path=path)
cpath = get_root_path(path)
try:
conf_file = os.path.join(cpath, name, 'config')
except AttributeError:
conf_file = os.path.join(cpath, six.text_type(name), 'config')
if not os.path.isfile(conf_file):
raise CommandExecutionError(
'LXC config file {0} does not exist'.format(conf_file)
)
ret = {}
config = []
with salt.utils.files.fopen(conf_file) as fp_:
for line in fp_:
line = salt.utils.stringutils.to_unicode(line)
comps = [x.strip() for x in
line.split('#', 1)[0].strip().split('=', 1)]
if len(comps) == 2:
config.append(tuple(comps))
ifaces = []
current = None
for key, val in config:
if key == 'lxc.network.type':
current = {'type': val}
ifaces.append(current)
elif not current:
continue
elif key.startswith('lxc.network.'):
current[key.replace('lxc.network.', '', 1)] = val
if ifaces:
ret['nics'] = ifaces
ret['rootfs'] = next(
(x[1] for x in config if x[0] == 'lxc.rootfs'),
None
)
ret['state'] = state(name, path=path)
ret['ips'] = []
ret['public_ips'] = []
ret['private_ips'] = []
ret['public_ipv4_ips'] = []
ret['public_ipv6_ips'] = []
ret['private_ipv4_ips'] = []
ret['private_ipv6_ips'] = []
ret['ipv4_ips'] = []
ret['ipv6_ips'] = []
ret['size'] = None
ret['config'] = conf_file
if ret['state'] == 'running':
try:
limit = int(get_parameter(name, 'memory.limit_in_bytes'))
except (CommandExecutionError, TypeError, ValueError):
limit = 0
try:
usage = int(get_parameter(name, 'memory.usage_in_bytes'))
except (CommandExecutionError, TypeError, ValueError):
usage = 0
free = limit - usage
ret['memory_limit'] = limit
ret['memory_free'] = free
size = run_stdout(name, 'df /', path=path, python_shell=False)
# The size is the 2nd column of the last line
ret['size'] = size.splitlines()[-1].split()[1]
# First try iproute2
ip_cmd = run_all(
name, 'ip link show', path=path, python_shell=False)
if ip_cmd['retcode'] == 0:
ip_data = ip_cmd['stdout']
ip_cmd = run_all(
name, 'ip addr show', path=path, python_shell=False)
ip_data += '\n' + ip_cmd['stdout']
ip_data = salt.utils.network._interfaces_ip(ip_data)
else:
# That didn't work, try ifconfig
ip_cmd = run_all(
name, 'ifconfig', path=path, python_shell=False)
if ip_cmd['retcode'] == 0:
ip_data = \
salt.utils.network._interfaces_ifconfig(
ip_cmd['stdout'])
else:
# Neither was successful, give up
log.warning(
'Unable to run ip or ifconfig in container \'%s\'', name
)
ip_data = {}
ret['ipv4_ips'] = salt.utils.network.ip_addrs(
include_loopback=True,
interface_data=ip_data
)
ret['ipv6_ips'] = salt.utils.network.ip_addrs6(
include_loopback=True,
interface_data=ip_data
)
ret['ips'] = ret['ipv4_ips'] + ret['ipv6_ips']
for address in ret['ipv4_ips']:
if address == '127.0.0.1':
ret['private_ips'].append(address)
ret['private_ipv4_ips'].append(address)
elif salt.utils.cloud.is_public_ip(address):
ret['public_ips'].append(address)
ret['public_ipv4_ips'].append(address)
else:
ret['private_ips'].append(address)
ret['private_ipv4_ips'].append(address)
for address in ret['ipv6_ips']:
if address == '::1' or address.startswith('fe80'):
ret['private_ips'].append(address)
ret['private_ipv6_ips'].append(address)
else:
ret['public_ips'].append(address)
ret['public_ipv6_ips'].append(address)
for key in [x for x in ret if x == 'ips' or x.endswith('ips')]:
ret[key].sort(key=_ip_sort)
__context__[cachekey] = ret
return __context__[cachekey]
def set_password(name, users, password, encrypted=True, path=None):
'''
.. versionchanged:: 2015.5.0
Function renamed from ``set_pass`` to ``set_password``. Additionally,
this function now supports (and defaults to using) a password hash
instead of a plaintext password.
Set the password of one or more system users inside containers
users
Comma-separated list (or python list) of users to change password
password
Password to set for the specified user(s)
encrypted : True
If true, ``password`` must be a password hash. Set to ``False`` to set
a plaintext password (not recommended).
.. versionadded:: 2015.5.0
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.set_pass container-name root '$6$uJ2uAyLU$KoI67t8As/0fXtJOPcHKGXmUpcoYUcVR2K6x93walnShTCQvjRwq25yIkiCBOqgbfdKQSFnAo28/ek6716vEV1'
salt '*' lxc.set_pass container-name root foo encrypted=False
'''
def _bad_user_input():
raise SaltInvocationError('Invalid input for \'users\' parameter')
if not isinstance(users, list):
try:
users = users.split(',')
except AttributeError:
_bad_user_input()
if not users:
_bad_user_input()
failed_users = []
for user in users:
result = retcode(name,
'chpasswd{0}'.format(' -e' if encrypted else ''),
stdin=':'.join((user, password)),
python_shell=False,
path=path,
chroot_fallback=True,
output_loglevel='quiet')
if result != 0:
failed_users.append(user)
if failed_users:
raise CommandExecutionError(
'Password change failed for the following user(s): {0}'
.format(', '.join(failed_users))
)
return True
set_pass = salt.utils.functools.alias_function(set_password, 'set_pass')
def update_lxc_conf(name, lxc_conf, lxc_conf_unset, path=None):
'''
Edit LXC configuration options
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.update_lxc_conf ubuntu \\
lxc_conf="[{'network.ipv4.ip':'10.0.3.5'}]" \\
lxc_conf_unset="['lxc.utsname']"
'''
_ensure_exists(name, path=path)
cpath = get_root_path(path)
lxc_conf_p = os.path.join(cpath, name, 'config')
if not os.path.exists(lxc_conf_p):
raise SaltInvocationError(
'Configuration file {0} does not exist'.format(lxc_conf_p)
)
changes = {'edited': [], 'added': [], 'removed': []}
ret = {'changes': changes, 'result': True, 'comment': ''}
# do not use salt.utils.files.fopen !
with salt.utils.files.fopen(lxc_conf_p, 'r') as fic:
filtered_lxc_conf = []
for row in lxc_conf:
if not row:
continue
for conf in row:
filtered_lxc_conf.append((conf.strip(),
row[conf].strip()))
ret['comment'] = 'lxc.conf is up to date'
lines = []
orig_config = salt.utils.stringutils.to_unicode(fic.read())
for line in orig_config.splitlines():
if line.startswith('#') or not line.strip():
lines.append([line, ''])
else:
line = line.split('=')
index = line.pop(0)
val = (index.strip(), '='.join(line).strip())
if val not in lines:
lines.append(val)
for key, item in filtered_lxc_conf:
matched = False
for idx, line in enumerate(lines[:]):
if line[0] == key:
matched = True
lines[idx] = (key, item)
if '='.join(line[1:]).strip() != item.strip():
changes['edited'].append(
({line[0]: line[1:]}, {key: item}))
break
if not matched:
if (key, item) not in lines:
lines.append((key, item))
changes['added'].append({key: item})
dest_lxc_conf = []
# filter unset
if lxc_conf_unset:
for line in lines:
for opt in lxc_conf_unset:
if (
not line[0].startswith(opt) and
line not in dest_lxc_conf
):
dest_lxc_conf.append(line)
else:
changes['removed'].append(opt)
else:
dest_lxc_conf = lines
conf = ''
for key, val in dest_lxc_conf:
if not val:
conf += '{0}\n'.format(key)
else:
conf += '{0} = {1}\n'.format(key.strip(), val.strip())
conf_changed = conf != orig_config
chrono = datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S')
if conf_changed:
# DO NOT USE salt.utils.files.fopen here, i got (kiorky)
# problems with lxc configs which were wiped !
with salt.utils.files.fopen('{0}.{1}'.format(lxc_conf_p, chrono), 'w') as wfic:
wfic.write(salt.utils.stringutils.to_str(conf))
with salt.utils.files.fopen(lxc_conf_p, 'w') as wfic:
wfic.write(salt.utils.stringutils.to_str(conf))
ret['comment'] = 'Updated'
ret['result'] = True
if not any(changes[x] for x in changes):
# Ensure an empty changes dict if nothing was modified
ret['changes'] = {}
return ret
def set_dns(name, dnsservers=None, searchdomains=None, path=None):
'''
.. versionchanged:: 2015.5.0
The ``dnsservers`` and ``searchdomains`` parameters can now be passed
as a comma-separated list.
Update /etc/resolv.confo
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.set_dns ubuntu "['8.8.8.8', '4.4.4.4']"
'''
if dnsservers is None:
dnsservers = ['8.8.8.8', '4.4.4.4']
elif not isinstance(dnsservers, list):
try:
dnsservers = dnsservers.split(',')
except AttributeError:
raise SaltInvocationError(
'Invalid input for \'dnsservers\' parameter'
)
if searchdomains is None:
searchdomains = []
elif not isinstance(searchdomains, list):
try:
searchdomains = searchdomains.split(',')
except AttributeError:
raise SaltInvocationError(
'Invalid input for \'searchdomains\' parameter'
)
dns = ['nameserver {0}'.format(x) for x in dnsservers]
dns.extend(['search {0}'.format(x) for x in searchdomains])
dns = '\n'.join(dns) + '\n'
# we may be using resolvconf in the container
# We need to handle that case with care:
# - we create the resolv.conf runtime directory (the
# linked directory) as anyway it will be shadowed when the real
# runned tmpfs mountpoint will be mounted.
# ( /etc/resolv.conf -> ../run/resolvconf/resolv.conf)
# Indeed, it can save us in any other case (running, eg, in a
# bare chroot when repairing or preparing the container for
# operation.
# - We also teach resolvconf to use the aforementioned dns.
# - We finally also set /etc/resolv.conf in all cases
rstr = __salt__['test.random_hash']()
# no tmp here, apparmor won't let us execute !
script = '/sbin/{0}_dns.sh'.format(rstr)
DNS_SCRIPT = "\n".join([
# 'set -x',
'#!/usr/bin/env bash',
'if [ -h /etc/resolv.conf ];then',
' if [ "x$(readlink /etc/resolv.conf)"'
' = "x../run/resolvconf/resolv.conf" ];then',
' if [ ! -d /run/resolvconf/ ];then',
' mkdir -p /run/resolvconf',
' fi',
' cat > /etc/resolvconf/resolv.conf.d/head <<EOF',
dns,
'EOF',
'',
' fi',
'fi',
'cat > /etc/resolv.conf <<EOF',
dns,
'EOF',
''])
result = run_all(
name, 'tee {0}'.format(script), path=path,
stdin=DNS_SCRIPT, python_shell=True)
if result['retcode'] == 0:
result = run_all(
name, 'sh -c "chmod +x {0};{0}"'.format(script),
path=path, python_shell=True)
# blindly delete the setter file
run_all(name,
'sh -c \'if [ -f "{0}" ];then rm -f "{0}";fi\''.format(script),
path=path, python_shell=True)
if result['retcode'] != 0:
error = ('Unable to write to /etc/resolv.conf in container \'{0}\''
.format(name))
if result['stderr']:
error += ': {0}'.format(result['stderr'])
raise CommandExecutionError(error)
return True
def running_systemd(name, cache=True, path=None):
'''
Determine if systemD is running
path
path to the container parent
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.running_systemd ubuntu
'''
k = 'lxc.systemd.test.{0}{1}'.format(name, path)
ret = __context__.get(k, None)
if ret is None or not cache:
rstr = __salt__['test.random_hash']()
# no tmp here, apparmor won't let us execute !
script = '/sbin/{0}_testsystemd.sh'.format(rstr)
# ubuntu already had since trusty some bits of systemd but was
# still using upstart ...
# we need to be a bit more careful that just testing that systemd
# is present
_script = textwrap.dedent(
'''\
#!/usr/bin/env bash
set -x
if ! command -v systemctl 1>/dev/null 2>/dev/null;then exit 2;fi
for i in \\
/run/systemd/journal/dev-log\\
/run/systemd/journal/flushed\\
/run/systemd/journal/kernel-seqnum\\
/run/systemd/journal/socket\\
/run/systemd/journal/stdout\\
/var/run/systemd/journal/dev-log\\
/var/run/systemd/journal/flushed\\
/var/run/systemd/journal/kernel-seqnum\\
/var/run/systemd/journal/socket\\
/var/run/systemd/journal/stdout\\
;do\\
if test -e ${i};then exit 0;fi
done
if test -d /var/systemd/system;then exit 0;fi
exit 2
''')
result = run_all(
name, 'tee {0}'.format(script), path=path,
stdin=_script, python_shell=True)
if result['retcode'] == 0:
result = run_all(name,
'sh -c "chmod +x {0};{0}"'''.format(script),
path=path,
python_shell=True)
else:
raise CommandExecutionError(
'lxc {0} failed to copy initd tester'.format(name))
run_all(name,
'sh -c \'if [ -f "{0}" ];then rm -f "{0}";fi\''
''.format(script),
path=path,
ignore_retcode=True,
python_shell=True)
if result['retcode'] != 0:
error = ('Unable to determine if the container \'{0}\''
' was running systemd, assmuming it is not.'
''.format(name))
if result['stderr']:
error += ': {0}'.format(result['stderr'])
# only cache result if we got a known exit code
if result['retcode'] in (0, 2):
__context__[k] = ret = not result['retcode']
return ret
def systemd_running_state(name, path=None):
'''
Get the operational state of a systemd based container
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.systemd_running_state ubuntu
'''
try:
ret = run_all(name,
'systemctl is-system-running',
path=path,
ignore_retcode=True)['stdout']
except CommandExecutionError:
ret = ''
return ret
def test_sd_started_state(name, path=None):
'''
Test if a systemd container is fully started
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.test_sd_started_state ubuntu
'''
qstate = systemd_running_state(name, path=path)
if qstate in ('initializing', 'starting'):
return False
elif qstate == '':
return None
else:
return True
def test_bare_started_state(name, path=None):
'''
Test if a non systemd container is fully started
For now, it consists only to test if the container is attachable
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.test_bare_started_state ubuntu
'''
try:
ret = run_all(
name, 'ls', path=path, ignore_retcode=True
)['retcode'] == 0
except (CommandExecutionError,):
ret = None
return ret
def wait_started(name, path=None, timeout=300):
'''
Check that the system has fully inited
This is actually very important for systemD based containers
see https://github.com/saltstack/salt/issues/23847
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.wait_started ubuntu
'''
if not exists(name, path=path):
raise CommandExecutionError(
'Container {0} does does exists'.format(name))
if not state(name, path=path) == 'running':
raise CommandExecutionError(
'Container {0} is not running'.format(name))
ret = False
if running_systemd(name, path=path):
test_started = test_sd_started_state
logger = log.error
else:
test_started = test_bare_started_state
logger = log.debug
now = time.time()
expire = now + timeout
now = time.time()
started = test_started(name, path=path)
while time.time() < expire and not started:
time.sleep(0.3)
started = test_started(name, path=path)
if started is None:
logger(
'Assuming %s is started, although we failed to detect that'
' is fully started correctly', name)
ret = True
else:
ret = started
return ret
def _needs_install(name, path=None):
ret = 0
has_minion = retcode(name,
'which salt-minion',
path=path,
ignore_retcode=True)
# we assume that installing is when no minion is running
# but testing the executable presence is not enougth for custom
# installs where the bootstrap can do much more than installing
# the bare salt binaries.
if has_minion:
processes = run_stdout(name, "ps aux", path=path)
if 'salt-minion' not in processes:
ret = 1
else:
retcode(name, 'salt-call --local service.stop salt-minion')
else:
ret = 1
return ret
def bootstrap(name,
config=None,
approve_key=True,
install=True,
pub_key=None,
priv_key=None,
bootstrap_url=None,
force_install=False,
unconditional_install=False,
path=None,
bootstrap_delay=None,
bootstrap_args=None,
bootstrap_shell=None):
'''
Install and configure salt in a container.
config
Minion configuration options. By default, the ``master`` option is set
to the target host's master.
approve_key
Request a pre-approval of the generated minion key. Requires
that the salt-master be configured to either auto-accept all keys or
expect a signing request from the target host. Default: ``True``
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
pub_key
Explicit public key to pressed the minion with (optional).
This can be either a filepath or a string representing the key
priv_key
Explicit private key to pressed the minion with (optional).
This can be either a filepath or a string representing the key
bootstrap_delay
Delay in seconds between end of container creation and bootstrapping.
Useful when waiting for container to obtain a DHCP lease.
.. versionadded:: 2015.5.0
bootstrap_url
url, content or filepath to the salt bootstrap script
bootstrap_args
salt bootstrap script arguments
bootstrap_shell
shell to execute the script into
install
Whether to attempt a full installation of salt-minion if needed.
force_install
Force installation even if salt-minion is detected,
this is the way to run vendor bootstrap scripts even
if a salt minion is already present in the container
unconditional_install
Run the script even if the container seems seeded
CLI Examples:
.. code-block:: bash
salt 'minion' lxc.bootstrap container_name [config=config_data] \\
[approve_key=(True|False)] [install=(True|False)]
'''
wait_started(name, path=path)
if bootstrap_delay is not None:
try:
log.info('LXC %s: bootstrap_delay: %s', name, bootstrap_delay)
time.sleep(bootstrap_delay)
except TypeError:
# Bad input, but assume since a value was passed that
# a delay was desired, and sleep for 5 seconds
time.sleep(5)
c_info = info(name, path=path)
if not c_info:
return None
# default set here as we cannot set them
# in def as it can come from a chain of procedures.
if bootstrap_args:
# custom bootstrap args can be totally customized, and user could
# have inserted the placeholder for the config directory.
# For example, some salt bootstrap script do not use at all -c
if '{0}' not in bootstrap_args:
bootstrap_args += ' -c {0}'
else:
bootstrap_args = '-c {0}'
if not bootstrap_shell:
bootstrap_shell = 'sh'
orig_state = _ensure_running(name, path=path)
if not orig_state:
return orig_state
if not force_install:
needs_install = _needs_install(name, path=path)
else:
needs_install = True
seeded = retcode(name,
'test -e \'{0}\''.format(SEED_MARKER),
path=path,
chroot_fallback=True,
ignore_retcode=True) == 0
tmp = tempfile.mkdtemp()
if seeded and not unconditional_install:
ret = True
else:
ret = False
cfg_files = __salt__['seed.mkconfig'](
config, tmp=tmp, id_=name, approve_key=approve_key,
pub_key=pub_key, priv_key=priv_key)
if needs_install or force_install or unconditional_install:
if install:
rstr = __salt__['test.random_hash']()
configdir = '/var/tmp/.c_{0}'.format(rstr)
cmd = 'install -m 0700 -d {0}'.format(configdir)
if run_all(
name, cmd, path=path, python_shell=False
)['retcode'] != 0:
log.error('tmpdir %s creation failed %s', configdir, cmd)
return False
bs_ = __salt__['config.gather_bootstrap_script'](
bootstrap=bootstrap_url)
script = '/sbin/{0}_bootstrap.sh'.format(rstr)
copy_to(name, bs_, script, path=path)
result = run_all(name,
'sh -c "chmod +x {0}"'.format(script),
path=path,
python_shell=True)
copy_to(name, cfg_files['config'],
os.path.join(configdir, 'minion'),
path=path)
copy_to(name, cfg_files['privkey'],
os.path.join(configdir, 'minion.pem'),
path=path)
copy_to(name, cfg_files['pubkey'],
os.path.join(configdir, 'minion.pub'),
path=path)
bootstrap_args = bootstrap_args.format(configdir)
cmd = ('{0} {2} {1}'
.format(bootstrap_shell,
bootstrap_args.replace("'", "''"),
script))
# log ASAP the forged bootstrap command which can be wrapped
# out of the output in case of unexpected problem
log.info('Running %s in LXC container \'%s\'', cmd, name)
ret = retcode(name, cmd, output_loglevel='info',
path=path, use_vt=True) == 0
run_all(name,
'sh -c \'if [ -f "{0}" ];then rm -f "{0}";fi\''
''.format(script),
path=path,
ignore_retcode=True,
python_shell=True)
else:
ret = False
else:
minion_config = salt.config.minion_config(cfg_files['config'])
pki_dir = minion_config['pki_dir']
copy_to(name,
cfg_files['config'],
'/etc/salt/minion',
path=path)
copy_to(name,
cfg_files['privkey'],
os.path.join(pki_dir, 'minion.pem'),
path=path)
copy_to(name,
cfg_files['pubkey'],
os.path.join(pki_dir, 'minion.pub'),
path=path)
run(name,
'salt-call --local service.enable salt-minion',
path=path,
python_shell=False)
ret = True
shutil.rmtree(tmp)
if orig_state == 'stopped':
stop(name, path=path)
elif orig_state == 'frozen':
freeze(name, path=path)
# mark seeded upon successful install
if ret:
run(name,
'touch \'{0}\''.format(SEED_MARKER),
path=path,
python_shell=False)
return ret
def attachable(name, path=None):
'''
Return True if the named container can be attached to via the lxc-attach
command
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt 'minion' lxc.attachable ubuntu
'''
cachekey = 'lxc.attachable{0}{1}'.format(name, path)
try:
return __context__[cachekey]
except KeyError:
_ensure_exists(name, path=path)
# Can't use run() here because it uses attachable() and would
# endlessly recurse, resulting in a traceback
log.debug('Checking if LXC container %s is attachable', name)
cmd = 'lxc-attach'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' --clear-env -n {0} -- /usr/bin/env'.format(name)
result = __salt__['cmd.retcode'](cmd,
python_shell=False,
output_loglevel='quiet',
ignore_retcode=True) == 0
__context__[cachekey] = result
return __context__[cachekey]
def _run(name,
cmd,
output=None,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=None,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
Common logic for lxc.run functions
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
'''
orig_state = state(name, path=path)
try:
if attachable(name, path=path):
ret = __salt__['container_resource.run'](
name,
cmd,
path=path,
container_type=__virtualname__,
exec_driver=EXEC_DRIVER,
output=output,
no_start=no_start,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
ignore_retcode=ignore_retcode,
use_vt=use_vt,
keep_env=keep_env)
else:
if not chroot_fallback:
raise CommandExecutionError(
'{0} is not attachable.'.format(name))
rootfs = info(name, path=path).get('rootfs')
# Set context var to make cmd.run_chroot run cmd.run instead of
# cmd.run_all.
__context__['cmd.run_chroot.func'] = __salt__['cmd.run']
ret = __salt__['cmd.run_chroot'](rootfs,
cmd,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
ignore_retcode=ignore_retcode)
except Exception:
raise
finally:
# Make sure we honor preserve_state, even if there was an exception
new_state = state(name, path=path)
if preserve_state:
if orig_state == 'stopped' and new_state != 'stopped':
stop(name, path=path)
elif orig_state == 'frozen' and new_state != 'frozen':
freeze(name, start=True, path=path)
if output in (None, 'all'):
return ret
else:
return ret[output]
def run(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.8.0
Run :mod:`cmd.run <salt.modules.cmdmod.run>` within a container
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed in stderr if the command being run
does not exist. If no output is returned using this function, try using
:mod:`lxc.run_stderr <salt.modules.lxc.run_stderr>` or
:mod:`lxc.run_all <salt.modules.lxc.run_all>`.
name
Name of the container in which to run the command
cmd
Command to run
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console. Assumes
``output=all``.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
CLI Example:
.. code-block:: bash
salt myminion lxc.run mycontainer 'ifconfig -a'
'''
return _run(name,
cmd,
path=path,
output=None,
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def run_stdout(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.5.0
Run :mod:`cmd.run_stdout <salt.modules.cmdmod.run_stdout>` within a container
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed in stderr if the command being run
does not exist. If no output is returned using this function, try using
:mod:`lxc.run_stderr <salt.modules.lxc.run_stderr>` or
:mod:`lxc.run_all <salt.modules.lxc.run_all>`.
name
Name of the container in which to run the command
cmd
Command to run
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console
``output=all``.
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
CLI Example:
.. code-block:: bash
salt myminion lxc.run_stdout mycontainer 'ifconfig -a'
'''
return _run(name,
cmd,
path=path,
output='stdout',
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def run_stderr(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.5.0
Run :mod:`cmd.run_stderr <salt.modules.cmdmod.run_stderr>` within a container
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed if the command being run does not
exist.
name
Name of the container in which to run the command
cmd
Command to run
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console
``output=all``.
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
CLI Example:
.. code-block:: bash
salt myminion lxc.run_stderr mycontainer 'ip addr show'
'''
return _run(name,
cmd,
path=path,
output='stderr',
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def retcode(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.5.0
Run :mod:`cmd.retcode <salt.modules.cmdmod.retcode>` within a container
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed in stderr if the command being run
does not exist. If the retcode is nonzero and not what was expected,
try using :mod:`lxc.run_stderr <salt.modules.lxc.run_stderr>`
or :mod:`lxc.run_all <salt.modules.lxc.run_all>`.
name
Name of the container in which to run the command
cmd
Command to run
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console
``output=all``.
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
CLI Example:
.. code-block:: bash
salt myminion lxc.retcode mycontainer 'ip addr show'
'''
return _run(name,
cmd,
output='retcode',
path=path,
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def run_all(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.5.0
Run :mod:`cmd.run_all <salt.modules.cmdmod.run_all>` within a container
.. note::
While the command is run within the container, it is initiated from the
host. Therefore, the PID in the return dict is from the host, not from
the container.
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed in stderr if the command being run
does not exist.
name
Name of the container in which to run the command
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
cmd
Command to run
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console
``output=all``.
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
CLI Example:
.. code-block:: bash
salt myminion lxc.run_all mycontainer 'ip addr show'
'''
return _run(name,
cmd,
output='all',
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
path=path,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def _get_md5(name, path):
'''
Get the MD5 checksum of a file from a container
'''
output = run_stdout(name, 'md5sum "{0}"'.format(path),
chroot_fallback=True,
ignore_retcode=True)
try:
return output.split()[0]
except IndexError:
# Destination file does not exist or could not be accessed
return None
def copy_to(name, source, dest, overwrite=False, makedirs=False, path=None):
'''
.. versionchanged:: 2015.8.0
Function renamed from ``lxc.cp`` to ``lxc.copy_to`` for consistency
with other container types. ``lxc.cp`` will continue to work, however.
For versions 2015.2.x and earlier, use ``lxc.cp``.
Copy a file or directory from the host into a container
name
Container name
source
File to be copied to the container
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
dest
Destination on the container. Must be an absolute path.
.. versionchanged:: 2015.5.0
If the destination is a directory, the file will be copied into
that directory.
overwrite : False
Unless this option is set to ``True``, then if a file exists at the
location specified by the ``dest`` argument, an error will be raised.
.. versionadded:: 2015.8.0
makedirs : False
Create the parent directory on the container if it does not already
exist.
.. versionadded:: 2015.5.0
CLI Example:
.. code-block:: bash
salt 'minion' lxc.copy_to /tmp/foo /root/foo
salt 'minion' lxc.cp /tmp/foo /root/foo
'''
_ensure_running(name, no_start=True, path=path)
return __salt__['container_resource.copy_to'](
name,
source,
dest,
container_type=__virtualname__,
path=path,
exec_driver=EXEC_DRIVER,
overwrite=overwrite,
makedirs=makedirs)
cp = salt.utils.functools.alias_function(copy_to, 'cp')
def read_conf(conf_file, out_format='simple'):
'''
Read in an LXC configuration file. By default returns a simple, unsorted
dict, but can also return a more detailed structure including blank lines
and comments.
out_format:
set to 'simple' if you need the old and unsupported behavior.
This won't support the multiple lxc values (eg: multiple network nics)
CLI Examples:
.. code-block:: bash
salt 'minion' lxc.read_conf /etc/lxc/mycontainer.conf
salt 'minion' lxc.read_conf /etc/lxc/mycontainer.conf out_format=commented
'''
ret_commented = []
ret_simple = {}
with salt.utils.files.fopen(conf_file, 'r') as fp_:
for line in salt.utils.data.decode(fp_.readlines()):
if '=' not in line:
ret_commented.append(line)
continue
comps = line.split('=')
value = '='.join(comps[1:]).strip()
comment = None
if value.strip().startswith('#'):
vcomps = value.strip().split('#')
value = vcomps[1].strip()
comment = '#'.join(vcomps[1:]).strip()
ret_commented.append({comps[0].strip(): {
'value': value,
'comment': comment,
}})
else:
ret_commented.append({comps[0].strip(): value})
ret_simple[comps[0].strip()] = value
if out_format == 'simple':
return ret_simple
return ret_commented
def write_conf(conf_file, conf):
'''
Write out an LXC configuration file
This is normally only used internally. The format of the data structure
must match that which is returned from ``lxc.read_conf()``, with
``out_format`` set to ``commented``.
An example might look like:
.. code-block:: python
[
{'lxc.utsname': '$CONTAINER_NAME'},
'# This is a commented line\\n',
'\\n',
{'lxc.mount': '$CONTAINER_FSTAB'},
{'lxc.rootfs': {'comment': 'This is another test',
'value': 'This is another test'}},
'\\n',
{'lxc.network.type': 'veth'},
{'lxc.network.flags': 'up'},
{'lxc.network.link': 'br0'},
{'lxc.network.mac': '$CONTAINER_MACADDR'},
{'lxc.network.ipv4': '$CONTAINER_IPADDR'},
{'lxc.network.name': '$CONTAINER_DEVICENAME'},
]
CLI Example:
.. code-block:: bash
salt 'minion' lxc.write_conf /etc/lxc/mycontainer.conf \\
out_format=commented
'''
if not isinstance(conf, list):
raise SaltInvocationError('Configuration must be passed as a list')
# construct the content prior to write to the file
# to avoid half written configs
content = ''
for line in conf:
if isinstance(line, (six.text_type, six.string_types)):
content += line
elif isinstance(line, dict):
for key in list(line.keys()):
out_line = None
if isinstance(
line[key],
(six.text_type, six.string_types, six.integer_types, float)
):
out_line = ' = '.join((key, "{0}".format(line[key])))
elif isinstance(line[key], dict):
out_line = ' = '.join((key, line[key]['value']))
if 'comment' in line[key]:
out_line = ' # '.join((out_line, line[key]['comment']))
if out_line:
content += out_line
content += '\n'
with salt.utils.files.fopen(conf_file, 'w') as fp_:
fp_.write(salt.utils.stringutils.to_str(content))
return {}
def edit_conf(conf_file,
out_format='simple',
read_only=False,
lxc_config=None,
**kwargs):
'''
Edit an LXC configuration file. If a setting is already present inside the
file, its value will be replaced. If it does not exist, it will be appended
to the end of the file. Comments and blank lines will be kept in-tact if
they already exist in the file.
out_format:
Set to simple if you need backward compatibility (multiple items for a
simple key is not supported)
read_only:
return only the edited configuration without applying it
to the underlying lxc configuration file
lxc_config:
List of dict containning lxc configuration items
For network configuration, you also need to add the device it belongs
to, otherwise it will default to eth0.
Also, any change to a network parameter will result in the whole
network reconfiguration to avoid mismatchs, be aware of that !
After the file is edited, its contents will be returned. By default, it
will be returned in ``simple`` format, meaning an unordered dict (which
may not represent the actual file order). Passing in an ``out_format`` of
``commented`` will return a data structure which accurately represents the
order and content of the file.
CLI Example:
.. code-block:: bash
salt 'minion' lxc.edit_conf /etc/lxc/mycontainer.conf \\
out_format=commented lxc.network.type=veth
salt 'minion' lxc.edit_conf /etc/lxc/mycontainer.conf \\
out_format=commented \\
lxc_config="[{'lxc.network.name': 'eth0', \\
'lxc.network.ipv4': '1.2.3.4'},
{'lxc.network.name': 'eth2', \\
'lxc.network.ipv4': '1.2.3.5',\\
'lxc.network.gateway': '1.2.3.1'}]"
'''
data = []
try:
conf = read_conf(conf_file, out_format=out_format)
except Exception:
conf = []
if not lxc_config:
lxc_config = []
lxc_config = copy.deepcopy(lxc_config)
# search if we want to access net config
# in that case, we will replace all the net configuration
net_config = []
for lxc_kws in lxc_config + [kwargs]:
net_params = {}
for kwarg in [a for a in lxc_kws]:
if kwarg.startswith('__'):
continue
if kwarg.startswith('lxc.network.'):
net_params[kwarg] = lxc_kws[kwarg]
lxc_kws.pop(kwarg, None)
if net_params:
net_config.append(net_params)
nic_opts = salt.utils.odict.OrderedDict()
for params in net_config:
dev = params.get('lxc.network.name', DEFAULT_NIC)
dev_opts = nic_opts.setdefault(dev, salt.utils.odict.OrderedDict())
for param in params:
opt = param.replace('lxc.network.', '')
opt = {'hwaddr': 'mac'}.get(opt, opt)
dev_opts[opt] = params[param]
net_changes = []
if nic_opts:
net_changes = _config_list(conf, only_net=True,
**{'network_profile': DEFAULT_NIC,
'nic_opts': nic_opts})
if net_changes:
lxc_config.extend(net_changes)
for line in conf:
if not isinstance(line, dict):
data.append(line)
continue
else:
for key in list(line.keys()):
val = line[key]
if net_changes and key.startswith('lxc.network.'):
continue
found = False
for ix in range(len(lxc_config)):
kw = lxc_config[ix]
if key in kw:
found = True
data.append({key: kw[key]})
del kw[key]
if not found:
data.append({key: val})
for lxc_kws in lxc_config:
for kwarg in lxc_kws:
data.append({kwarg: lxc_kws[kwarg]})
if read_only:
return data
write_conf(conf_file, data)
return read_conf(conf_file, out_format)
def reboot(name, path=None):
'''
Reboot a container.
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Examples:
.. code-block:: bash
salt 'minion' lxc.reboot myvm
'''
ret = {'result': True,
'changes': {},
'comment': '{0} rebooted'.format(name)}
does_exist = exists(name, path=path)
if does_exist and (state(name, path=path) == 'running'):
try:
stop(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
ret['result'] = False
return ret
if does_exist and (state(name, path=path) != 'running'):
try:
start(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
ret['result'] = False
return ret
ret['changes'][name] = 'rebooted'
return ret
def reconfigure(name,
cpu=None,
cpuset=None,
cpushare=None,
memory=None,
profile=None,
network_profile=None,
nic_opts=None,
bridge=None,
gateway=None,
autostart=None,
utsname=None,
rootfs=None,
path=None,
**kwargs):
'''
Reconfigure a container.
This only applies to a few property
name
Name of the container.
utsname
utsname of the container.
.. versionadded:: 2016.3.0
rootfs
rootfs of the container.
.. versionadded:: 2016.3.0
cpu
Select a random number of cpu cores and assign it to the cpuset, if the
cpuset option is set then this option will be ignored
cpuset
Explicitly define the cpus this container will be bound to
cpushare
cgroups cpu shares.
autostart
autostart container on reboot
memory
cgroups memory limit, in MB.
(0 for nolimit, None for old default 1024MB)
gateway
the ipv4 gateway to use
the default does nothing more than lxcutils does
bridge
the bridge to use
the default does nothing more than lxcutils does
nic
Network interfaces profile (defined in config or pillar).
nic_opts
Extra options for network interfaces, will override
``{"eth0": {"mac": "aa:bb:cc:dd:ee:ff", "ipv4": "10.1.1.1", "ipv6": "2001:db8::ff00:42:8329"}}``
or
``{"eth0": {"mac": "aa:bb:cc:dd:ee:ff", "ipv4": "10.1.1.1/24", "ipv6": "2001:db8::ff00:42:8329"}}``
path
path to the container parent
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt-call -lall mc_lxc_fork.reconfigure foobar nic_opts="{'eth1': {'mac': '00:16:3e:dd:ee:44'}}" memory=4
'''
changes = {}
cpath = get_root_path(path)
path = os.path.join(cpath, name, 'config')
ret = {'name': name,
'comment': 'config for {0} up to date'.format(name),
'result': True,
'changes': changes}
profile = get_container_profile(copy.deepcopy(profile))
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, _marker)
profile_match = profile.pop(key, default)
# let kwarg overrides be the preferred choice
if kw_overrides_match is _marker:
return profile_match
return kw_overrides_match
if nic_opts is not None and not network_profile:
network_profile = DEFAULT_NIC
if autostart is not None:
autostart = select('autostart', autostart)
else:
autostart = 'keep'
if not utsname:
utsname = select('utsname', utsname)
if os.path.exists(path):
old_chunks = read_conf(path, out_format='commented')
make_kw = salt.utils.odict.OrderedDict([
('utsname', utsname),
('rootfs', rootfs),
('autostart', autostart),
('cpu', cpu),
('gateway', gateway),
('cpuset', cpuset),
('cpushare', cpushare),
('network_profile', network_profile),
('nic_opts', nic_opts),
('bridge', bridge)])
# match 0 and none as memory = 0 in lxc config is harmful
if memory:
make_kw['memory'] = memory
kw = salt.utils.odict.OrderedDict()
for key, val in six.iteritems(make_kw):
if val is not None:
kw[key] = val
new_cfg = _config_list(conf_tuples=old_chunks, **kw)
if new_cfg:
edit_conf(path, out_format='commented', lxc_config=new_cfg)
chunks = read_conf(path, out_format='commented')
if old_chunks != chunks:
ret['comment'] = '{0} lxc config updated'.format(name)
if state(name, path=path) == 'running':
cret = reboot(name, path=path)
ret['result'] = cret['result']
return ret
def apply_network_profile(name, network_profile, nic_opts=None, path=None):
'''
.. versionadded:: 2015.5.0
Apply a network profile to a container
network_profile
profile name or default values (dict)
nic_opts
values to override in defaults (dict)
indexed by nic card names
path
path to the container parent
.. versionadded:: 2015.8.0
CLI Examples:
.. code-block:: bash
salt 'minion' lxc.apply_network_profile web1 centos
salt 'minion' lxc.apply_network_profile web1 centos \\
nic_opts="{'eth0': {'mac': 'xx:xx:xx:xx:xx:xx'}}"
salt 'minion' lxc.apply_network_profile web1 \\
"{'eth0': {'mac': 'xx:xx:xx:xx:xx:yy'}}"
nic_opts="{'eth0': {'mac': 'xx:xx:xx:xx:xx:xx'}}"
The special case to disable use of ethernet nics:
.. code-block:: bash
salt 'minion' lxc.apply_network_profile web1 centos \\
"{eth0: {disable: true}}"
'''
cpath = get_root_path(path)
cfgpath = os.path.join(cpath, name, 'config')
before = []
with salt.utils.files.fopen(cfgpath, 'r') as fp_:
for line in fp_:
before.append(line)
lxcconfig = _LXCConfig(name=name, path=path)
old_net = lxcconfig._filter_data('lxc.network')
network_params = {}
for param in _network_conf(
conf_tuples=old_net,
network_profile=network_profile, nic_opts=nic_opts
):
network_params.update(param)
if network_params:
edit_conf(cfgpath, out_format='commented', **network_params)
after = []
with salt.utils.files.fopen(cfgpath, 'r') as fp_:
for line in fp_:
after.append(line)
diff = ''
for line in difflib.unified_diff(before,
after,
fromfile='before',
tofile='after'):
diff += line
return diff
def get_pid(name, path=None):
'''
Returns a container pid.
Throw an exception if the container isn't running.
CLI Example:
.. code-block:: bash
salt '*' lxc.get_pid name
'''
if name not in list_(limit='running', path=path):
raise CommandExecutionError('Container {0} is not running, can\'t determine PID'.format(name))
info = __salt__['cmd.run']('lxc-info -n {0}'.format(name)).split("\n")
pid = [line.split(':')[1].strip() for line in info if re.match(r'\s*PID', line)][0]
return pid
def add_veth(name, interface_name, bridge=None, path=None):
'''
Add a veth to a container.
Note : this function doesn't update the container config, just add the interface at runtime
name
Name of the container
interface_name
Name of the interface in the container
bridge
Name of the bridge to attach the interface to (facultative)
CLI Examples:
.. code-block:: bash
salt '*' lxc.add_veth container_name eth1 br1
salt '*' lxc.add_veth container_name eth1
'''
# Get container init PID
pid = get_pid(name, path=path)
# Generate a ramdom string for veth and ensure that is isn't present on the system
while True:
random_veth = 'veth'+''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(6))
if random_veth not in __salt__['network.interfaces']().keys():
break
# Check prerequisites
if not __salt__['file.directory_exists']('/var/run/'):
raise CommandExecutionError('Directory /var/run required for lxc.add_veth doesn\'t exists')
if not __salt__['file.file_exists']('/proc/{0}/ns/net'.format(pid)):
raise CommandExecutionError('Proc file for container {0} network namespace doesn\'t exists'.format(name))
if not __salt__['file.directory_exists']('/var/run/netns'):
__salt__['file.mkdir']('/var/run/netns')
# Ensure that the symlink is up to date (change on container restart)
if __salt__['file.is_link']('/var/run/netns/{0}'.format(name)):
__salt__['file.remove']('/var/run/netns/{0}'.format(name))
__salt__['file.symlink']('/proc/{0}/ns/net'.format(pid), '/var/run/netns/{0}'.format(name))
# Ensure that interface doesn't exists
interface_exists = 0 == __salt__['cmd.retcode']('ip netns exec {netns} ip address list {interface}'.format(
netns=name,
interface=interface_name
))
if interface_exists:
raise CommandExecutionError('Interface {interface} already exists in {container}'.format(
interface=interface_name,
container=name
))
# Create veth and bring it up
if __salt__['cmd.retcode']('ip link add name {veth} type veth peer name {veth}_c'.format(veth=random_veth)) != 0:
raise CommandExecutionError('Error while creating the veth pair {0}'.format(random_veth))
if __salt__['cmd.retcode']('ip link set dev {0} up'.format(random_veth)) != 0:
raise CommandExecutionError('Error while bringing up host-side veth {0}'.format(random_veth))
# Attach it to the container
attached = 0 == __salt__['cmd.retcode']('ip link set dev {veth}_c netns {container} name {interface_name}'.format(
veth=random_veth,
container=name,
interface_name=interface_name
))
if not attached:
raise CommandExecutionError('Error while attaching the veth {veth} to container {container}'.format(
veth=random_veth,
container=name
))
__salt__['file.remove']('/var/run/netns/{0}'.format(name))
if bridge is not None:
__salt__['bridge.addif'](bridge, random_veth)
|
saltstack/salt
|
salt/modules/lxc.py
|
_rand_cpu_str
|
python
|
def _rand_cpu_str(cpu):
'''
Return a random subset of cpus for the cpuset config
'''
cpu = int(cpu)
avail = __salt__['status.nproc']()
if cpu < avail:
return '0-{0}'.format(avail)
to_set = set()
while len(to_set) < cpu:
choice = random.randint(0, avail - 1)
if choice not in to_set:
to_set.add(six.text_type(choice))
return ','.join(sorted(to_set))
|
Return a random subset of cpus for the cpuset config
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/lxc.py#L686-L699
| null |
# -*- coding: utf-8 -*-
'''
Control Linux Containers via Salt
:depends: lxc package for distribution
lxc >= 1.0 (even beta alpha) is required
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import datetime
import copy
import string
import textwrap
import difflib
import logging
import tempfile
import os
import pipes
import time
import shutil
import re
import random
# Import salt libs
import salt.utils.args
import salt.utils.cloud
import salt.utils.data
import salt.utils.dictupdate
import salt.utils.files
import salt.utils.functools
import salt.utils.hashutils
import salt.utils.network
import salt.utils.odict
import salt.utils.path
import salt.utils.stringutils
from salt.exceptions import CommandExecutionError, SaltInvocationError
import salt.config
from salt.utils.versions import LooseVersion as _LooseVersion
# Import 3rd-party libs
from salt.ext import six
# pylint: disable=import-error,no-name-in-module
from salt.ext.six.moves import range # pylint: disable=redefined-builtin
from salt.ext.six.moves.urllib.parse import urlparse as _urlparse
# pylint: enable=import-error,no-name-in-module
# Set up logging
log = logging.getLogger(__name__)
# Don't shadow built-in's.
__func_alias__ = {
'list_': 'list',
'ls_': 'ls'
}
__virtualname__ = 'lxc'
DEFAULT_NIC = 'eth0'
DEFAULT_BR = 'br0'
SEED_MARKER = '/lxc.initial_seed'
EXEC_DRIVER = 'lxc-attach'
DEFAULT_PATH = '/var/lib/lxc'
_marker = object()
def __virtual__():
if salt.utils.path.which('lxc-start'):
return __virtualname__
# To speed up the whole thing, we decided to not use the
# subshell way and assume things are in place for lxc
# Discussion made by @kiorky and @thatch45
# lxc-version presence is not sufficient, in lxc1.0 alpha
# (precise backports), we have it and it is sufficient
# for the module to execute.
# elif salt.utils.path.which('lxc-version'):
# passed = False
# try:
# passed = subprocess.check_output(
# 'lxc-version').split(':')[1].strip() >= '1.0'
# except Exception:
# pass
# if not passed:
# log.warning('Support for lxc < 1.0 may be incomplete.')
# return 'lxc'
# return False
#
return (False, 'The lxc execution module cannot be loaded: the lxc-start binary is not in the path.')
def get_root_path(path):
'''
Get the configured lxc root for containers
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.get_root_path
'''
if not path:
path = __opts__.get('lxc.root_path', DEFAULT_PATH)
return path
def version():
'''
Return the actual lxc client version
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.version
'''
k = 'lxc.version'
if not __context__.get(k, None):
cversion = __salt__['cmd.run_all']('lxc-info --version')
if not cversion['retcode']:
ver = _LooseVersion(cversion['stdout'])
if ver < _LooseVersion('1.0'):
raise CommandExecutionError('LXC should be at least 1.0')
__context__[k] = "{0}".format(ver)
return __context__.get(k, None)
def _clear_context():
'''
Clear any lxc variables set in __context__
'''
for var in [x for x in __context__ if x.startswith('lxc.')]:
log.trace('Clearing __context__[\'%s\']', var)
__context__.pop(var, None)
def _ip_sort(ip):
'''Ip sorting'''
idx = '001'
if ip == '127.0.0.1':
idx = '200'
if ip == '::1':
idx = '201'
elif '::' in ip:
idx = '100'
return '{0}___{1}'.format(idx, ip)
def search_lxc_bridges():
'''
Search which bridges are potentially available as LXC bridges
CLI Example:
.. code-block:: bash
salt '*' lxc.search_lxc_bridges
'''
bridges = __context__.get('lxc.bridges', None)
# either match not yet called or no bridges were found
# to handle the case where lxc was not installed on the first
# call
if not bridges:
bridges = set()
running_bridges = set()
bridges.add(DEFAULT_BR)
try:
output = __salt__['cmd.run_all']('brctl show')
for line in output['stdout'].splitlines()[1:]:
if not line.startswith(' '):
running_bridges.add(line.split()[0].strip())
except (SaltInvocationError, CommandExecutionError):
pass
for ifc, ip in six.iteritems(
__grains__.get('ip_interfaces', {})
):
if ifc in running_bridges:
bridges.add(ifc)
elif os.path.exists(
'/sys/devices/virtual/net/{0}/bridge'.format(ifc)
):
bridges.add(ifc)
bridges = list(bridges)
# if we found interfaces that have lxc in their names
# we filter them as being the potential lxc bridges
# we also try to default on br0 on other cases
def sort_bridges(a):
pref = 'z'
if 'lxc' in a:
pref = 'a'
elif 'br0' == a:
pref = 'c'
return '{0}_{1}'.format(pref, a)
bridges.sort(key=sort_bridges)
__context__['lxc.bridges'] = bridges
return bridges
def search_lxc_bridge():
'''
Search the first bridge which is potentially available as LXC bridge
CLI Example:
.. code-block:: bash
salt '*' lxc.search_lxc_bridge
'''
return search_lxc_bridges()[0]
def _get_salt_config(config, **kwargs):
if not config:
config = kwargs.get('minion', {})
if not config:
config = {}
config.setdefault('master',
kwargs.get('master',
__opts__.get('master',
__opts__['id'])))
config.setdefault(
'master_port',
kwargs.get('master_port',
__opts__.get('master_port',
__opts__.get('ret_port',
__opts__.get('4506')))))
if not config['master']:
config = {}
return config
def cloud_init_interface(name, vm_=None, **kwargs):
'''
Interface between salt.cloud.lxc driver and lxc.init
``vm_`` is a mapping of vm opts in the salt.cloud format
as documented for the lxc driver.
This can be used either:
- from the salt cloud driver
- because you find the argument to give easier here
than using directly lxc.init
.. warning::
BE REALLY CAREFUL CHANGING DEFAULTS !!!
IT'S A RETRO COMPATIBLE INTERFACE WITH
THE SALT CLOUD DRIVER (ask kiorky).
name
name of the lxc container to create
pub_key
public key to preseed the minion with.
Can be the keycontent or a filepath
priv_key
private key to preseed the minion with.
Can be the keycontent or a filepath
path
path to the container parent directory (default: /var/lib/lxc)
.. versionadded:: 2015.8.0
profile
:ref:`profile <tutorial-lxc-profiles-container>` selection
network_profile
:ref:`network profile <tutorial-lxc-profiles-network>` selection
nic_opts
per interface settings compatibles with
network profile (ipv4/ipv6/link/gateway/mac/netmask)
eg::
- {'eth0': {'mac': '00:16:3e:01:29:40',
'gateway': None, (default)
'link': 'br0', (default)
'gateway': None, (default)
'netmask': '', (default)
'ip': '22.1.4.25'}}
unconditional_install
given to lxc.bootstrap (see relative doc)
force_install
given to lxc.bootstrap (see relative doc)
config
any extra argument for the salt minion config
dnsservers
list of DNS servers to set inside the container
dns_via_dhcp
do not set the dns servers, let them be set by the dhcp.
autostart
autostart the container at boot time
password
administrative password for the container
bootstrap_delay
delay before launching bootstrap script at Container init
.. warning::
Legacy but still supported options:
from_container
which container we use as a template
when running lxc.clone
image
which template do we use when we
are using lxc.create. This is the default
mode unless you specify something in from_container
backing
which backing store to use.
Values can be: overlayfs, dir(default), lvm, zfs, brtfs
fstype
When using a blockdevice level backing store,
which filesystem to use on
size
When using a blockdevice level backing store,
which size for the filesystem to use on
snapshot
Use snapshot when cloning the container source
vgname
if using LVM: vgname
lvname
if using LVM: lvname
thinpool:
if using LVM: thinpool
ip
ip for the primary nic
mac
mac address for the primary nic
netmask
netmask for the primary nic (24)
= ``vm_.get('netmask', '24')``
bridge
bridge for the primary nic (lxcbr0)
gateway
network gateway for the container
additional_ips
additional ips which will be wired on the main bridge (br0)
which is connected to internet.
Be aware that you may use manual virtual mac addresses
providen by you provider (online, ovh, etc).
This is a list of mappings {ip: '', mac: '', netmask:''}
Set gateway to None and an interface with a gateway
to escape from another interface that eth0.
eg::
- {'mac': '00:16:3e:01:29:40',
'gateway': None, (default)
'link': 'br0', (default)
'netmask': '', (default)
'ip': '22.1.4.25'}
users
administrative users for the container
default: [root] and [root, ubuntu] on ubuntu
default_nic
name of the first interface, you should
really not override this
CLI Example:
.. code-block:: bash
salt '*' lxc.cloud_init_interface foo
'''
if vm_ is None:
vm_ = {}
vm_ = copy.deepcopy(vm_)
vm_ = salt.utils.dictupdate.update(vm_, kwargs)
profile_data = copy.deepcopy(
vm_.get('lxc_profile',
vm_.get('profile', {})))
if not isinstance(profile_data, (dict, six.string_types)):
profile_data = {}
profile = get_container_profile(profile_data)
def _cloud_get(k, default=None):
return vm_.get(k, profile.get(k, default))
if name is None:
name = vm_['name']
# if we are on ubuntu, default to ubuntu
default_template = ''
if __grains__.get('os', '') in ['Ubuntu']:
default_template = 'ubuntu'
image = _cloud_get('image')
if not image:
_cloud_get('template', default_template)
backing = _cloud_get('backing', 'dir')
if image:
profile['template'] = image
vgname = _cloud_get('vgname', None)
if vgname:
profile['vgname'] = vgname
if backing:
profile['backing'] = backing
snapshot = _cloud_get('snapshot', False)
autostart = bool(_cloud_get('autostart', True))
dnsservers = _cloud_get('dnsservers', [])
dns_via_dhcp = _cloud_get('dns_via_dhcp', True)
password = _cloud_get('password', 's3cr3t')
password_encrypted = _cloud_get('password_encrypted', False)
fstype = _cloud_get('fstype', None)
lvname = _cloud_get('lvname', None)
thinpool = _cloud_get('thinpool', None)
pub_key = _cloud_get('pub_key', None)
priv_key = _cloud_get('priv_key', None)
size = _cloud_get('size', '20G')
script = _cloud_get('script', None)
script_args = _cloud_get('script_args', None)
users = _cloud_get('users', None)
if users is None:
users = []
ssh_username = _cloud_get('ssh_username', None)
if ssh_username and (ssh_username not in users):
users.append(ssh_username)
network_profile = _cloud_get('network_profile', None)
nic_opts = kwargs.get('nic_opts', None)
netmask = _cloud_get('netmask', '24')
path = _cloud_get('path', None)
bridge = _cloud_get('bridge', None)
gateway = _cloud_get('gateway', None)
unconditional_install = _cloud_get('unconditional_install', False)
force_install = _cloud_get('force_install', True)
config = _get_salt_config(_cloud_get('config', {}), **vm_)
default_nic = _cloud_get('default_nic', DEFAULT_NIC)
# do the interface with lxc.init mainly via nic_opts
# to avoid extra and confusing extra use cases.
if not isinstance(nic_opts, dict):
nic_opts = salt.utils.odict.OrderedDict()
# have a reference to the default nic
eth0 = nic_opts.setdefault(default_nic,
salt.utils.odict.OrderedDict())
# lxc config is based of ifc order, be sure to use odicts.
if not isinstance(nic_opts, salt.utils.odict.OrderedDict):
bnic_opts = salt.utils.odict.OrderedDict()
bnic_opts.update(nic_opts)
nic_opts = bnic_opts
gw = None
# legacy salt.cloud scheme for network interfaces settings support
bridge = _cloud_get('bridge', None)
ip = _cloud_get('ip', None)
mac = _cloud_get('mac', None)
if ip:
fullip = ip
if netmask:
fullip += '/{0}'.format(netmask)
eth0['ipv4'] = fullip
if mac is not None:
eth0['mac'] = mac
for ix, iopts in enumerate(_cloud_get("additional_ips", [])):
ifh = "eth{0}".format(ix+1)
ethx = nic_opts.setdefault(ifh, {})
if gw is None:
gw = iopts.get('gateway', ethx.get('gateway', None))
if gw:
# only one and only one default gateway is allowed !
eth0.pop('gateway', None)
gateway = None
# even if the gateway if on default "eth0" nic
# and we popped it will work
# as we reinject or set it here.
ethx['gateway'] = gw
elink = iopts.get('link', ethx.get('link', None))
if elink:
ethx['link'] = elink
# allow dhcp
aip = iopts.get('ipv4', iopts.get('ip', None))
if aip:
ethx['ipv4'] = aip
nm = iopts.get('netmask', '')
if nm:
ethx['ipv4'] += '/{0}'.format(nm)
for i in ('mac', 'hwaddr'):
if i in iopts:
ethx['mac'] = iopts[i]
break
if 'mac' not in ethx:
ethx['mac'] = salt.utils.network.gen_mac()
# last round checking for unique gateway and such
gw = None
for ethx in [a for a in nic_opts]:
ndata = nic_opts[ethx]
if gw:
ndata.pop('gateway', None)
if 'gateway' in ndata:
gw = ndata['gateway']
gateway = None
# only use a default bridge / gateway if we configured them
# via the legacy salt cloud configuration style.
# On other cases, we should rely on settings provided by the new
# salt lxc network profile style configuration which can
# be also be overridden or a per interface basis via the nic_opts dict.
if bridge:
eth0['link'] = bridge
if gateway:
eth0['gateway'] = gateway
#
lxc_init_interface = {}
lxc_init_interface['name'] = name
lxc_init_interface['config'] = config
lxc_init_interface['memory'] = _cloud_get('memory', 0) # nolimit
lxc_init_interface['pub_key'] = pub_key
lxc_init_interface['priv_key'] = priv_key
lxc_init_interface['nic_opts'] = nic_opts
for clone_from in ['clone_from', 'clone', 'from_container']:
# clone_from should default to None if not available
lxc_init_interface['clone_from'] = _cloud_get(clone_from, None)
if lxc_init_interface['clone_from'] is not None:
break
lxc_init_interface['profile'] = profile
lxc_init_interface['snapshot'] = snapshot
lxc_init_interface['dnsservers'] = dnsservers
lxc_init_interface['fstype'] = fstype
lxc_init_interface['path'] = path
lxc_init_interface['vgname'] = vgname
lxc_init_interface['size'] = size
lxc_init_interface['lvname'] = lvname
lxc_init_interface['thinpool'] = thinpool
lxc_init_interface['force_install'] = force_install
lxc_init_interface['unconditional_install'] = (
unconditional_install
)
lxc_init_interface['bootstrap_url'] = script
lxc_init_interface['bootstrap_args'] = script_args
lxc_init_interface['bootstrap_shell'] = _cloud_get('bootstrap_shell', 'sh')
lxc_init_interface['bootstrap_delay'] = _cloud_get('bootstrap_delay', None)
lxc_init_interface['autostart'] = autostart
lxc_init_interface['users'] = users
lxc_init_interface['password'] = password
lxc_init_interface['password_encrypted'] = password_encrypted
# be sure not to let objects goes inside the return
# as this return will be msgpacked for use in the runner !
lxc_init_interface['network_profile'] = network_profile
for i in ['cpu', 'cpuset', 'cpushare']:
if _cloud_get(i, None):
try:
lxc_init_interface[i] = vm_[i]
except KeyError:
lxc_init_interface[i] = profile[i]
return lxc_init_interface
def _get_profile(key, name, **kwargs):
if isinstance(name, dict):
profilename = name.pop('name', None)
return _get_profile(key, profilename, **name)
if name is None:
profile_match = {}
else:
profile_match = \
__salt__['config.get'](
'lxc.{1}:{0}'.format(name, key),
default=None,
merge='recurse'
)
if profile_match is None:
# No matching profile, make the profile an empty dict so that
# overrides can be applied below.
profile_match = {}
if not isinstance(profile_match, dict):
raise CommandExecutionError('lxc.{0} must be a dictionary'.format(key))
# Overlay the kwargs to override matched profile data
overrides = salt.utils.args.clean_kwargs(**copy.deepcopy(kwargs))
profile_match = salt.utils.dictupdate.update(
copy.deepcopy(profile_match),
overrides
)
return profile_match
def get_container_profile(name=None, **kwargs):
'''
.. versionadded:: 2015.5.0
Gather a pre-configured set of container configuration parameters. If no
arguments are passed, an empty profile is returned.
Profiles can be defined in the minion or master config files, or in pillar
or grains, and are loaded using :mod:`config.get
<salt.modules.config.get>`. The key under which LXC profiles must be
configured is ``lxc.container_profile.profile_name``. An example container
profile would be as follows:
.. code-block:: yaml
lxc.container_profile:
ubuntu:
template: ubuntu
backing: lvm
vgname: lxc
size: 1G
Parameters set in a profile can be overridden by passing additional
container creation arguments (such as the ones passed to :mod:`lxc.create
<salt.modules.lxc.create>`) to this function.
A profile can be defined either as the name of the profile, or a dictionary
of variable names and values. See the :ref:`LXC Tutorial
<tutorial-lxc-profiles>` for more information on how to use LXC profiles.
CLI Example:
.. code-block:: bash
salt-call lxc.get_container_profile centos
salt-call lxc.get_container_profile ubuntu template=ubuntu backing=overlayfs
'''
profile = _get_profile('container_profile', name, **kwargs)
return profile
def get_network_profile(name=None, **kwargs):
'''
.. versionadded:: 2015.5.0
Gather a pre-configured set of network configuration parameters. If no
arguments are passed, the following default profile is returned:
.. code-block:: python
{'eth0': {'link': 'br0', 'type': 'veth', 'flags': 'up'}}
Profiles can be defined in the minion or master config files, or in pillar
or grains, and are loaded using :mod:`config.get
<salt.modules.config.get>`. The key under which LXC profiles must be
configured is ``lxc.network_profile``. An example network profile would be
as follows:
.. code-block:: yaml
lxc.network_profile.centos:
eth0:
link: br0
type: veth
flags: up
To disable networking entirely:
.. code-block:: yaml
lxc.network_profile.centos:
eth0:
disable: true
Parameters set in a profile can be overridden by passing additional
arguments to this function.
A profile can be passed either as the name of the profile, or a
dictionary of variable names and values. See the :ref:`LXC Tutorial
<tutorial-lxc-profiles>` for more information on how to use network
profiles.
.. warning::
The ``ipv4``, ``ipv6``, ``gateway``, and ``link`` (bridge) settings in
network profiles will only work if the container doesn't redefine the
network configuration (for example in
``/etc/sysconfig/network-scripts/ifcfg-<interface_name>`` on
RHEL/CentOS, or ``/etc/network/interfaces`` on Debian/Ubuntu/etc.)
CLI Example:
.. code-block:: bash
salt-call lxc.get_network_profile default
'''
profile = _get_profile('network_profile', name, **kwargs)
return profile
def _network_conf(conf_tuples=None, **kwargs):
'''
Network configuration defaults
network_profile
as for containers, we can either call this function
either with a network_profile dict or network profile name
in the kwargs
nic_opts
overrides or extra nics in the form {nic_name: {set: tings}
'''
nic = kwargs.get('network_profile', None)
ret = []
nic_opts = kwargs.get('nic_opts', {})
if nic_opts is None:
# coming from elsewhere
nic_opts = {}
if not conf_tuples:
conf_tuples = []
old = _get_veths(conf_tuples)
if not old:
old = {}
# if we have a profile name, get the profile and load the network settings
# this will obviously by default look for a profile called "eth0"
# or by what is defined in nic_opts
# and complete each nic settings by sane defaults
if nic and isinstance(nic, (six.string_types, dict)):
nicp = get_network_profile(nic)
else:
nicp = {}
if DEFAULT_NIC not in nicp:
nicp[DEFAULT_NIC] = {}
kwargs = copy.deepcopy(kwargs)
gateway = kwargs.pop('gateway', None)
bridge = kwargs.get('bridge', None)
if nic_opts:
for dev, args in six.iteritems(nic_opts):
ethx = nicp.setdefault(dev, {})
try:
ethx = salt.utils.dictupdate.update(ethx, args)
except AttributeError:
raise SaltInvocationError('Invalid nic_opts configuration')
ifs = [a for a in nicp]
ifs += [a for a in old if a not in nicp]
ifs.sort()
gateway_set = False
for dev in ifs:
args = nicp.get(dev, {})
opts = nic_opts.get(dev, {}) if nic_opts else {}
old_if = old.get(dev, {})
disable = opts.get('disable', args.get('disable', False))
if disable:
continue
mac = opts.get('mac',
opts.get('hwaddr',
args.get('mac',
args.get('hwaddr', ''))))
type_ = opts.get('type', args.get('type', ''))
flags = opts.get('flags', args.get('flags', ''))
link = opts.get('link', args.get('link', ''))
ipv4 = opts.get('ipv4', args.get('ipv4', ''))
ipv6 = opts.get('ipv6', args.get('ipv6', ''))
infos = salt.utils.odict.OrderedDict([
('lxc.network.type', {
'test': not type_,
'value': type_,
'old': old_if.get('lxc.network.type'),
'default': 'veth'}),
('lxc.network.name', {
'test': False,
'value': dev,
'old': dev,
'default': dev}),
('lxc.network.flags', {
'test': not flags,
'value': flags,
'old': old_if.get('lxc.network.flags'),
'default': 'up'}),
('lxc.network.link', {
'test': not link,
'value': link,
'old': old_if.get('lxc.network.link'),
'default': search_lxc_bridge()}),
('lxc.network.hwaddr', {
'test': not mac,
'value': mac,
'old': old_if.get('lxc.network.hwaddr'),
'default': salt.utils.network.gen_mac()}),
('lxc.network.ipv4', {
'test': not ipv4,
'value': ipv4,
'old': old_if.get('lxc.network.ipv4', ''),
'default': None}),
('lxc.network.ipv6', {
'test': not ipv6,
'value': ipv6,
'old': old_if.get('lxc.network.ipv6', ''),
'default': None})])
# for each parameter, if not explicitly set, the
# config value present in the LXC configuration should
# take precedence over the profile configuration
for info in list(infos.keys()):
bundle = infos[info]
if bundle['test']:
if bundle['old']:
bundle['value'] = bundle['old']
elif bundle['default']:
bundle['value'] = bundle['default']
for info, data in six.iteritems(infos):
if data['value']:
ret.append({info: data['value']})
for key, val in six.iteritems(args):
if key == 'link' and bridge:
val = bridge
val = opts.get(key, val)
if key in [
'type', 'flags', 'name',
'gateway', 'mac', 'link', 'ipv4', 'ipv6'
]:
continue
ret.append({'lxc.network.{0}'.format(key): val})
# gateway (in automode) must be appended following network conf !
if not gateway:
gateway = args.get('gateway', None)
if gateway is not None and not gateway_set:
ret.append({'lxc.network.ipv4.gateway': gateway})
# only one network gateway ;)
gateway_set = True
# normally, this won't happen
# set the gateway if specified even if we did
# not managed the network underlying
if gateway is not None and not gateway_set:
ret.append({'lxc.network.ipv4.gateway': gateway})
# only one network gateway ;)
gateway_set = True
new = _get_veths(ret)
# verify that we did not loose the mac settings
for iface in [a for a in new]:
ndata = new[iface]
nmac = ndata.get('lxc.network.hwaddr', '')
ntype = ndata.get('lxc.network.type', '')
omac, otype = '', ''
if iface in old:
odata = old[iface]
omac = odata.get('lxc.network.hwaddr', '')
otype = odata.get('lxc.network.type', '')
# default for network type is setted here
# attention not to change the network type
# without a good and explicit reason to.
if otype and not ntype:
ntype = otype
if not ntype:
ntype = 'veth'
new[iface]['lxc.network.type'] = ntype
if omac and not nmac:
new[iface]['lxc.network.hwaddr'] = omac
ret = []
for val in six.itervalues(new):
for row in val:
ret.append(salt.utils.odict.OrderedDict([(row, val[row])]))
# on old versions of lxc, still support the gateway auto mode
# if we didn't explicitly say no to
# (lxc.network.ipv4.gateway: auto)
if _LooseVersion(version()) <= _LooseVersion('1.0.7') and \
True not in ['lxc.network.ipv4.gateway' in a for a in ret] and \
True in ['lxc.network.ipv4' in a for a in ret]:
ret.append({'lxc.network.ipv4.gateway': 'auto'})
return ret
def _get_lxc_default_data(**kwargs):
kwargs = copy.deepcopy(kwargs)
ret = {}
for k in ['utsname', 'rootfs']:
val = kwargs.get(k, None)
if val is not None:
ret['lxc.{0}'.format(k)] = val
autostart = kwargs.get('autostart')
# autostart can have made in kwargs, but with the None
# value which is invalid, we need an explicit boolean
# autostart = on is the default.
if autostart is None:
autostart = True
# we will set the regular lxc marker to restart container at
# machine (re)boot only if we did not explicitly ask
# not to touch to the autostart settings via
# autostart == 'keep'
if autostart != 'keep':
if autostart:
ret['lxc.start.auto'] = '1'
else:
ret['lxc.start.auto'] = '0'
memory = kwargs.get('memory')
if memory is not None:
# converting the config value from MB to bytes
ret['lxc.cgroup.memory.limit_in_bytes'] = memory * 1024 * 1024
cpuset = kwargs.get('cpuset')
if cpuset:
ret['lxc.cgroup.cpuset.cpus'] = cpuset
cpushare = kwargs.get('cpushare')
cpu = kwargs.get('cpu')
if cpushare:
ret['lxc.cgroup.cpu.shares'] = cpushare
if cpu and not cpuset:
ret['lxc.cgroup.cpuset.cpus'] = _rand_cpu_str(cpu)
return ret
def _config_list(conf_tuples=None, only_net=False, **kwargs):
'''
Return a list of dicts from the salt level configurations
conf_tuples
_LXCConfig compatible list of entries which can contain
- string line
- tuple (lxc config param,value)
- dict of one entry: {lxc config param: value)
only_net
by default we add to the tuples a reflection of both
the real config if avalaible and a certain amount of
default values like the cpu parameters, the memory
and etc.
On the other hand, we also no matter the case reflect
the network configuration computed from the actual config if
available and given values.
if no_default_loads is set, we will only
reflect the network configuration back to the conf tuples
list
'''
# explicit cast
only_net = bool(only_net)
if not conf_tuples:
conf_tuples = []
kwargs = copy.deepcopy(kwargs)
ret = []
if not only_net:
default_data = _get_lxc_default_data(**kwargs)
for k, val in six.iteritems(default_data):
ret.append({k: val})
net_datas = _network_conf(conf_tuples=conf_tuples, **kwargs)
ret.extend(net_datas)
return ret
def _get_veths(net_data):
'''
Parse the nic setup inside lxc conf tuples back to a dictionary indexed by
network interface
'''
if isinstance(net_data, dict):
net_data = list(net_data.items())
nics = salt.utils.odict.OrderedDict()
current_nic = salt.utils.odict.OrderedDict()
no_names = True
for item in net_data:
if item and isinstance(item, dict):
item = list(item.items())[0]
# skip LXC configuration comment lines, and play only with tuples conf
elif isinstance(item, six.string_types):
# deal with reflection of commented lxc configs
sitem = item.strip()
if sitem.startswith('#') or not sitem:
continue
elif '=' in item:
item = tuple([a.strip() for a in item.split('=', 1)])
if item[0] == 'lxc.network.type':
current_nic = salt.utils.odict.OrderedDict()
if item[0] == 'lxc.network.name':
no_names = False
nics[item[1].strip()] = current_nic
current_nic[item[0].strip()] = item[1].strip()
# if not ethernet card name has been collected, assuming we collected
# data for eth0
if no_names and current_nic:
nics[DEFAULT_NIC] = current_nic
return nics
class _LXCConfig(object):
'''
LXC configuration data
'''
pattern = re.compile(r'^(\S+)(\s*)(=)(\s*)(.*)')
non_interpretable_pattern = re.compile(r'^((#.*)|(\s*))$')
def __init__(self, **kwargs):
kwargs = copy.deepcopy(kwargs)
self.name = kwargs.pop('name', None)
path = get_root_path(kwargs.get('path', None))
self.data = []
if self.name:
self.path = os.path.join(path, self.name, 'config')
if os.path.isfile(self.path):
with salt.utils.files.fopen(self.path) as fhr:
for line in salt.utils.data.decode(fhr.readlines()):
match = self.pattern.findall((line.strip()))
if match:
self.data.append((match[0][0], match[0][-1]))
match = self.non_interpretable_pattern.findall(
(line.strip()))
if match:
self.data.append(('', match[0][0]))
else:
self.path = None
def _replace(key, val):
if val:
self._filter_data(key)
self.data.append((key, val))
default_data = _get_lxc_default_data(**kwargs)
for key, val in six.iteritems(default_data):
_replace(key, val)
old_net = self._filter_data('lxc.network')
net_datas = _network_conf(conf_tuples=old_net, **kwargs)
if net_datas:
for row in net_datas:
self.data.extend(list(row.items()))
# be sure to reset harmful settings
for idx in ['lxc.cgroup.memory.limit_in_bytes']:
if not default_data.get(idx):
self._filter_data(idx)
def as_string(self):
chunks = ('{0[0]}{1}{0[1]}'.format(item, (' = ' if item[0] else '')) for item in self.data)
return '\n'.join(chunks) + '\n'
def write(self):
if self.path:
content = self.as_string()
# 2 step rendering to be sure not to open/wipe the config
# before as_string succeeds.
with salt.utils.files.fopen(self.path, 'w') as fic:
fic.write(salt.utils.stringutils.to_str(content))
fic.flush()
def tempfile(self):
# this might look like the function name is shadowing the
# module, but it's not since the method belongs to the class
ntf = tempfile.NamedTemporaryFile()
ntf.write(self.as_string())
ntf.flush()
return ntf
def _filter_data(self, pattern):
'''
Removes parameters which match the pattern from the config data
'''
removed = []
filtered = []
for param in self.data:
if not param[0].startswith(pattern):
filtered.append(param)
else:
removed.append(param)
self.data = filtered
return removed
def _get_base(**kwargs):
'''
If the needed base does not exist, then create it, if it does exist
create nothing and return the name of the base lxc container so
it can be cloned.
'''
profile = get_container_profile(copy.deepcopy(kwargs.get('profile')))
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, _marker)
profile_match = profile.pop(key, default)
# let kwarg overrides be the preferred choice
if kw_overrides_match is _marker:
return profile_match
return kw_overrides_match
template = select('template')
image = select('image')
vgname = select('vgname')
path = kwargs.get('path', None)
# remove the above three variables from kwargs, if they exist, to avoid
# duplicates if create() is invoked below.
for param in ('path', 'image', 'vgname', 'template'):
kwargs.pop(param, None)
if image:
proto = _urlparse(image).scheme
img_tar = __salt__['cp.cache_file'](image)
img_name = os.path.basename(img_tar)
hash_ = salt.utils.hashutils.get_hash(
img_tar,
__salt__['config.get']('hash_type'))
name = '__base_{0}_{1}_{2}'.format(proto, img_name, hash_)
if not exists(name, path=path):
create(name, template=template, image=image,
path=path, vgname=vgname, **kwargs)
if vgname:
rootfs = os.path.join('/dev', vgname, name)
edit_conf(info(name, path=path)['config'],
out_format='commented', **{'lxc.rootfs': rootfs})
return name
elif template:
name = '__base_{0}'.format(template)
if not exists(name, path=path):
create(name, template=template, image=image, path=path,
vgname=vgname, **kwargs)
if vgname:
rootfs = os.path.join('/dev', vgname, name)
edit_conf(info(name, path=path)['config'],
out_format='commented', **{'lxc.rootfs': rootfs})
return name
return ''
def init(name,
config=None,
cpuset=None,
cpushare=None,
memory=None,
profile=None,
network_profile=None,
nic_opts=None,
cpu=None,
autostart=True,
password=None,
password_encrypted=None,
users=None,
dnsservers=None,
searchdomains=None,
bridge=None,
gateway=None,
pub_key=None,
priv_key=None,
force_install=False,
unconditional_install=False,
bootstrap_delay=None,
bootstrap_args=None,
bootstrap_shell=None,
bootstrap_url=None,
**kwargs):
'''
Initialize a new container.
This is a partial idempotent function as if it is already provisioned, we
will reset a bit the lxc configuration file but much of the hard work will
be escaped as markers will prevent re-execution of harmful tasks.
name
Name of the container
image
A tar archive to use as the rootfs for the container. Conflicts with
the ``template`` argument.
cpus
Select a random number of cpu cores and assign it to the cpuset, if the
cpuset option is set then this option will be ignored
cpuset
Explicitly define the cpus this container will be bound to
cpushare
cgroups cpu shares
autostart
autostart container on reboot
memory
cgroups memory limit, in MB
.. versionchanged:: 2015.5.0
If no value is passed, no limit is set. In earlier Salt versions,
not passing this value causes a 1024MB memory limit to be set, and
it was necessary to pass ``memory=0`` to set no limit.
gateway
the ipv4 gateway to use
the default does nothing more than lxcutils does
bridge
the bridge to use
the default does nothing more than lxcutils does
network_profile
Network profile to use for the container
.. versionadded:: 2015.5.0
nic_opts
Extra options for network interfaces, will override
``{"eth0": {"hwaddr": "aa:bb:cc:dd:ee:ff", "ipv4": "10.1.1.1", "ipv6": "2001:db8::ff00:42:8329"}}``
or
``{"eth0": {"hwaddr": "aa:bb:cc:dd:ee:ff", "ipv4": "10.1.1.1/24", "ipv6": "2001:db8::ff00:42:8329"}}``
users
Users for which the password defined in the ``password`` param should
be set. Can be passed as a comma separated list or a python list.
Defaults to just the ``root`` user.
password
Set the initial password for the users defined in the ``users``
parameter
password_encrypted : False
Set to ``True`` to denote a password hash instead of a plaintext
password
.. versionadded:: 2015.5.0
profile
A LXC profile (defined in config or pillar).
This can be either a real profile mapping or a string
to retrieve it in configuration
start
Start the newly-created container
dnsservers
list of dns servers to set in the container, default [] (no setting)
seed
Seed the container with the minion config. Default: ``True``
install
If salt-minion is not already installed, install it. Default: ``True``
config
Optional config parameters. By default, the id is set to
the name of the container.
master
salt master (default to minion's master)
master_port
salt master port (default to minion's master port)
pub_key
Explicit public key to preseed the minion with (optional).
This can be either a filepath or a string representing the key
priv_key
Explicit private key to preseed the minion with (optional).
This can be either a filepath or a string representing the key
approve_key
If explicit preseeding is not used;
Attempt to request key approval from the master. Default: ``True``
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
clone_from
Original from which to use a clone operation to create the container.
Default: ``None``
bootstrap_delay
Delay in seconds between end of container creation and bootstrapping.
Useful when waiting for container to obtain a DHCP lease.
.. versionadded:: 2015.5.0
bootstrap_url
See lxc.bootstrap
bootstrap_shell
See lxc.bootstrap
bootstrap_args
See lxc.bootstrap
force_install
Force installation even if salt-minion is detected,
this is the way to run vendor bootstrap scripts even
if a salt minion is already present in the container
unconditional_install
Run the script even if the container seems seeded
CLI Example:
.. code-block:: bash
salt 'minion' lxc.init name [cpuset=cgroups_cpuset] \\
[cpushare=cgroups_cpushare] [memory=cgroups_memory] \\
[nic=nic_profile] [profile=lxc_profile] \\
[nic_opts=nic_opts] [start=(True|False)] \\
[seed=(True|False)] [install=(True|False)] \\
[config=minion_config] [approve_key=(True|False) \\
[clone_from=original] [autostart=True] \\
[priv_key=/path_or_content] [pub_key=/path_or_content] \\
[bridge=lxcbr0] [gateway=10.0.3.1] \\
[dnsservers[dns1,dns2]] \\
[users=[foo]] [password='secret'] \\
[password_encrypted=(True|False)]
'''
ret = {'name': name,
'changes': {}}
profile = get_container_profile(copy.deepcopy(profile))
if not network_profile:
network_profile = profile.get('network_profile')
if not network_profile:
network_profile = DEFAULT_NIC
# Changes is a pointer to changes_dict['init']. This method is used so that
# we can have a list of changes as they are made, providing an ordered list
# of things that were changed.
changes_dict = {'init': []}
changes = changes_dict.get('init')
if users is None:
users = []
dusers = ['root']
for user in dusers:
if user not in users:
users.append(user)
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, _marker)
profile_match = profile.pop(key, default)
# let kwarg overrides be the preferred choice
if kw_overrides_match is _marker:
return profile_match
return kw_overrides_match
path = select('path')
bpath = get_root_path(path)
state_pre = state(name, path=path)
tvg = select('vgname')
vgname = tvg if tvg else __salt__['config.get']('lxc.vgname')
start_ = select('start', True)
autostart = select('autostart', autostart)
seed = select('seed', True)
install = select('install', True)
seed_cmd = select('seed_cmd')
salt_config = _get_salt_config(config, **kwargs)
approve_key = select('approve_key', True)
clone_from = select('clone_from')
# If using a volume group then set up to make snapshot cow clones
if vgname and not clone_from:
try:
kwargs['vgname'] = vgname
clone_from = _get_base(profile=profile, **kwargs)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = exc.strerror
if changes:
ret['changes'] = changes_dict
return ret
if not kwargs.get('snapshot') is False:
kwargs['snapshot'] = True
does_exist = exists(name, path=path)
to_reboot = False
remove_seed_marker = False
if does_exist:
pass
elif clone_from:
remove_seed_marker = True
try:
clone(name, clone_from, profile=profile, **kwargs)
changes.append({'create': 'Container cloned'})
except (SaltInvocationError, CommandExecutionError) as exc:
if 'already exists' in exc.strerror:
changes.append({'create': 'Container already exists'})
else:
ret['result'] = False
ret['comment'] = exc.strerror
if changes:
ret['changes'] = changes_dict
return ret
cfg = _LXCConfig(name=name, network_profile=network_profile,
nic_opts=nic_opts, bridge=bridge, path=path,
gateway=gateway, autostart=autostart,
cpuset=cpuset, cpushare=cpushare, memory=memory)
old_chunks = read_conf(cfg.path, out_format='commented')
cfg.write()
chunks = read_conf(cfg.path, out_format='commented')
if old_chunks != chunks:
to_reboot = True
else:
remove_seed_marker = True
cfg = _LXCConfig(network_profile=network_profile,
nic_opts=nic_opts, cpuset=cpuset, path=path,
bridge=bridge, gateway=gateway,
autostart=autostart,
cpushare=cpushare, memory=memory)
with cfg.tempfile() as cfile:
try:
create(name, config=cfile.name, profile=profile, **kwargs)
changes.append({'create': 'Container created'})
except (SaltInvocationError, CommandExecutionError) as exc:
if 'already exists' in exc.strerror:
changes.append({'create': 'Container already exists'})
else:
ret['comment'] = exc.strerror
if changes:
ret['changes'] = changes_dict
return ret
cpath = os.path.join(bpath, name, 'config')
old_chunks = []
if os.path.exists(cpath):
old_chunks = read_conf(cpath, out_format='commented')
new_cfg = _config_list(conf_tuples=old_chunks,
cpu=cpu,
network_profile=network_profile,
nic_opts=nic_opts, bridge=bridge,
cpuset=cpuset, cpushare=cpushare,
memory=memory)
if new_cfg:
edit_conf(cpath, out_format='commented', lxc_config=new_cfg)
chunks = read_conf(cpath, out_format='commented')
if old_chunks != chunks:
to_reboot = True
# last time to be sure any of our property is correctly applied
cfg = _LXCConfig(name=name, network_profile=network_profile,
nic_opts=nic_opts, bridge=bridge, path=path,
gateway=gateway, autostart=autostart,
cpuset=cpuset, cpushare=cpushare, memory=memory)
old_chunks = []
if os.path.exists(cfg.path):
old_chunks = read_conf(cfg.path, out_format='commented')
cfg.write()
chunks = read_conf(cfg.path, out_format='commented')
if old_chunks != chunks:
changes.append({'config': 'Container configuration updated'})
to_reboot = True
if to_reboot:
try:
stop(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
if changes:
ret['changes'] = changes_dict
return ret
if not does_exist or (does_exist and state(name, path=path) != 'running'):
try:
start(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
if changes:
ret['changes'] = changes_dict
return ret
if remove_seed_marker:
run(name,
'rm -f \'{0}\''.format(SEED_MARKER),
path=path,
chroot_fallback=False,
python_shell=False)
# set the default user/password, only the first time
if ret.get('result', True) and password:
gid = '/.lxc.initial_pass'
gids = [gid,
'/lxc.initial_pass',
'/.lxc.{0}.initial_pass'.format(name)]
if not any(retcode(name,
'test -e "{0}"'.format(x),
chroot_fallback=True,
path=path,
ignore_retcode=True) == 0
for x in gids):
# think to touch the default user generated by default templates
# which has a really unsecure passwords...
# root is defined as a member earlier in the code
for default_user in ['ubuntu']:
if (
default_user not in users and
retcode(name,
'id {0}'.format(default_user),
python_shell=False,
path=path,
chroot_fallback=True,
ignore_retcode=True) == 0
):
users.append(default_user)
for user in users:
try:
cret = set_password(name,
users=[user],
path=path,
password=password,
encrypted=password_encrypted)
except (SaltInvocationError, CommandExecutionError) as exc:
msg = '{0}: Failed to set password'.format(
user) + exc.strerror
# only hardfail in unrecoverable situation:
# root cannot be setted up
if user == 'root':
ret['comment'] = msg
ret['result'] = False
else:
log.debug(msg)
if ret.get('result', True):
changes.append({'password': 'Password(s) updated'})
if retcode(name,
('sh -c \'touch "{0}"; test -e "{0}"\''
.format(gid)),
path=path,
chroot_fallback=True,
ignore_retcode=True) != 0:
ret['comment'] = 'Failed to set password marker'
changes[-1]['password'] += '. ' + ret['comment'] + '.'
ret['result'] = False
# set dns servers if any, only the first time
if ret.get('result', True) and dnsservers:
# retro compatibility, test also old markers
gid = '/.lxc.initial_dns'
gids = [gid,
'/lxc.initial_dns',
'/lxc.{0}.initial_dns'.format(name)]
if not any(retcode(name,
'test -e "{0}"'.format(x),
chroot_fallback=True,
path=path,
ignore_retcode=True) == 0
for x in gids):
try:
set_dns(name,
path=path,
dnsservers=dnsservers,
searchdomains=searchdomains)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Failed to set DNS: ' + exc.strerror
ret['result'] = False
else:
changes.append({'dns': 'DNS updated'})
if retcode(name,
('sh -c \'touch "{0}"; test -e "{0}"\''
.format(gid)),
chroot_fallback=True,
path=path,
ignore_retcode=True) != 0:
ret['comment'] = 'Failed to set DNS marker'
changes[-1]['dns'] += '. ' + ret['comment'] + '.'
ret['result'] = False
# retro compatibility, test also old markers
if remove_seed_marker:
run(name,
'rm -f \'{0}\''.format(SEED_MARKER),
path=path,
python_shell=False)
gid = '/.lxc.initial_seed'
gids = [gid, '/lxc.initial_seed']
if (
any(retcode(name,
'test -e {0}'.format(x),
path=path,
chroot_fallback=True,
ignore_retcode=True) == 0
for x in gids) or not ret.get('result', True)
):
pass
elif seed or seed_cmd:
if seed:
try:
result = bootstrap(
name, config=salt_config, path=path,
approve_key=approve_key,
pub_key=pub_key, priv_key=priv_key,
install=install,
force_install=force_install,
unconditional_install=unconditional_install,
bootstrap_delay=bootstrap_delay,
bootstrap_url=bootstrap_url,
bootstrap_shell=bootstrap_shell,
bootstrap_args=bootstrap_args)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Bootstrap failed: ' + exc.strerror
ret['result'] = False
else:
if not result:
ret['comment'] = ('Bootstrap failed, see minion log for '
'more information')
ret['result'] = False
else:
changes.append(
{'bootstrap': 'Container successfully bootstrapped'}
)
elif seed_cmd:
try:
result = __salt__[seed_cmd](info(name, path=path)['rootfs'],
name,
salt_config)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = ('Bootstrap via seed_cmd \'{0}\' failed: {1}'
.format(seed_cmd, exc.strerror))
ret['result'] = False
else:
if not result:
ret['comment'] = ('Bootstrap via seed_cmd \'{0}\' failed, '
'see minion log for more information '
.format(seed_cmd))
ret['result'] = False
else:
changes.append(
{'bootstrap': 'Container successfully bootstrapped '
'using seed_cmd \'{0}\''
.format(seed_cmd)}
)
if ret.get('result', True) and not start_:
try:
stop(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
ret['result'] = False
state_post = state(name, path=path)
if state_pre != state_post:
changes.append({'state': {'old': state_pre, 'new': state_post}})
if ret.get('result', True):
ret['comment'] = ('Container \'{0}\' successfully initialized'
.format(name))
ret['result'] = True
if changes:
ret['changes'] = changes_dict
return ret
def cloud_init(name, vm_=None, **kwargs):
'''
Thin wrapper to lxc.init to be used from the saltcloud lxc driver
name
Name of the container
may be None and then guessed from saltcloud mapping
`vm_`
saltcloud mapping defaults for the vm
CLI Example:
.. code-block:: bash
salt '*' lxc.cloud_init foo
'''
init_interface = cloud_init_interface(name, vm_, **kwargs)
name = init_interface.pop('name', name)
return init(name, **init_interface)
def images(dist=None):
'''
.. versionadded:: 2015.5.0
List the available images for LXC's ``download`` template.
dist : None
Filter results to a single Linux distribution
CLI Examples:
.. code-block:: bash
salt myminion lxc.images
salt myminion lxc.images dist=centos
'''
out = __salt__['cmd.run_stdout'](
'lxc-create -n __imgcheck -t download -- --list',
ignore_retcode=True
)
if 'DIST' not in out:
raise CommandExecutionError(
'Unable to run the \'download\' template script. Is it installed?'
)
ret = {}
passed_header = False
for line in out.splitlines():
try:
distro, release, arch, variant, build_time = line.split()
except ValueError:
continue
if not passed_header:
if distro == 'DIST':
passed_header = True
continue
dist_list = ret.setdefault(distro, [])
dist_list.append({
'release': release,
'arch': arch,
'variant': variant,
'build_time': build_time,
})
if dist is not None:
return dict([(dist, ret.get(dist, []))])
return ret
def templates():
'''
.. versionadded:: 2015.5.0
List the available LXC template scripts installed on the minion
CLI Examples:
.. code-block:: bash
salt myminion lxc.templates
'''
try:
template_scripts = os.listdir('/usr/share/lxc/templates')
except OSError:
return []
else:
return [x[4:] for x in template_scripts if x.startswith('lxc-')]
def _after_ignition_network_profile(cmd,
ret,
name,
network_profile,
path,
nic_opts):
_clear_context()
if ret['retcode'] == 0 and exists(name, path=path):
if network_profile:
network_changes = apply_network_profile(name,
network_profile,
path=path,
nic_opts=nic_opts)
if network_changes:
log.info(
'Network changes from applying network profile \'%s\' '
'to newly-created container \'%s\':\n%s',
network_profile, name, network_changes
)
c_state = state(name, path=path)
return {'result': True,
'state': {'old': None, 'new': c_state}}
else:
if exists(name, path=path):
# destroy the container if it was partially created
cmd = 'lxc-destroy'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0}'.format(name)
__salt__['cmd.retcode'](cmd, python_shell=False)
raise CommandExecutionError(
'Container could not be created with cmd \'{0}\': {1}'
.format(cmd, ret['stderr'])
)
def create(name,
config=None,
profile=None,
network_profile=None,
nic_opts=None,
**kwargs):
'''
Create a new container.
name
Name of the container
config
The config file to use for the container. Defaults to system-wide
config (usually in /etc/lxc/lxc.conf).
profile
Profile to use in container creation (see
:mod:`lxc.get_container_profile
<salt.modules.lxc.get_container_profile>`). Values in a profile will be
overridden by the **Container Creation Arguments** listed below.
network_profile
Network profile to use for container
.. versionadded:: 2015.5.0
**Container Creation Arguments**
template
The template to use. For example, ``ubuntu`` or ``fedora``.
For a full list of available templates, check out
the :mod:`lxc.templates <salt.modules.lxc.templates>` function.
Conflicts with the ``image`` argument.
.. note::
The ``download`` template requires the following three parameters
to be defined in ``options``:
* **dist** - The name of the distribution
* **release** - Release name/version
* **arch** - Architecture of the container
The available images can be listed using the :mod:`lxc.images
<salt.modules.lxc.images>` function.
options
Template-specific options to pass to the lxc-create command. These
correspond to the long options (ones beginning with two dashes) that
the template script accepts. For example:
.. code-block:: bash
options='{"dist": "centos", "release": "6", "arch": "amd64"}'
For available template options, refer to the lxc template scripts
which are ususally located under ``/usr/share/lxc/templates``,
or run ``lxc-create -t <template> -h``.
image
A tar archive to use as the rootfs for the container. Conflicts with
the ``template`` argument.
backing
The type of storage to use. Set to ``lvm`` to use an LVM group.
Defaults to filesystem within /var/lib/lxc.
fstype
Filesystem type to use on LVM logical volume
size : 1G
Size of the volume to create. Only applicable if ``backing=lvm``.
vgname : lxc
Name of the LVM volume group in which to create the volume for this
container. Only applicable if ``backing=lvm``.
lvname
Name of the LVM logical volume in which to create the volume for this
container. Only applicable if ``backing=lvm``.
thinpool
Name of a pool volume that will be used for thin-provisioning this
container. Only applicable if ``backing=lvm``.
nic_opts
give extra opts overriding network profile values
path
parent path for the container creation (default: /var/lib/lxc)
zfsroot
Name of the ZFS root in which to create the volume for this container.
Only applicable if ``backing=zfs``. (default: tank/lxc)
.. versionadded:: 2015.8.0
'''
# Required params for 'download' template
download_template_deps = ('dist', 'release', 'arch')
cmd = 'lxc-create -n {0}'.format(name)
profile = get_container_profile(copy.deepcopy(profile))
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, None)
profile_match = profile.pop(key, default)
# Return the profile match if the the kwarg match was None, as the
# lxc.present state will pass these kwargs set to None by default.
if kw_overrides_match is None:
return profile_match
return kw_overrides_match
path = select('path')
if exists(name, path=path):
raise CommandExecutionError(
'Container \'{0}\' already exists'.format(name)
)
tvg = select('vgname')
vgname = tvg if tvg else __salt__['config.get']('lxc.vgname')
# The 'template' and 'image' params conflict
template = select('template')
image = select('image')
if template and image:
raise SaltInvocationError(
'Only one of \'template\' and \'image\' is permitted'
)
elif not any((template, image, profile)):
raise SaltInvocationError(
'At least one of \'template\', \'image\', and \'profile\' is '
'required'
)
options = select('options') or {}
backing = select('backing')
if vgname and not backing:
backing = 'lvm'
lvname = select('lvname')
thinpool = select('thinpool')
fstype = select('fstype')
size = select('size', '1G')
zfsroot = select('zfsroot')
if backing in ('dir', 'overlayfs', 'btrfs', 'zfs'):
fstype = None
size = None
# some backends won't support some parameters
if backing in ('aufs', 'dir', 'overlayfs', 'btrfs'):
lvname = vgname = thinpool = None
if image:
img_tar = __salt__['cp.cache_file'](image)
template = os.path.join(
os.path.dirname(salt.__file__),
'templates',
'lxc',
'salt_tarball')
options['imgtar'] = img_tar
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
if not os.path.exists(path):
os.makedirs(path)
if config:
cmd += ' -f {0}'.format(config)
if template:
cmd += ' -t {0}'.format(template)
if backing:
backing = backing.lower()
cmd += ' -B {0}'.format(backing)
if backing in ('zfs',):
if zfsroot:
cmd += ' --zfsroot {0}'.format(zfsroot)
if backing in ('lvm',):
if lvname:
cmd += ' --lvname {0}'.format(lvname)
if vgname:
cmd += ' --vgname {0}'.format(vgname)
if thinpool:
cmd += ' --thinpool {0}'.format(thinpool)
if backing not in ('dir', 'overlayfs'):
if fstype:
cmd += ' --fstype {0}'.format(fstype)
if size:
cmd += ' --fssize {0}'.format(size)
if options:
if template == 'download':
missing_deps = [x for x in download_template_deps
if x not in options]
if missing_deps:
raise SaltInvocationError(
'Missing params in \'options\' dict: {0}'
.format(', '.join(missing_deps))
)
cmd += ' --'
for key, val in six.iteritems(options):
cmd += ' --{0} {1}'.format(key, val)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
# please do not merge extra conflicting stuff
# inside those two line (ret =, return)
return _after_ignition_network_profile(cmd,
ret,
name,
network_profile,
path,
nic_opts)
def clone(name,
orig,
profile=None,
network_profile=None,
nic_opts=None,
**kwargs):
'''
Create a new container as a clone of another container
name
Name of the container
orig
Name of the original container to be cloned
profile
Profile to use in container cloning (see
:mod:`lxc.get_container_profile
<salt.modules.lxc.get_container_profile>`). Values in a profile will be
overridden by the **Container Cloning Arguments** listed below.
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
**Container Cloning Arguments**
snapshot
Use Copy On Write snapshots (LVM)
size : 1G
Size of the volume to create. Only applicable if ``backing=lvm``.
backing
The type of storage to use. Set to ``lvm`` to use an LVM group.
Defaults to filesystem within /var/lib/lxc.
network_profile
Network profile to use for container
.. versionadded:: 2015.8.0
nic_opts
give extra opts overriding network profile values
.. versionadded:: 2015.8.0
CLI Examples:
.. code-block:: bash
salt '*' lxc.clone myclone orig=orig_container
salt '*' lxc.clone myclone orig=orig_container snapshot=True
'''
profile = get_container_profile(copy.deepcopy(profile))
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, None)
profile_match = profile.pop(key, default)
# let kwarg overrides be the preferred choice
if kw_overrides_match is None:
return profile_match
return kw_overrides_match
path = select('path')
if exists(name, path=path):
raise CommandExecutionError(
'Container \'{0}\' already exists'.format(name)
)
_ensure_exists(orig, path=path)
if state(orig, path=path) != 'stopped':
raise CommandExecutionError(
'Container \'{0}\' must be stopped to be cloned'.format(orig)
)
backing = select('backing')
snapshot = select('snapshot')
if backing in ('dir',):
snapshot = False
if not snapshot:
snapshot = ''
else:
snapshot = '-s'
size = select('size', '1G')
if backing in ('dir', 'overlayfs', 'btrfs'):
size = None
# LXC commands and options changed in 2.0 - CF issue #34086 for details
if _LooseVersion(version()) >= _LooseVersion('2.0'):
# https://linuxcontainers.org/lxc/manpages//man1/lxc-copy.1.html
cmd = 'lxc-copy'
cmd += ' {0} -n {1} -N {2}'.format(snapshot, orig, name)
else:
# https://linuxcontainers.org/lxc/manpages//man1/lxc-clone.1.html
cmd = 'lxc-clone'
cmd += ' {0} -o {1} -n {2}'.format(snapshot, orig, name)
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
if not os.path.exists(path):
os.makedirs(path)
if backing:
backing = backing.lower()
cmd += ' -B {0}'.format(backing)
if backing not in ('dir', 'overlayfs'):
if size:
cmd += ' -L {0}'.format(size)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
# please do not merge extra conflicting stuff
# inside those two line (ret =, return)
return _after_ignition_network_profile(cmd,
ret,
name,
network_profile,
path,
nic_opts)
def ls_(active=None, cache=True, path=None):
'''
Return a list of the containers available on the minion
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
active
If ``True``, return only active (i.e. running) containers
.. versionadded:: 2015.5.0
CLI Example:
.. code-block:: bash
salt '*' lxc.ls
salt '*' lxc.ls active=True
'''
contextvar = 'lxc.ls{0}'.format(path)
if active:
contextvar += '.active'
if cache and (contextvar in __context__):
return __context__[contextvar]
else:
ret = []
cmd = 'lxc-ls'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
if active:
cmd += ' --active'
output = __salt__['cmd.run_stdout'](cmd, python_shell=False)
for line in output.splitlines():
ret.extend(line.split())
__context__[contextvar] = ret
return ret
def list_(extra=False, limit=None, path=None):
'''
List containers classified by state
extra
Also get per-container specific info. This will change the return data.
Instead of returning a list of containers, a dictionary of containers
and each container's output from :mod:`lxc.info
<salt.modules.lxc.info>`.
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
limit
Return output matching a specific state (**frozen**, **running**, or
**stopped**).
.. versionadded:: 2015.5.0
CLI Examples:
.. code-block:: bash
salt '*' lxc.list
salt '*' lxc.list extra=True
salt '*' lxc.list limit=running
'''
ctnrs = ls_(path=path)
if extra:
stopped = {}
frozen = {}
running = {}
else:
stopped = []
frozen = []
running = []
ret = {'running': running,
'stopped': stopped,
'frozen': frozen}
for container in ctnrs:
cmd = 'lxc-info'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0}'.format(container)
c_info = __salt__['cmd.run'](
cmd,
python_shell=False,
output_loglevel='debug'
)
c_state = None
for line in c_info.splitlines():
stat = line.split(':')
if stat[0] in ('State', 'state'):
c_state = stat[1].strip()
break
if not c_state or (limit is not None and c_state.lower() != limit):
continue
if extra:
infos = info(container, path=path)
method = 'update'
value = {container: infos}
else:
method = 'append'
value = container
if c_state == 'STOPPED':
getattr(stopped, method)(value)
continue
if c_state == 'FROZEN':
getattr(frozen, method)(value)
continue
if c_state == 'RUNNING':
getattr(running, method)(value)
continue
if limit is not None:
return ret.get(limit, {} if extra else [])
return ret
def _change_state(cmd,
name,
expected,
stdin=_marker,
stdout=_marker,
stderr=_marker,
with_communicate=_marker,
use_vt=_marker,
path=None):
pre = state(name, path=path)
if pre == expected:
return {'result': True,
'state': {'old': expected, 'new': expected},
'comment': 'Container \'{0}\' already {1}'
.format(name, expected)}
if cmd == 'lxc-destroy':
# Kill the container first
scmd = 'lxc-stop'
if path:
scmd += ' -P {0}'.format(pipes.quote(path))
scmd += ' -k -n {0}'.format(name)
__salt__['cmd.run'](scmd,
python_shell=False)
if path and ' -P ' not in cmd:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0}'.format(name)
# certain lxc commands need to be taken with care (lxc-start)
# as te command itself mess with double forks; we must not
# communicate with it, but just wait for the exit status
pkwargs = {'python_shell': False,
'redirect_stderr': True,
'with_communicate': with_communicate,
'use_vt': use_vt,
'stdin': stdin,
'stdout': stdout}
for i in [a for a in pkwargs]:
val = pkwargs[i]
if val is _marker:
pkwargs.pop(i, None)
_cmdout = __salt__['cmd.run_all'](cmd, **pkwargs)
if _cmdout['retcode'] != 0:
raise CommandExecutionError(
'Error changing state for container \'{0}\' using command '
'\'{1}\': {2}'.format(name, cmd, _cmdout['stdout'])
)
if expected is not None:
# some commands do not wait, so we will
rcmd = 'lxc-wait'
if path:
rcmd += ' -P {0}'.format(pipes.quote(path))
rcmd += ' -n {0} -s {1}'.format(name, expected.upper())
__salt__['cmd.run'](rcmd, python_shell=False, timeout=30)
_clear_context()
post = state(name, path=path)
ret = {'result': post == expected,
'state': {'old': pre, 'new': post}}
return ret
def _ensure_exists(name, path=None):
'''
Raise an exception if the container does not exist
'''
if not exists(name, path=path):
raise CommandExecutionError(
'Container \'{0}\' does not exist'.format(name)
)
def _ensure_running(name, no_start=False, path=None):
'''
If the container is not currently running, start it. This function returns
the state that the container was in before changing
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
'''
_ensure_exists(name, path=path)
pre = state(name, path=path)
if pre == 'running':
# This will be a no-op but running the function will give us a pretty
# return dict.
return start(name, path=path)
elif pre == 'stopped':
if no_start:
raise CommandExecutionError(
'Container \'{0}\' is not running'.format(name)
)
return start(name, path=path)
elif pre == 'frozen':
if no_start:
raise CommandExecutionError(
'Container \'{0}\' is not running'.format(name)
)
return unfreeze(name, path=path)
def restart(name, path=None, lxc_config=None, force=False):
'''
.. versionadded:: 2015.5.0
Restart the named container. If the container was not running, the
container will merely be started.
name
The name of the container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
lxc_config
path to a lxc config file
config file will be guessed from container name otherwise
.. versionadded:: 2015.8.0
force : False
If ``True``, the container will be force-stopped instead of gracefully
shut down
CLI Example:
.. code-block:: bash
salt myminion lxc.restart name
'''
_ensure_exists(name, path=path)
orig_state = state(name, path=path)
if orig_state != 'stopped':
stop(name, kill=force, path=path)
ret = start(name, path=path, lxc_config=lxc_config)
ret['state']['old'] = orig_state
if orig_state != 'stopped':
ret['restarted'] = True
return ret
def start(name, **kwargs):
'''
Start the named container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
lxc_config
path to a lxc config file
config file will be guessed from container name otherwise
.. versionadded:: 2015.8.0
use_vt
run the command through VT
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.start name
'''
path = kwargs.get('path', None)
cpath = get_root_path(path)
lxc_config = kwargs.get('lxc_config', None)
cmd = 'lxc-start'
if not lxc_config:
lxc_config = os.path.join(cpath, name, 'config')
# we try to start, even without config, if global opts are there
if os.path.exists(lxc_config):
cmd += ' -f {0}'.format(pipes.quote(lxc_config))
cmd += ' -d'
_ensure_exists(name, path=path)
if state(name, path=path) == 'frozen':
raise CommandExecutionError(
'Container \'{0}\' is frozen, use lxc.unfreeze'.format(name)
)
# lxc-start daemonize itself violently, we must not communicate with it
use_vt = kwargs.get('use_vt', None)
with_communicate = kwargs.get('with_communicate', False)
return _change_state(cmd, name, 'running',
stdout=None,
stderr=None,
stdin=None,
with_communicate=with_communicate,
path=path,
use_vt=use_vt)
def stop(name, kill=False, path=None, use_vt=None):
'''
Stop the named container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
kill: False
Do not wait for the container to stop, kill all tasks in the container.
Older LXC versions will stop containers like this irrespective of this
argument.
.. versionchanged:: 2015.5.0
Default value changed to ``False``
use_vt
run the command through VT
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.stop name
'''
_ensure_exists(name, path=path)
orig_state = state(name, path=path)
if orig_state == 'frozen' and not kill:
# Gracefully stopping a frozen container is slower than unfreezing and
# then stopping it (at least in my testing), so if we're not
# force-stopping the container, unfreeze it first.
unfreeze(name, path=path)
cmd = 'lxc-stop'
if kill:
cmd += ' -k'
ret = _change_state(cmd, name, 'stopped', use_vt=use_vt, path=path)
ret['state']['old'] = orig_state
return ret
def freeze(name, **kwargs):
'''
Freeze the named container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
start : False
If ``True`` and the container is stopped, the container will be started
before attempting to freeze.
.. versionadded:: 2015.5.0
use_vt
run the command through VT
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.freeze name
'''
use_vt = kwargs.get('use_vt', None)
path = kwargs.get('path', None)
_ensure_exists(name, path=path)
orig_state = state(name, path=path)
start_ = kwargs.get('start', False)
if orig_state == 'stopped':
if not start_:
raise CommandExecutionError(
'Container \'{0}\' is stopped'.format(name)
)
start(name, path=path)
cmd = 'lxc-freeze'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
ret = _change_state(cmd, name, 'frozen', use_vt=use_vt, path=path)
if orig_state == 'stopped' and start_:
ret['state']['old'] = orig_state
ret['started'] = True
ret['state']['new'] = state(name, path=path)
return ret
def unfreeze(name, path=None, use_vt=None):
'''
Unfreeze the named container.
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
use_vt
run the command through VT
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.unfreeze name
'''
_ensure_exists(name, path=path)
if state(name, path=path) == 'stopped':
raise CommandExecutionError(
'Container \'{0}\' is stopped'.format(name)
)
cmd = 'lxc-unfreeze'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
return _change_state(cmd, name, 'running', path=path, use_vt=use_vt)
def destroy(name, stop=False, path=None):
'''
Destroy the named container.
.. warning::
Destroys all data associated with the container.
path
path to the container parent directory (default: /var/lib/lxc)
.. versionadded:: 2015.8.0
stop : False
If ``True``, the container will be destroyed even if it is
running/frozen.
.. versionchanged:: 2015.5.0
Default value changed to ``False``. This more closely matches the
behavior of ``lxc-destroy(1)``, and also makes it less likely that
an accidental command will destroy a running container that was
being used for important things.
CLI Examples:
.. code-block:: bash
salt '*' lxc.destroy foo
salt '*' lxc.destroy foo stop=True
'''
_ensure_exists(name, path=path)
if not stop and state(name, path=path) != 'stopped':
raise CommandExecutionError(
'Container \'{0}\' is not stopped'.format(name)
)
return _change_state('lxc-destroy', name, None, path=path)
# Compatibility between LXC and nspawn
remove = salt.utils.functools.alias_function(destroy, 'remove')
def exists(name, path=None):
'''
Returns whether the named container exists.
path
path to the container parent directory (default: /var/lib/lxc)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.exists name
'''
_exists = name in ls_(path=path)
# container may be just created but we did cached earlier the
# lxc-ls results
if not _exists:
_exists = name in ls_(cache=False, path=path)
return _exists
def state(name, path=None):
'''
Returns the state of a container.
path
path to the container parent directory (default: /var/lib/lxc)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.state name
'''
# Don't use _ensure_exists() here, it will mess with _change_state()
cachekey = 'lxc.state.{0}{1}'.format(name, path)
try:
return __context__[cachekey]
except KeyError:
if not exists(name, path=path):
__context__[cachekey] = None
else:
cmd = 'lxc-info'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0}'.format(name)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
if ret['retcode'] != 0:
_clear_context()
raise CommandExecutionError(
'Unable to get state of container \'{0}\''.format(name)
)
c_infos = ret['stdout'].splitlines()
c_state = None
for c_info in c_infos:
stat = c_info.split(':')
if stat[0].lower() == 'state':
c_state = stat[1].strip().lower()
break
__context__[cachekey] = c_state
return __context__[cachekey]
def get_parameter(name, parameter, path=None):
'''
Returns the value of a cgroup parameter for a container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.get_parameter container_name memory.limit_in_bytes
'''
_ensure_exists(name, path=path)
cmd = 'lxc-cgroup'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0} {1}'.format(name, parameter)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
if ret['retcode'] != 0:
raise CommandExecutionError(
'Unable to retrieve value for \'{0}\''.format(parameter)
)
return ret['stdout'].strip()
def set_parameter(name, parameter, value, path=None):
'''
Set the value of a cgroup parameter for a container.
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.set_parameter name parameter value
'''
if not exists(name, path=path):
return None
cmd = 'lxc-cgroup'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0} {1} {2}'.format(name, parameter, value)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
if ret['retcode'] != 0:
return False
else:
return True
def info(name, path=None):
'''
Returns information about a container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.info name
'''
cachekey = 'lxc.info.{0}{1}'.format(name, path)
try:
return __context__[cachekey]
except KeyError:
_ensure_exists(name, path=path)
cpath = get_root_path(path)
try:
conf_file = os.path.join(cpath, name, 'config')
except AttributeError:
conf_file = os.path.join(cpath, six.text_type(name), 'config')
if not os.path.isfile(conf_file):
raise CommandExecutionError(
'LXC config file {0} does not exist'.format(conf_file)
)
ret = {}
config = []
with salt.utils.files.fopen(conf_file) as fp_:
for line in fp_:
line = salt.utils.stringutils.to_unicode(line)
comps = [x.strip() for x in
line.split('#', 1)[0].strip().split('=', 1)]
if len(comps) == 2:
config.append(tuple(comps))
ifaces = []
current = None
for key, val in config:
if key == 'lxc.network.type':
current = {'type': val}
ifaces.append(current)
elif not current:
continue
elif key.startswith('lxc.network.'):
current[key.replace('lxc.network.', '', 1)] = val
if ifaces:
ret['nics'] = ifaces
ret['rootfs'] = next(
(x[1] for x in config if x[0] == 'lxc.rootfs'),
None
)
ret['state'] = state(name, path=path)
ret['ips'] = []
ret['public_ips'] = []
ret['private_ips'] = []
ret['public_ipv4_ips'] = []
ret['public_ipv6_ips'] = []
ret['private_ipv4_ips'] = []
ret['private_ipv6_ips'] = []
ret['ipv4_ips'] = []
ret['ipv6_ips'] = []
ret['size'] = None
ret['config'] = conf_file
if ret['state'] == 'running':
try:
limit = int(get_parameter(name, 'memory.limit_in_bytes'))
except (CommandExecutionError, TypeError, ValueError):
limit = 0
try:
usage = int(get_parameter(name, 'memory.usage_in_bytes'))
except (CommandExecutionError, TypeError, ValueError):
usage = 0
free = limit - usage
ret['memory_limit'] = limit
ret['memory_free'] = free
size = run_stdout(name, 'df /', path=path, python_shell=False)
# The size is the 2nd column of the last line
ret['size'] = size.splitlines()[-1].split()[1]
# First try iproute2
ip_cmd = run_all(
name, 'ip link show', path=path, python_shell=False)
if ip_cmd['retcode'] == 0:
ip_data = ip_cmd['stdout']
ip_cmd = run_all(
name, 'ip addr show', path=path, python_shell=False)
ip_data += '\n' + ip_cmd['stdout']
ip_data = salt.utils.network._interfaces_ip(ip_data)
else:
# That didn't work, try ifconfig
ip_cmd = run_all(
name, 'ifconfig', path=path, python_shell=False)
if ip_cmd['retcode'] == 0:
ip_data = \
salt.utils.network._interfaces_ifconfig(
ip_cmd['stdout'])
else:
# Neither was successful, give up
log.warning(
'Unable to run ip or ifconfig in container \'%s\'', name
)
ip_data = {}
ret['ipv4_ips'] = salt.utils.network.ip_addrs(
include_loopback=True,
interface_data=ip_data
)
ret['ipv6_ips'] = salt.utils.network.ip_addrs6(
include_loopback=True,
interface_data=ip_data
)
ret['ips'] = ret['ipv4_ips'] + ret['ipv6_ips']
for address in ret['ipv4_ips']:
if address == '127.0.0.1':
ret['private_ips'].append(address)
ret['private_ipv4_ips'].append(address)
elif salt.utils.cloud.is_public_ip(address):
ret['public_ips'].append(address)
ret['public_ipv4_ips'].append(address)
else:
ret['private_ips'].append(address)
ret['private_ipv4_ips'].append(address)
for address in ret['ipv6_ips']:
if address == '::1' or address.startswith('fe80'):
ret['private_ips'].append(address)
ret['private_ipv6_ips'].append(address)
else:
ret['public_ips'].append(address)
ret['public_ipv6_ips'].append(address)
for key in [x for x in ret if x == 'ips' or x.endswith('ips')]:
ret[key].sort(key=_ip_sort)
__context__[cachekey] = ret
return __context__[cachekey]
def set_password(name, users, password, encrypted=True, path=None):
'''
.. versionchanged:: 2015.5.0
Function renamed from ``set_pass`` to ``set_password``. Additionally,
this function now supports (and defaults to using) a password hash
instead of a plaintext password.
Set the password of one or more system users inside containers
users
Comma-separated list (or python list) of users to change password
password
Password to set for the specified user(s)
encrypted : True
If true, ``password`` must be a password hash. Set to ``False`` to set
a plaintext password (not recommended).
.. versionadded:: 2015.5.0
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.set_pass container-name root '$6$uJ2uAyLU$KoI67t8As/0fXtJOPcHKGXmUpcoYUcVR2K6x93walnShTCQvjRwq25yIkiCBOqgbfdKQSFnAo28/ek6716vEV1'
salt '*' lxc.set_pass container-name root foo encrypted=False
'''
def _bad_user_input():
raise SaltInvocationError('Invalid input for \'users\' parameter')
if not isinstance(users, list):
try:
users = users.split(',')
except AttributeError:
_bad_user_input()
if not users:
_bad_user_input()
failed_users = []
for user in users:
result = retcode(name,
'chpasswd{0}'.format(' -e' if encrypted else ''),
stdin=':'.join((user, password)),
python_shell=False,
path=path,
chroot_fallback=True,
output_loglevel='quiet')
if result != 0:
failed_users.append(user)
if failed_users:
raise CommandExecutionError(
'Password change failed for the following user(s): {0}'
.format(', '.join(failed_users))
)
return True
set_pass = salt.utils.functools.alias_function(set_password, 'set_pass')
def update_lxc_conf(name, lxc_conf, lxc_conf_unset, path=None):
'''
Edit LXC configuration options
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.update_lxc_conf ubuntu \\
lxc_conf="[{'network.ipv4.ip':'10.0.3.5'}]" \\
lxc_conf_unset="['lxc.utsname']"
'''
_ensure_exists(name, path=path)
cpath = get_root_path(path)
lxc_conf_p = os.path.join(cpath, name, 'config')
if not os.path.exists(lxc_conf_p):
raise SaltInvocationError(
'Configuration file {0} does not exist'.format(lxc_conf_p)
)
changes = {'edited': [], 'added': [], 'removed': []}
ret = {'changes': changes, 'result': True, 'comment': ''}
# do not use salt.utils.files.fopen !
with salt.utils.files.fopen(lxc_conf_p, 'r') as fic:
filtered_lxc_conf = []
for row in lxc_conf:
if not row:
continue
for conf in row:
filtered_lxc_conf.append((conf.strip(),
row[conf].strip()))
ret['comment'] = 'lxc.conf is up to date'
lines = []
orig_config = salt.utils.stringutils.to_unicode(fic.read())
for line in orig_config.splitlines():
if line.startswith('#') or not line.strip():
lines.append([line, ''])
else:
line = line.split('=')
index = line.pop(0)
val = (index.strip(), '='.join(line).strip())
if val not in lines:
lines.append(val)
for key, item in filtered_lxc_conf:
matched = False
for idx, line in enumerate(lines[:]):
if line[0] == key:
matched = True
lines[idx] = (key, item)
if '='.join(line[1:]).strip() != item.strip():
changes['edited'].append(
({line[0]: line[1:]}, {key: item}))
break
if not matched:
if (key, item) not in lines:
lines.append((key, item))
changes['added'].append({key: item})
dest_lxc_conf = []
# filter unset
if lxc_conf_unset:
for line in lines:
for opt in lxc_conf_unset:
if (
not line[0].startswith(opt) and
line not in dest_lxc_conf
):
dest_lxc_conf.append(line)
else:
changes['removed'].append(opt)
else:
dest_lxc_conf = lines
conf = ''
for key, val in dest_lxc_conf:
if not val:
conf += '{0}\n'.format(key)
else:
conf += '{0} = {1}\n'.format(key.strip(), val.strip())
conf_changed = conf != orig_config
chrono = datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S')
if conf_changed:
# DO NOT USE salt.utils.files.fopen here, i got (kiorky)
# problems with lxc configs which were wiped !
with salt.utils.files.fopen('{0}.{1}'.format(lxc_conf_p, chrono), 'w') as wfic:
wfic.write(salt.utils.stringutils.to_str(conf))
with salt.utils.files.fopen(lxc_conf_p, 'w') as wfic:
wfic.write(salt.utils.stringutils.to_str(conf))
ret['comment'] = 'Updated'
ret['result'] = True
if not any(changes[x] for x in changes):
# Ensure an empty changes dict if nothing was modified
ret['changes'] = {}
return ret
def set_dns(name, dnsservers=None, searchdomains=None, path=None):
'''
.. versionchanged:: 2015.5.0
The ``dnsservers`` and ``searchdomains`` parameters can now be passed
as a comma-separated list.
Update /etc/resolv.confo
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.set_dns ubuntu "['8.8.8.8', '4.4.4.4']"
'''
if dnsservers is None:
dnsservers = ['8.8.8.8', '4.4.4.4']
elif not isinstance(dnsservers, list):
try:
dnsservers = dnsservers.split(',')
except AttributeError:
raise SaltInvocationError(
'Invalid input for \'dnsservers\' parameter'
)
if searchdomains is None:
searchdomains = []
elif not isinstance(searchdomains, list):
try:
searchdomains = searchdomains.split(',')
except AttributeError:
raise SaltInvocationError(
'Invalid input for \'searchdomains\' parameter'
)
dns = ['nameserver {0}'.format(x) for x in dnsservers]
dns.extend(['search {0}'.format(x) for x in searchdomains])
dns = '\n'.join(dns) + '\n'
# we may be using resolvconf in the container
# We need to handle that case with care:
# - we create the resolv.conf runtime directory (the
# linked directory) as anyway it will be shadowed when the real
# runned tmpfs mountpoint will be mounted.
# ( /etc/resolv.conf -> ../run/resolvconf/resolv.conf)
# Indeed, it can save us in any other case (running, eg, in a
# bare chroot when repairing or preparing the container for
# operation.
# - We also teach resolvconf to use the aforementioned dns.
# - We finally also set /etc/resolv.conf in all cases
rstr = __salt__['test.random_hash']()
# no tmp here, apparmor won't let us execute !
script = '/sbin/{0}_dns.sh'.format(rstr)
DNS_SCRIPT = "\n".join([
# 'set -x',
'#!/usr/bin/env bash',
'if [ -h /etc/resolv.conf ];then',
' if [ "x$(readlink /etc/resolv.conf)"'
' = "x../run/resolvconf/resolv.conf" ];then',
' if [ ! -d /run/resolvconf/ ];then',
' mkdir -p /run/resolvconf',
' fi',
' cat > /etc/resolvconf/resolv.conf.d/head <<EOF',
dns,
'EOF',
'',
' fi',
'fi',
'cat > /etc/resolv.conf <<EOF',
dns,
'EOF',
''])
result = run_all(
name, 'tee {0}'.format(script), path=path,
stdin=DNS_SCRIPT, python_shell=True)
if result['retcode'] == 0:
result = run_all(
name, 'sh -c "chmod +x {0};{0}"'.format(script),
path=path, python_shell=True)
# blindly delete the setter file
run_all(name,
'sh -c \'if [ -f "{0}" ];then rm -f "{0}";fi\''.format(script),
path=path, python_shell=True)
if result['retcode'] != 0:
error = ('Unable to write to /etc/resolv.conf in container \'{0}\''
.format(name))
if result['stderr']:
error += ': {0}'.format(result['stderr'])
raise CommandExecutionError(error)
return True
def running_systemd(name, cache=True, path=None):
'''
Determine if systemD is running
path
path to the container parent
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.running_systemd ubuntu
'''
k = 'lxc.systemd.test.{0}{1}'.format(name, path)
ret = __context__.get(k, None)
if ret is None or not cache:
rstr = __salt__['test.random_hash']()
# no tmp here, apparmor won't let us execute !
script = '/sbin/{0}_testsystemd.sh'.format(rstr)
# ubuntu already had since trusty some bits of systemd but was
# still using upstart ...
# we need to be a bit more careful that just testing that systemd
# is present
_script = textwrap.dedent(
'''\
#!/usr/bin/env bash
set -x
if ! command -v systemctl 1>/dev/null 2>/dev/null;then exit 2;fi
for i in \\
/run/systemd/journal/dev-log\\
/run/systemd/journal/flushed\\
/run/systemd/journal/kernel-seqnum\\
/run/systemd/journal/socket\\
/run/systemd/journal/stdout\\
/var/run/systemd/journal/dev-log\\
/var/run/systemd/journal/flushed\\
/var/run/systemd/journal/kernel-seqnum\\
/var/run/systemd/journal/socket\\
/var/run/systemd/journal/stdout\\
;do\\
if test -e ${i};then exit 0;fi
done
if test -d /var/systemd/system;then exit 0;fi
exit 2
''')
result = run_all(
name, 'tee {0}'.format(script), path=path,
stdin=_script, python_shell=True)
if result['retcode'] == 0:
result = run_all(name,
'sh -c "chmod +x {0};{0}"'''.format(script),
path=path,
python_shell=True)
else:
raise CommandExecutionError(
'lxc {0} failed to copy initd tester'.format(name))
run_all(name,
'sh -c \'if [ -f "{0}" ];then rm -f "{0}";fi\''
''.format(script),
path=path,
ignore_retcode=True,
python_shell=True)
if result['retcode'] != 0:
error = ('Unable to determine if the container \'{0}\''
' was running systemd, assmuming it is not.'
''.format(name))
if result['stderr']:
error += ': {0}'.format(result['stderr'])
# only cache result if we got a known exit code
if result['retcode'] in (0, 2):
__context__[k] = ret = not result['retcode']
return ret
def systemd_running_state(name, path=None):
'''
Get the operational state of a systemd based container
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.systemd_running_state ubuntu
'''
try:
ret = run_all(name,
'systemctl is-system-running',
path=path,
ignore_retcode=True)['stdout']
except CommandExecutionError:
ret = ''
return ret
def test_sd_started_state(name, path=None):
'''
Test if a systemd container is fully started
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.test_sd_started_state ubuntu
'''
qstate = systemd_running_state(name, path=path)
if qstate in ('initializing', 'starting'):
return False
elif qstate == '':
return None
else:
return True
def test_bare_started_state(name, path=None):
'''
Test if a non systemd container is fully started
For now, it consists only to test if the container is attachable
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.test_bare_started_state ubuntu
'''
try:
ret = run_all(
name, 'ls', path=path, ignore_retcode=True
)['retcode'] == 0
except (CommandExecutionError,):
ret = None
return ret
def wait_started(name, path=None, timeout=300):
'''
Check that the system has fully inited
This is actually very important for systemD based containers
see https://github.com/saltstack/salt/issues/23847
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.wait_started ubuntu
'''
if not exists(name, path=path):
raise CommandExecutionError(
'Container {0} does does exists'.format(name))
if not state(name, path=path) == 'running':
raise CommandExecutionError(
'Container {0} is not running'.format(name))
ret = False
if running_systemd(name, path=path):
test_started = test_sd_started_state
logger = log.error
else:
test_started = test_bare_started_state
logger = log.debug
now = time.time()
expire = now + timeout
now = time.time()
started = test_started(name, path=path)
while time.time() < expire and not started:
time.sleep(0.3)
started = test_started(name, path=path)
if started is None:
logger(
'Assuming %s is started, although we failed to detect that'
' is fully started correctly', name)
ret = True
else:
ret = started
return ret
def _needs_install(name, path=None):
ret = 0
has_minion = retcode(name,
'which salt-minion',
path=path,
ignore_retcode=True)
# we assume that installing is when no minion is running
# but testing the executable presence is not enougth for custom
# installs where the bootstrap can do much more than installing
# the bare salt binaries.
if has_minion:
processes = run_stdout(name, "ps aux", path=path)
if 'salt-minion' not in processes:
ret = 1
else:
retcode(name, 'salt-call --local service.stop salt-minion')
else:
ret = 1
return ret
def bootstrap(name,
config=None,
approve_key=True,
install=True,
pub_key=None,
priv_key=None,
bootstrap_url=None,
force_install=False,
unconditional_install=False,
path=None,
bootstrap_delay=None,
bootstrap_args=None,
bootstrap_shell=None):
'''
Install and configure salt in a container.
config
Minion configuration options. By default, the ``master`` option is set
to the target host's master.
approve_key
Request a pre-approval of the generated minion key. Requires
that the salt-master be configured to either auto-accept all keys or
expect a signing request from the target host. Default: ``True``
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
pub_key
Explicit public key to pressed the minion with (optional).
This can be either a filepath or a string representing the key
priv_key
Explicit private key to pressed the minion with (optional).
This can be either a filepath or a string representing the key
bootstrap_delay
Delay in seconds between end of container creation and bootstrapping.
Useful when waiting for container to obtain a DHCP lease.
.. versionadded:: 2015.5.0
bootstrap_url
url, content or filepath to the salt bootstrap script
bootstrap_args
salt bootstrap script arguments
bootstrap_shell
shell to execute the script into
install
Whether to attempt a full installation of salt-minion if needed.
force_install
Force installation even if salt-minion is detected,
this is the way to run vendor bootstrap scripts even
if a salt minion is already present in the container
unconditional_install
Run the script even if the container seems seeded
CLI Examples:
.. code-block:: bash
salt 'minion' lxc.bootstrap container_name [config=config_data] \\
[approve_key=(True|False)] [install=(True|False)]
'''
wait_started(name, path=path)
if bootstrap_delay is not None:
try:
log.info('LXC %s: bootstrap_delay: %s', name, bootstrap_delay)
time.sleep(bootstrap_delay)
except TypeError:
# Bad input, but assume since a value was passed that
# a delay was desired, and sleep for 5 seconds
time.sleep(5)
c_info = info(name, path=path)
if not c_info:
return None
# default set here as we cannot set them
# in def as it can come from a chain of procedures.
if bootstrap_args:
# custom bootstrap args can be totally customized, and user could
# have inserted the placeholder for the config directory.
# For example, some salt bootstrap script do not use at all -c
if '{0}' not in bootstrap_args:
bootstrap_args += ' -c {0}'
else:
bootstrap_args = '-c {0}'
if not bootstrap_shell:
bootstrap_shell = 'sh'
orig_state = _ensure_running(name, path=path)
if not orig_state:
return orig_state
if not force_install:
needs_install = _needs_install(name, path=path)
else:
needs_install = True
seeded = retcode(name,
'test -e \'{0}\''.format(SEED_MARKER),
path=path,
chroot_fallback=True,
ignore_retcode=True) == 0
tmp = tempfile.mkdtemp()
if seeded and not unconditional_install:
ret = True
else:
ret = False
cfg_files = __salt__['seed.mkconfig'](
config, tmp=tmp, id_=name, approve_key=approve_key,
pub_key=pub_key, priv_key=priv_key)
if needs_install or force_install or unconditional_install:
if install:
rstr = __salt__['test.random_hash']()
configdir = '/var/tmp/.c_{0}'.format(rstr)
cmd = 'install -m 0700 -d {0}'.format(configdir)
if run_all(
name, cmd, path=path, python_shell=False
)['retcode'] != 0:
log.error('tmpdir %s creation failed %s', configdir, cmd)
return False
bs_ = __salt__['config.gather_bootstrap_script'](
bootstrap=bootstrap_url)
script = '/sbin/{0}_bootstrap.sh'.format(rstr)
copy_to(name, bs_, script, path=path)
result = run_all(name,
'sh -c "chmod +x {0}"'.format(script),
path=path,
python_shell=True)
copy_to(name, cfg_files['config'],
os.path.join(configdir, 'minion'),
path=path)
copy_to(name, cfg_files['privkey'],
os.path.join(configdir, 'minion.pem'),
path=path)
copy_to(name, cfg_files['pubkey'],
os.path.join(configdir, 'minion.pub'),
path=path)
bootstrap_args = bootstrap_args.format(configdir)
cmd = ('{0} {2} {1}'
.format(bootstrap_shell,
bootstrap_args.replace("'", "''"),
script))
# log ASAP the forged bootstrap command which can be wrapped
# out of the output in case of unexpected problem
log.info('Running %s in LXC container \'%s\'', cmd, name)
ret = retcode(name, cmd, output_loglevel='info',
path=path, use_vt=True) == 0
run_all(name,
'sh -c \'if [ -f "{0}" ];then rm -f "{0}";fi\''
''.format(script),
path=path,
ignore_retcode=True,
python_shell=True)
else:
ret = False
else:
minion_config = salt.config.minion_config(cfg_files['config'])
pki_dir = minion_config['pki_dir']
copy_to(name,
cfg_files['config'],
'/etc/salt/minion',
path=path)
copy_to(name,
cfg_files['privkey'],
os.path.join(pki_dir, 'minion.pem'),
path=path)
copy_to(name,
cfg_files['pubkey'],
os.path.join(pki_dir, 'minion.pub'),
path=path)
run(name,
'salt-call --local service.enable salt-minion',
path=path,
python_shell=False)
ret = True
shutil.rmtree(tmp)
if orig_state == 'stopped':
stop(name, path=path)
elif orig_state == 'frozen':
freeze(name, path=path)
# mark seeded upon successful install
if ret:
run(name,
'touch \'{0}\''.format(SEED_MARKER),
path=path,
python_shell=False)
return ret
def attachable(name, path=None):
'''
Return True if the named container can be attached to via the lxc-attach
command
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt 'minion' lxc.attachable ubuntu
'''
cachekey = 'lxc.attachable{0}{1}'.format(name, path)
try:
return __context__[cachekey]
except KeyError:
_ensure_exists(name, path=path)
# Can't use run() here because it uses attachable() and would
# endlessly recurse, resulting in a traceback
log.debug('Checking if LXC container %s is attachable', name)
cmd = 'lxc-attach'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' --clear-env -n {0} -- /usr/bin/env'.format(name)
result = __salt__['cmd.retcode'](cmd,
python_shell=False,
output_loglevel='quiet',
ignore_retcode=True) == 0
__context__[cachekey] = result
return __context__[cachekey]
def _run(name,
cmd,
output=None,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=None,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
Common logic for lxc.run functions
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
'''
orig_state = state(name, path=path)
try:
if attachable(name, path=path):
ret = __salt__['container_resource.run'](
name,
cmd,
path=path,
container_type=__virtualname__,
exec_driver=EXEC_DRIVER,
output=output,
no_start=no_start,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
ignore_retcode=ignore_retcode,
use_vt=use_vt,
keep_env=keep_env)
else:
if not chroot_fallback:
raise CommandExecutionError(
'{0} is not attachable.'.format(name))
rootfs = info(name, path=path).get('rootfs')
# Set context var to make cmd.run_chroot run cmd.run instead of
# cmd.run_all.
__context__['cmd.run_chroot.func'] = __salt__['cmd.run']
ret = __salt__['cmd.run_chroot'](rootfs,
cmd,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
ignore_retcode=ignore_retcode)
except Exception:
raise
finally:
# Make sure we honor preserve_state, even if there was an exception
new_state = state(name, path=path)
if preserve_state:
if orig_state == 'stopped' and new_state != 'stopped':
stop(name, path=path)
elif orig_state == 'frozen' and new_state != 'frozen':
freeze(name, start=True, path=path)
if output in (None, 'all'):
return ret
else:
return ret[output]
def run(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.8.0
Run :mod:`cmd.run <salt.modules.cmdmod.run>` within a container
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed in stderr if the command being run
does not exist. If no output is returned using this function, try using
:mod:`lxc.run_stderr <salt.modules.lxc.run_stderr>` or
:mod:`lxc.run_all <salt.modules.lxc.run_all>`.
name
Name of the container in which to run the command
cmd
Command to run
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console. Assumes
``output=all``.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
CLI Example:
.. code-block:: bash
salt myminion lxc.run mycontainer 'ifconfig -a'
'''
return _run(name,
cmd,
path=path,
output=None,
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def run_stdout(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.5.0
Run :mod:`cmd.run_stdout <salt.modules.cmdmod.run_stdout>` within a container
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed in stderr if the command being run
does not exist. If no output is returned using this function, try using
:mod:`lxc.run_stderr <salt.modules.lxc.run_stderr>` or
:mod:`lxc.run_all <salt.modules.lxc.run_all>`.
name
Name of the container in which to run the command
cmd
Command to run
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console
``output=all``.
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
CLI Example:
.. code-block:: bash
salt myminion lxc.run_stdout mycontainer 'ifconfig -a'
'''
return _run(name,
cmd,
path=path,
output='stdout',
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def run_stderr(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.5.0
Run :mod:`cmd.run_stderr <salt.modules.cmdmod.run_stderr>` within a container
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed if the command being run does not
exist.
name
Name of the container in which to run the command
cmd
Command to run
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console
``output=all``.
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
CLI Example:
.. code-block:: bash
salt myminion lxc.run_stderr mycontainer 'ip addr show'
'''
return _run(name,
cmd,
path=path,
output='stderr',
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def retcode(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.5.0
Run :mod:`cmd.retcode <salt.modules.cmdmod.retcode>` within a container
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed in stderr if the command being run
does not exist. If the retcode is nonzero and not what was expected,
try using :mod:`lxc.run_stderr <salt.modules.lxc.run_stderr>`
or :mod:`lxc.run_all <salt.modules.lxc.run_all>`.
name
Name of the container in which to run the command
cmd
Command to run
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console
``output=all``.
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
CLI Example:
.. code-block:: bash
salt myminion lxc.retcode mycontainer 'ip addr show'
'''
return _run(name,
cmd,
output='retcode',
path=path,
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def run_all(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.5.0
Run :mod:`cmd.run_all <salt.modules.cmdmod.run_all>` within a container
.. note::
While the command is run within the container, it is initiated from the
host. Therefore, the PID in the return dict is from the host, not from
the container.
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed in stderr if the command being run
does not exist.
name
Name of the container in which to run the command
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
cmd
Command to run
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console
``output=all``.
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
CLI Example:
.. code-block:: bash
salt myminion lxc.run_all mycontainer 'ip addr show'
'''
return _run(name,
cmd,
output='all',
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
path=path,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def _get_md5(name, path):
'''
Get the MD5 checksum of a file from a container
'''
output = run_stdout(name, 'md5sum "{0}"'.format(path),
chroot_fallback=True,
ignore_retcode=True)
try:
return output.split()[0]
except IndexError:
# Destination file does not exist or could not be accessed
return None
def copy_to(name, source, dest, overwrite=False, makedirs=False, path=None):
'''
.. versionchanged:: 2015.8.0
Function renamed from ``lxc.cp`` to ``lxc.copy_to`` for consistency
with other container types. ``lxc.cp`` will continue to work, however.
For versions 2015.2.x and earlier, use ``lxc.cp``.
Copy a file or directory from the host into a container
name
Container name
source
File to be copied to the container
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
dest
Destination on the container. Must be an absolute path.
.. versionchanged:: 2015.5.0
If the destination is a directory, the file will be copied into
that directory.
overwrite : False
Unless this option is set to ``True``, then if a file exists at the
location specified by the ``dest`` argument, an error will be raised.
.. versionadded:: 2015.8.0
makedirs : False
Create the parent directory on the container if it does not already
exist.
.. versionadded:: 2015.5.0
CLI Example:
.. code-block:: bash
salt 'minion' lxc.copy_to /tmp/foo /root/foo
salt 'minion' lxc.cp /tmp/foo /root/foo
'''
_ensure_running(name, no_start=True, path=path)
return __salt__['container_resource.copy_to'](
name,
source,
dest,
container_type=__virtualname__,
path=path,
exec_driver=EXEC_DRIVER,
overwrite=overwrite,
makedirs=makedirs)
cp = salt.utils.functools.alias_function(copy_to, 'cp')
def read_conf(conf_file, out_format='simple'):
'''
Read in an LXC configuration file. By default returns a simple, unsorted
dict, but can also return a more detailed structure including blank lines
and comments.
out_format:
set to 'simple' if you need the old and unsupported behavior.
This won't support the multiple lxc values (eg: multiple network nics)
CLI Examples:
.. code-block:: bash
salt 'minion' lxc.read_conf /etc/lxc/mycontainer.conf
salt 'minion' lxc.read_conf /etc/lxc/mycontainer.conf out_format=commented
'''
ret_commented = []
ret_simple = {}
with salt.utils.files.fopen(conf_file, 'r') as fp_:
for line in salt.utils.data.decode(fp_.readlines()):
if '=' not in line:
ret_commented.append(line)
continue
comps = line.split('=')
value = '='.join(comps[1:]).strip()
comment = None
if value.strip().startswith('#'):
vcomps = value.strip().split('#')
value = vcomps[1].strip()
comment = '#'.join(vcomps[1:]).strip()
ret_commented.append({comps[0].strip(): {
'value': value,
'comment': comment,
}})
else:
ret_commented.append({comps[0].strip(): value})
ret_simple[comps[0].strip()] = value
if out_format == 'simple':
return ret_simple
return ret_commented
def write_conf(conf_file, conf):
'''
Write out an LXC configuration file
This is normally only used internally. The format of the data structure
must match that which is returned from ``lxc.read_conf()``, with
``out_format`` set to ``commented``.
An example might look like:
.. code-block:: python
[
{'lxc.utsname': '$CONTAINER_NAME'},
'# This is a commented line\\n',
'\\n',
{'lxc.mount': '$CONTAINER_FSTAB'},
{'lxc.rootfs': {'comment': 'This is another test',
'value': 'This is another test'}},
'\\n',
{'lxc.network.type': 'veth'},
{'lxc.network.flags': 'up'},
{'lxc.network.link': 'br0'},
{'lxc.network.mac': '$CONTAINER_MACADDR'},
{'lxc.network.ipv4': '$CONTAINER_IPADDR'},
{'lxc.network.name': '$CONTAINER_DEVICENAME'},
]
CLI Example:
.. code-block:: bash
salt 'minion' lxc.write_conf /etc/lxc/mycontainer.conf \\
out_format=commented
'''
if not isinstance(conf, list):
raise SaltInvocationError('Configuration must be passed as a list')
# construct the content prior to write to the file
# to avoid half written configs
content = ''
for line in conf:
if isinstance(line, (six.text_type, six.string_types)):
content += line
elif isinstance(line, dict):
for key in list(line.keys()):
out_line = None
if isinstance(
line[key],
(six.text_type, six.string_types, six.integer_types, float)
):
out_line = ' = '.join((key, "{0}".format(line[key])))
elif isinstance(line[key], dict):
out_line = ' = '.join((key, line[key]['value']))
if 'comment' in line[key]:
out_line = ' # '.join((out_line, line[key]['comment']))
if out_line:
content += out_line
content += '\n'
with salt.utils.files.fopen(conf_file, 'w') as fp_:
fp_.write(salt.utils.stringutils.to_str(content))
return {}
def edit_conf(conf_file,
out_format='simple',
read_only=False,
lxc_config=None,
**kwargs):
'''
Edit an LXC configuration file. If a setting is already present inside the
file, its value will be replaced. If it does not exist, it will be appended
to the end of the file. Comments and blank lines will be kept in-tact if
they already exist in the file.
out_format:
Set to simple if you need backward compatibility (multiple items for a
simple key is not supported)
read_only:
return only the edited configuration without applying it
to the underlying lxc configuration file
lxc_config:
List of dict containning lxc configuration items
For network configuration, you also need to add the device it belongs
to, otherwise it will default to eth0.
Also, any change to a network parameter will result in the whole
network reconfiguration to avoid mismatchs, be aware of that !
After the file is edited, its contents will be returned. By default, it
will be returned in ``simple`` format, meaning an unordered dict (which
may not represent the actual file order). Passing in an ``out_format`` of
``commented`` will return a data structure which accurately represents the
order and content of the file.
CLI Example:
.. code-block:: bash
salt 'minion' lxc.edit_conf /etc/lxc/mycontainer.conf \\
out_format=commented lxc.network.type=veth
salt 'minion' lxc.edit_conf /etc/lxc/mycontainer.conf \\
out_format=commented \\
lxc_config="[{'lxc.network.name': 'eth0', \\
'lxc.network.ipv4': '1.2.3.4'},
{'lxc.network.name': 'eth2', \\
'lxc.network.ipv4': '1.2.3.5',\\
'lxc.network.gateway': '1.2.3.1'}]"
'''
data = []
try:
conf = read_conf(conf_file, out_format=out_format)
except Exception:
conf = []
if not lxc_config:
lxc_config = []
lxc_config = copy.deepcopy(lxc_config)
# search if we want to access net config
# in that case, we will replace all the net configuration
net_config = []
for lxc_kws in lxc_config + [kwargs]:
net_params = {}
for kwarg in [a for a in lxc_kws]:
if kwarg.startswith('__'):
continue
if kwarg.startswith('lxc.network.'):
net_params[kwarg] = lxc_kws[kwarg]
lxc_kws.pop(kwarg, None)
if net_params:
net_config.append(net_params)
nic_opts = salt.utils.odict.OrderedDict()
for params in net_config:
dev = params.get('lxc.network.name', DEFAULT_NIC)
dev_opts = nic_opts.setdefault(dev, salt.utils.odict.OrderedDict())
for param in params:
opt = param.replace('lxc.network.', '')
opt = {'hwaddr': 'mac'}.get(opt, opt)
dev_opts[opt] = params[param]
net_changes = []
if nic_opts:
net_changes = _config_list(conf, only_net=True,
**{'network_profile': DEFAULT_NIC,
'nic_opts': nic_opts})
if net_changes:
lxc_config.extend(net_changes)
for line in conf:
if not isinstance(line, dict):
data.append(line)
continue
else:
for key in list(line.keys()):
val = line[key]
if net_changes and key.startswith('lxc.network.'):
continue
found = False
for ix in range(len(lxc_config)):
kw = lxc_config[ix]
if key in kw:
found = True
data.append({key: kw[key]})
del kw[key]
if not found:
data.append({key: val})
for lxc_kws in lxc_config:
for kwarg in lxc_kws:
data.append({kwarg: lxc_kws[kwarg]})
if read_only:
return data
write_conf(conf_file, data)
return read_conf(conf_file, out_format)
def reboot(name, path=None):
'''
Reboot a container.
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Examples:
.. code-block:: bash
salt 'minion' lxc.reboot myvm
'''
ret = {'result': True,
'changes': {},
'comment': '{0} rebooted'.format(name)}
does_exist = exists(name, path=path)
if does_exist and (state(name, path=path) == 'running'):
try:
stop(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
ret['result'] = False
return ret
if does_exist and (state(name, path=path) != 'running'):
try:
start(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
ret['result'] = False
return ret
ret['changes'][name] = 'rebooted'
return ret
def reconfigure(name,
cpu=None,
cpuset=None,
cpushare=None,
memory=None,
profile=None,
network_profile=None,
nic_opts=None,
bridge=None,
gateway=None,
autostart=None,
utsname=None,
rootfs=None,
path=None,
**kwargs):
'''
Reconfigure a container.
This only applies to a few property
name
Name of the container.
utsname
utsname of the container.
.. versionadded:: 2016.3.0
rootfs
rootfs of the container.
.. versionadded:: 2016.3.0
cpu
Select a random number of cpu cores and assign it to the cpuset, if the
cpuset option is set then this option will be ignored
cpuset
Explicitly define the cpus this container will be bound to
cpushare
cgroups cpu shares.
autostart
autostart container on reboot
memory
cgroups memory limit, in MB.
(0 for nolimit, None for old default 1024MB)
gateway
the ipv4 gateway to use
the default does nothing more than lxcutils does
bridge
the bridge to use
the default does nothing more than lxcutils does
nic
Network interfaces profile (defined in config or pillar).
nic_opts
Extra options for network interfaces, will override
``{"eth0": {"mac": "aa:bb:cc:dd:ee:ff", "ipv4": "10.1.1.1", "ipv6": "2001:db8::ff00:42:8329"}}``
or
``{"eth0": {"mac": "aa:bb:cc:dd:ee:ff", "ipv4": "10.1.1.1/24", "ipv6": "2001:db8::ff00:42:8329"}}``
path
path to the container parent
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt-call -lall mc_lxc_fork.reconfigure foobar nic_opts="{'eth1': {'mac': '00:16:3e:dd:ee:44'}}" memory=4
'''
changes = {}
cpath = get_root_path(path)
path = os.path.join(cpath, name, 'config')
ret = {'name': name,
'comment': 'config for {0} up to date'.format(name),
'result': True,
'changes': changes}
profile = get_container_profile(copy.deepcopy(profile))
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, _marker)
profile_match = profile.pop(key, default)
# let kwarg overrides be the preferred choice
if kw_overrides_match is _marker:
return profile_match
return kw_overrides_match
if nic_opts is not None and not network_profile:
network_profile = DEFAULT_NIC
if autostart is not None:
autostart = select('autostart', autostart)
else:
autostart = 'keep'
if not utsname:
utsname = select('utsname', utsname)
if os.path.exists(path):
old_chunks = read_conf(path, out_format='commented')
make_kw = salt.utils.odict.OrderedDict([
('utsname', utsname),
('rootfs', rootfs),
('autostart', autostart),
('cpu', cpu),
('gateway', gateway),
('cpuset', cpuset),
('cpushare', cpushare),
('network_profile', network_profile),
('nic_opts', nic_opts),
('bridge', bridge)])
# match 0 and none as memory = 0 in lxc config is harmful
if memory:
make_kw['memory'] = memory
kw = salt.utils.odict.OrderedDict()
for key, val in six.iteritems(make_kw):
if val is not None:
kw[key] = val
new_cfg = _config_list(conf_tuples=old_chunks, **kw)
if new_cfg:
edit_conf(path, out_format='commented', lxc_config=new_cfg)
chunks = read_conf(path, out_format='commented')
if old_chunks != chunks:
ret['comment'] = '{0} lxc config updated'.format(name)
if state(name, path=path) == 'running':
cret = reboot(name, path=path)
ret['result'] = cret['result']
return ret
def apply_network_profile(name, network_profile, nic_opts=None, path=None):
'''
.. versionadded:: 2015.5.0
Apply a network profile to a container
network_profile
profile name or default values (dict)
nic_opts
values to override in defaults (dict)
indexed by nic card names
path
path to the container parent
.. versionadded:: 2015.8.0
CLI Examples:
.. code-block:: bash
salt 'minion' lxc.apply_network_profile web1 centos
salt 'minion' lxc.apply_network_profile web1 centos \\
nic_opts="{'eth0': {'mac': 'xx:xx:xx:xx:xx:xx'}}"
salt 'minion' lxc.apply_network_profile web1 \\
"{'eth0': {'mac': 'xx:xx:xx:xx:xx:yy'}}"
nic_opts="{'eth0': {'mac': 'xx:xx:xx:xx:xx:xx'}}"
The special case to disable use of ethernet nics:
.. code-block:: bash
salt 'minion' lxc.apply_network_profile web1 centos \\
"{eth0: {disable: true}}"
'''
cpath = get_root_path(path)
cfgpath = os.path.join(cpath, name, 'config')
before = []
with salt.utils.files.fopen(cfgpath, 'r') as fp_:
for line in fp_:
before.append(line)
lxcconfig = _LXCConfig(name=name, path=path)
old_net = lxcconfig._filter_data('lxc.network')
network_params = {}
for param in _network_conf(
conf_tuples=old_net,
network_profile=network_profile, nic_opts=nic_opts
):
network_params.update(param)
if network_params:
edit_conf(cfgpath, out_format='commented', **network_params)
after = []
with salt.utils.files.fopen(cfgpath, 'r') as fp_:
for line in fp_:
after.append(line)
diff = ''
for line in difflib.unified_diff(before,
after,
fromfile='before',
tofile='after'):
diff += line
return diff
def get_pid(name, path=None):
'''
Returns a container pid.
Throw an exception if the container isn't running.
CLI Example:
.. code-block:: bash
salt '*' lxc.get_pid name
'''
if name not in list_(limit='running', path=path):
raise CommandExecutionError('Container {0} is not running, can\'t determine PID'.format(name))
info = __salt__['cmd.run']('lxc-info -n {0}'.format(name)).split("\n")
pid = [line.split(':')[1].strip() for line in info if re.match(r'\s*PID', line)][0]
return pid
def add_veth(name, interface_name, bridge=None, path=None):
'''
Add a veth to a container.
Note : this function doesn't update the container config, just add the interface at runtime
name
Name of the container
interface_name
Name of the interface in the container
bridge
Name of the bridge to attach the interface to (facultative)
CLI Examples:
.. code-block:: bash
salt '*' lxc.add_veth container_name eth1 br1
salt '*' lxc.add_veth container_name eth1
'''
# Get container init PID
pid = get_pid(name, path=path)
# Generate a ramdom string for veth and ensure that is isn't present on the system
while True:
random_veth = 'veth'+''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(6))
if random_veth not in __salt__['network.interfaces']().keys():
break
# Check prerequisites
if not __salt__['file.directory_exists']('/var/run/'):
raise CommandExecutionError('Directory /var/run required for lxc.add_veth doesn\'t exists')
if not __salt__['file.file_exists']('/proc/{0}/ns/net'.format(pid)):
raise CommandExecutionError('Proc file for container {0} network namespace doesn\'t exists'.format(name))
if not __salt__['file.directory_exists']('/var/run/netns'):
__salt__['file.mkdir']('/var/run/netns')
# Ensure that the symlink is up to date (change on container restart)
if __salt__['file.is_link']('/var/run/netns/{0}'.format(name)):
__salt__['file.remove']('/var/run/netns/{0}'.format(name))
__salt__['file.symlink']('/proc/{0}/ns/net'.format(pid), '/var/run/netns/{0}'.format(name))
# Ensure that interface doesn't exists
interface_exists = 0 == __salt__['cmd.retcode']('ip netns exec {netns} ip address list {interface}'.format(
netns=name,
interface=interface_name
))
if interface_exists:
raise CommandExecutionError('Interface {interface} already exists in {container}'.format(
interface=interface_name,
container=name
))
# Create veth and bring it up
if __salt__['cmd.retcode']('ip link add name {veth} type veth peer name {veth}_c'.format(veth=random_veth)) != 0:
raise CommandExecutionError('Error while creating the veth pair {0}'.format(random_veth))
if __salt__['cmd.retcode']('ip link set dev {0} up'.format(random_veth)) != 0:
raise CommandExecutionError('Error while bringing up host-side veth {0}'.format(random_veth))
# Attach it to the container
attached = 0 == __salt__['cmd.retcode']('ip link set dev {veth}_c netns {container} name {interface_name}'.format(
veth=random_veth,
container=name,
interface_name=interface_name
))
if not attached:
raise CommandExecutionError('Error while attaching the veth {veth} to container {container}'.format(
veth=random_veth,
container=name
))
__salt__['file.remove']('/var/run/netns/{0}'.format(name))
if bridge is not None:
__salt__['bridge.addif'](bridge, random_veth)
|
saltstack/salt
|
salt/modules/lxc.py
|
_network_conf
|
python
|
def _network_conf(conf_tuples=None, **kwargs):
'''
Network configuration defaults
network_profile
as for containers, we can either call this function
either with a network_profile dict or network profile name
in the kwargs
nic_opts
overrides or extra nics in the form {nic_name: {set: tings}
'''
nic = kwargs.get('network_profile', None)
ret = []
nic_opts = kwargs.get('nic_opts', {})
if nic_opts is None:
# coming from elsewhere
nic_opts = {}
if not conf_tuples:
conf_tuples = []
old = _get_veths(conf_tuples)
if not old:
old = {}
# if we have a profile name, get the profile and load the network settings
# this will obviously by default look for a profile called "eth0"
# or by what is defined in nic_opts
# and complete each nic settings by sane defaults
if nic and isinstance(nic, (six.string_types, dict)):
nicp = get_network_profile(nic)
else:
nicp = {}
if DEFAULT_NIC not in nicp:
nicp[DEFAULT_NIC] = {}
kwargs = copy.deepcopy(kwargs)
gateway = kwargs.pop('gateway', None)
bridge = kwargs.get('bridge', None)
if nic_opts:
for dev, args in six.iteritems(nic_opts):
ethx = nicp.setdefault(dev, {})
try:
ethx = salt.utils.dictupdate.update(ethx, args)
except AttributeError:
raise SaltInvocationError('Invalid nic_opts configuration')
ifs = [a for a in nicp]
ifs += [a for a in old if a not in nicp]
ifs.sort()
gateway_set = False
for dev in ifs:
args = nicp.get(dev, {})
opts = nic_opts.get(dev, {}) if nic_opts else {}
old_if = old.get(dev, {})
disable = opts.get('disable', args.get('disable', False))
if disable:
continue
mac = opts.get('mac',
opts.get('hwaddr',
args.get('mac',
args.get('hwaddr', ''))))
type_ = opts.get('type', args.get('type', ''))
flags = opts.get('flags', args.get('flags', ''))
link = opts.get('link', args.get('link', ''))
ipv4 = opts.get('ipv4', args.get('ipv4', ''))
ipv6 = opts.get('ipv6', args.get('ipv6', ''))
infos = salt.utils.odict.OrderedDict([
('lxc.network.type', {
'test': not type_,
'value': type_,
'old': old_if.get('lxc.network.type'),
'default': 'veth'}),
('lxc.network.name', {
'test': False,
'value': dev,
'old': dev,
'default': dev}),
('lxc.network.flags', {
'test': not flags,
'value': flags,
'old': old_if.get('lxc.network.flags'),
'default': 'up'}),
('lxc.network.link', {
'test': not link,
'value': link,
'old': old_if.get('lxc.network.link'),
'default': search_lxc_bridge()}),
('lxc.network.hwaddr', {
'test': not mac,
'value': mac,
'old': old_if.get('lxc.network.hwaddr'),
'default': salt.utils.network.gen_mac()}),
('lxc.network.ipv4', {
'test': not ipv4,
'value': ipv4,
'old': old_if.get('lxc.network.ipv4', ''),
'default': None}),
('lxc.network.ipv6', {
'test': not ipv6,
'value': ipv6,
'old': old_if.get('lxc.network.ipv6', ''),
'default': None})])
# for each parameter, if not explicitly set, the
# config value present in the LXC configuration should
# take precedence over the profile configuration
for info in list(infos.keys()):
bundle = infos[info]
if bundle['test']:
if bundle['old']:
bundle['value'] = bundle['old']
elif bundle['default']:
bundle['value'] = bundle['default']
for info, data in six.iteritems(infos):
if data['value']:
ret.append({info: data['value']})
for key, val in six.iteritems(args):
if key == 'link' and bridge:
val = bridge
val = opts.get(key, val)
if key in [
'type', 'flags', 'name',
'gateway', 'mac', 'link', 'ipv4', 'ipv6'
]:
continue
ret.append({'lxc.network.{0}'.format(key): val})
# gateway (in automode) must be appended following network conf !
if not gateway:
gateway = args.get('gateway', None)
if gateway is not None and not gateway_set:
ret.append({'lxc.network.ipv4.gateway': gateway})
# only one network gateway ;)
gateway_set = True
# normally, this won't happen
# set the gateway if specified even if we did
# not managed the network underlying
if gateway is not None and not gateway_set:
ret.append({'lxc.network.ipv4.gateway': gateway})
# only one network gateway ;)
gateway_set = True
new = _get_veths(ret)
# verify that we did not loose the mac settings
for iface in [a for a in new]:
ndata = new[iface]
nmac = ndata.get('lxc.network.hwaddr', '')
ntype = ndata.get('lxc.network.type', '')
omac, otype = '', ''
if iface in old:
odata = old[iface]
omac = odata.get('lxc.network.hwaddr', '')
otype = odata.get('lxc.network.type', '')
# default for network type is setted here
# attention not to change the network type
# without a good and explicit reason to.
if otype and not ntype:
ntype = otype
if not ntype:
ntype = 'veth'
new[iface]['lxc.network.type'] = ntype
if omac and not nmac:
new[iface]['lxc.network.hwaddr'] = omac
ret = []
for val in six.itervalues(new):
for row in val:
ret.append(salt.utils.odict.OrderedDict([(row, val[row])]))
# on old versions of lxc, still support the gateway auto mode
# if we didn't explicitly say no to
# (lxc.network.ipv4.gateway: auto)
if _LooseVersion(version()) <= _LooseVersion('1.0.7') and \
True not in ['lxc.network.ipv4.gateway' in a for a in ret] and \
True in ['lxc.network.ipv4' in a for a in ret]:
ret.append({'lxc.network.ipv4.gateway': 'auto'})
return ret
|
Network configuration defaults
network_profile
as for containers, we can either call this function
either with a network_profile dict or network profile name
in the kwargs
nic_opts
overrides or extra nics in the form {nic_name: {set: tings}
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/lxc.py#L702-L874
|
[
"def _get_veths(net_data):\n '''\n Parse the nic setup inside lxc conf tuples back to a dictionary indexed by\n network interface\n '''\n if isinstance(net_data, dict):\n net_data = list(net_data.items())\n nics = salt.utils.odict.OrderedDict()\n current_nic = salt.utils.odict.OrderedDict()\n no_names = True\n for item in net_data:\n if item and isinstance(item, dict):\n item = list(item.items())[0]\n # skip LXC configuration comment lines, and play only with tuples conf\n elif isinstance(item, six.string_types):\n # deal with reflection of commented lxc configs\n sitem = item.strip()\n if sitem.startswith('#') or not sitem:\n continue\n elif '=' in item:\n item = tuple([a.strip() for a in item.split('=', 1)])\n if item[0] == 'lxc.network.type':\n current_nic = salt.utils.odict.OrderedDict()\n if item[0] == 'lxc.network.name':\n no_names = False\n nics[item[1].strip()] = current_nic\n current_nic[item[0].strip()] = item[1].strip()\n # if not ethernet card name has been collected, assuming we collected\n # data for eth0\n if no_names and current_nic:\n nics[DEFAULT_NIC] = current_nic\n return nics\n"
] |
# -*- coding: utf-8 -*-
'''
Control Linux Containers via Salt
:depends: lxc package for distribution
lxc >= 1.0 (even beta alpha) is required
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import datetime
import copy
import string
import textwrap
import difflib
import logging
import tempfile
import os
import pipes
import time
import shutil
import re
import random
# Import salt libs
import salt.utils.args
import salt.utils.cloud
import salt.utils.data
import salt.utils.dictupdate
import salt.utils.files
import salt.utils.functools
import salt.utils.hashutils
import salt.utils.network
import salt.utils.odict
import salt.utils.path
import salt.utils.stringutils
from salt.exceptions import CommandExecutionError, SaltInvocationError
import salt.config
from salt.utils.versions import LooseVersion as _LooseVersion
# Import 3rd-party libs
from salt.ext import six
# pylint: disable=import-error,no-name-in-module
from salt.ext.six.moves import range # pylint: disable=redefined-builtin
from salt.ext.six.moves.urllib.parse import urlparse as _urlparse
# pylint: enable=import-error,no-name-in-module
# Set up logging
log = logging.getLogger(__name__)
# Don't shadow built-in's.
__func_alias__ = {
'list_': 'list',
'ls_': 'ls'
}
__virtualname__ = 'lxc'
DEFAULT_NIC = 'eth0'
DEFAULT_BR = 'br0'
SEED_MARKER = '/lxc.initial_seed'
EXEC_DRIVER = 'lxc-attach'
DEFAULT_PATH = '/var/lib/lxc'
_marker = object()
def __virtual__():
if salt.utils.path.which('lxc-start'):
return __virtualname__
# To speed up the whole thing, we decided to not use the
# subshell way and assume things are in place for lxc
# Discussion made by @kiorky and @thatch45
# lxc-version presence is not sufficient, in lxc1.0 alpha
# (precise backports), we have it and it is sufficient
# for the module to execute.
# elif salt.utils.path.which('lxc-version'):
# passed = False
# try:
# passed = subprocess.check_output(
# 'lxc-version').split(':')[1].strip() >= '1.0'
# except Exception:
# pass
# if not passed:
# log.warning('Support for lxc < 1.0 may be incomplete.')
# return 'lxc'
# return False
#
return (False, 'The lxc execution module cannot be loaded: the lxc-start binary is not in the path.')
def get_root_path(path):
'''
Get the configured lxc root for containers
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.get_root_path
'''
if not path:
path = __opts__.get('lxc.root_path', DEFAULT_PATH)
return path
def version():
'''
Return the actual lxc client version
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.version
'''
k = 'lxc.version'
if not __context__.get(k, None):
cversion = __salt__['cmd.run_all']('lxc-info --version')
if not cversion['retcode']:
ver = _LooseVersion(cversion['stdout'])
if ver < _LooseVersion('1.0'):
raise CommandExecutionError('LXC should be at least 1.0')
__context__[k] = "{0}".format(ver)
return __context__.get(k, None)
def _clear_context():
'''
Clear any lxc variables set in __context__
'''
for var in [x for x in __context__ if x.startswith('lxc.')]:
log.trace('Clearing __context__[\'%s\']', var)
__context__.pop(var, None)
def _ip_sort(ip):
'''Ip sorting'''
idx = '001'
if ip == '127.0.0.1':
idx = '200'
if ip == '::1':
idx = '201'
elif '::' in ip:
idx = '100'
return '{0}___{1}'.format(idx, ip)
def search_lxc_bridges():
'''
Search which bridges are potentially available as LXC bridges
CLI Example:
.. code-block:: bash
salt '*' lxc.search_lxc_bridges
'''
bridges = __context__.get('lxc.bridges', None)
# either match not yet called or no bridges were found
# to handle the case where lxc was not installed on the first
# call
if not bridges:
bridges = set()
running_bridges = set()
bridges.add(DEFAULT_BR)
try:
output = __salt__['cmd.run_all']('brctl show')
for line in output['stdout'].splitlines()[1:]:
if not line.startswith(' '):
running_bridges.add(line.split()[0].strip())
except (SaltInvocationError, CommandExecutionError):
pass
for ifc, ip in six.iteritems(
__grains__.get('ip_interfaces', {})
):
if ifc in running_bridges:
bridges.add(ifc)
elif os.path.exists(
'/sys/devices/virtual/net/{0}/bridge'.format(ifc)
):
bridges.add(ifc)
bridges = list(bridges)
# if we found interfaces that have lxc in their names
# we filter them as being the potential lxc bridges
# we also try to default on br0 on other cases
def sort_bridges(a):
pref = 'z'
if 'lxc' in a:
pref = 'a'
elif 'br0' == a:
pref = 'c'
return '{0}_{1}'.format(pref, a)
bridges.sort(key=sort_bridges)
__context__['lxc.bridges'] = bridges
return bridges
def search_lxc_bridge():
'''
Search the first bridge which is potentially available as LXC bridge
CLI Example:
.. code-block:: bash
salt '*' lxc.search_lxc_bridge
'''
return search_lxc_bridges()[0]
def _get_salt_config(config, **kwargs):
if not config:
config = kwargs.get('minion', {})
if not config:
config = {}
config.setdefault('master',
kwargs.get('master',
__opts__.get('master',
__opts__['id'])))
config.setdefault(
'master_port',
kwargs.get('master_port',
__opts__.get('master_port',
__opts__.get('ret_port',
__opts__.get('4506')))))
if not config['master']:
config = {}
return config
def cloud_init_interface(name, vm_=None, **kwargs):
'''
Interface between salt.cloud.lxc driver and lxc.init
``vm_`` is a mapping of vm opts in the salt.cloud format
as documented for the lxc driver.
This can be used either:
- from the salt cloud driver
- because you find the argument to give easier here
than using directly lxc.init
.. warning::
BE REALLY CAREFUL CHANGING DEFAULTS !!!
IT'S A RETRO COMPATIBLE INTERFACE WITH
THE SALT CLOUD DRIVER (ask kiorky).
name
name of the lxc container to create
pub_key
public key to preseed the minion with.
Can be the keycontent or a filepath
priv_key
private key to preseed the minion with.
Can be the keycontent or a filepath
path
path to the container parent directory (default: /var/lib/lxc)
.. versionadded:: 2015.8.0
profile
:ref:`profile <tutorial-lxc-profiles-container>` selection
network_profile
:ref:`network profile <tutorial-lxc-profiles-network>` selection
nic_opts
per interface settings compatibles with
network profile (ipv4/ipv6/link/gateway/mac/netmask)
eg::
- {'eth0': {'mac': '00:16:3e:01:29:40',
'gateway': None, (default)
'link': 'br0', (default)
'gateway': None, (default)
'netmask': '', (default)
'ip': '22.1.4.25'}}
unconditional_install
given to lxc.bootstrap (see relative doc)
force_install
given to lxc.bootstrap (see relative doc)
config
any extra argument for the salt minion config
dnsservers
list of DNS servers to set inside the container
dns_via_dhcp
do not set the dns servers, let them be set by the dhcp.
autostart
autostart the container at boot time
password
administrative password for the container
bootstrap_delay
delay before launching bootstrap script at Container init
.. warning::
Legacy but still supported options:
from_container
which container we use as a template
when running lxc.clone
image
which template do we use when we
are using lxc.create. This is the default
mode unless you specify something in from_container
backing
which backing store to use.
Values can be: overlayfs, dir(default), lvm, zfs, brtfs
fstype
When using a blockdevice level backing store,
which filesystem to use on
size
When using a blockdevice level backing store,
which size for the filesystem to use on
snapshot
Use snapshot when cloning the container source
vgname
if using LVM: vgname
lvname
if using LVM: lvname
thinpool:
if using LVM: thinpool
ip
ip for the primary nic
mac
mac address for the primary nic
netmask
netmask for the primary nic (24)
= ``vm_.get('netmask', '24')``
bridge
bridge for the primary nic (lxcbr0)
gateway
network gateway for the container
additional_ips
additional ips which will be wired on the main bridge (br0)
which is connected to internet.
Be aware that you may use manual virtual mac addresses
providen by you provider (online, ovh, etc).
This is a list of mappings {ip: '', mac: '', netmask:''}
Set gateway to None and an interface with a gateway
to escape from another interface that eth0.
eg::
- {'mac': '00:16:3e:01:29:40',
'gateway': None, (default)
'link': 'br0', (default)
'netmask': '', (default)
'ip': '22.1.4.25'}
users
administrative users for the container
default: [root] and [root, ubuntu] on ubuntu
default_nic
name of the first interface, you should
really not override this
CLI Example:
.. code-block:: bash
salt '*' lxc.cloud_init_interface foo
'''
if vm_ is None:
vm_ = {}
vm_ = copy.deepcopy(vm_)
vm_ = salt.utils.dictupdate.update(vm_, kwargs)
profile_data = copy.deepcopy(
vm_.get('lxc_profile',
vm_.get('profile', {})))
if not isinstance(profile_data, (dict, six.string_types)):
profile_data = {}
profile = get_container_profile(profile_data)
def _cloud_get(k, default=None):
return vm_.get(k, profile.get(k, default))
if name is None:
name = vm_['name']
# if we are on ubuntu, default to ubuntu
default_template = ''
if __grains__.get('os', '') in ['Ubuntu']:
default_template = 'ubuntu'
image = _cloud_get('image')
if not image:
_cloud_get('template', default_template)
backing = _cloud_get('backing', 'dir')
if image:
profile['template'] = image
vgname = _cloud_get('vgname', None)
if vgname:
profile['vgname'] = vgname
if backing:
profile['backing'] = backing
snapshot = _cloud_get('snapshot', False)
autostart = bool(_cloud_get('autostart', True))
dnsservers = _cloud_get('dnsservers', [])
dns_via_dhcp = _cloud_get('dns_via_dhcp', True)
password = _cloud_get('password', 's3cr3t')
password_encrypted = _cloud_get('password_encrypted', False)
fstype = _cloud_get('fstype', None)
lvname = _cloud_get('lvname', None)
thinpool = _cloud_get('thinpool', None)
pub_key = _cloud_get('pub_key', None)
priv_key = _cloud_get('priv_key', None)
size = _cloud_get('size', '20G')
script = _cloud_get('script', None)
script_args = _cloud_get('script_args', None)
users = _cloud_get('users', None)
if users is None:
users = []
ssh_username = _cloud_get('ssh_username', None)
if ssh_username and (ssh_username not in users):
users.append(ssh_username)
network_profile = _cloud_get('network_profile', None)
nic_opts = kwargs.get('nic_opts', None)
netmask = _cloud_get('netmask', '24')
path = _cloud_get('path', None)
bridge = _cloud_get('bridge', None)
gateway = _cloud_get('gateway', None)
unconditional_install = _cloud_get('unconditional_install', False)
force_install = _cloud_get('force_install', True)
config = _get_salt_config(_cloud_get('config', {}), **vm_)
default_nic = _cloud_get('default_nic', DEFAULT_NIC)
# do the interface with lxc.init mainly via nic_opts
# to avoid extra and confusing extra use cases.
if not isinstance(nic_opts, dict):
nic_opts = salt.utils.odict.OrderedDict()
# have a reference to the default nic
eth0 = nic_opts.setdefault(default_nic,
salt.utils.odict.OrderedDict())
# lxc config is based of ifc order, be sure to use odicts.
if not isinstance(nic_opts, salt.utils.odict.OrderedDict):
bnic_opts = salt.utils.odict.OrderedDict()
bnic_opts.update(nic_opts)
nic_opts = bnic_opts
gw = None
# legacy salt.cloud scheme for network interfaces settings support
bridge = _cloud_get('bridge', None)
ip = _cloud_get('ip', None)
mac = _cloud_get('mac', None)
if ip:
fullip = ip
if netmask:
fullip += '/{0}'.format(netmask)
eth0['ipv4'] = fullip
if mac is not None:
eth0['mac'] = mac
for ix, iopts in enumerate(_cloud_get("additional_ips", [])):
ifh = "eth{0}".format(ix+1)
ethx = nic_opts.setdefault(ifh, {})
if gw is None:
gw = iopts.get('gateway', ethx.get('gateway', None))
if gw:
# only one and only one default gateway is allowed !
eth0.pop('gateway', None)
gateway = None
# even if the gateway if on default "eth0" nic
# and we popped it will work
# as we reinject or set it here.
ethx['gateway'] = gw
elink = iopts.get('link', ethx.get('link', None))
if elink:
ethx['link'] = elink
# allow dhcp
aip = iopts.get('ipv4', iopts.get('ip', None))
if aip:
ethx['ipv4'] = aip
nm = iopts.get('netmask', '')
if nm:
ethx['ipv4'] += '/{0}'.format(nm)
for i in ('mac', 'hwaddr'):
if i in iopts:
ethx['mac'] = iopts[i]
break
if 'mac' not in ethx:
ethx['mac'] = salt.utils.network.gen_mac()
# last round checking for unique gateway and such
gw = None
for ethx in [a for a in nic_opts]:
ndata = nic_opts[ethx]
if gw:
ndata.pop('gateway', None)
if 'gateway' in ndata:
gw = ndata['gateway']
gateway = None
# only use a default bridge / gateway if we configured them
# via the legacy salt cloud configuration style.
# On other cases, we should rely on settings provided by the new
# salt lxc network profile style configuration which can
# be also be overridden or a per interface basis via the nic_opts dict.
if bridge:
eth0['link'] = bridge
if gateway:
eth0['gateway'] = gateway
#
lxc_init_interface = {}
lxc_init_interface['name'] = name
lxc_init_interface['config'] = config
lxc_init_interface['memory'] = _cloud_get('memory', 0) # nolimit
lxc_init_interface['pub_key'] = pub_key
lxc_init_interface['priv_key'] = priv_key
lxc_init_interface['nic_opts'] = nic_opts
for clone_from in ['clone_from', 'clone', 'from_container']:
# clone_from should default to None if not available
lxc_init_interface['clone_from'] = _cloud_get(clone_from, None)
if lxc_init_interface['clone_from'] is not None:
break
lxc_init_interface['profile'] = profile
lxc_init_interface['snapshot'] = snapshot
lxc_init_interface['dnsservers'] = dnsservers
lxc_init_interface['fstype'] = fstype
lxc_init_interface['path'] = path
lxc_init_interface['vgname'] = vgname
lxc_init_interface['size'] = size
lxc_init_interface['lvname'] = lvname
lxc_init_interface['thinpool'] = thinpool
lxc_init_interface['force_install'] = force_install
lxc_init_interface['unconditional_install'] = (
unconditional_install
)
lxc_init_interface['bootstrap_url'] = script
lxc_init_interface['bootstrap_args'] = script_args
lxc_init_interface['bootstrap_shell'] = _cloud_get('bootstrap_shell', 'sh')
lxc_init_interface['bootstrap_delay'] = _cloud_get('bootstrap_delay', None)
lxc_init_interface['autostart'] = autostart
lxc_init_interface['users'] = users
lxc_init_interface['password'] = password
lxc_init_interface['password_encrypted'] = password_encrypted
# be sure not to let objects goes inside the return
# as this return will be msgpacked for use in the runner !
lxc_init_interface['network_profile'] = network_profile
for i in ['cpu', 'cpuset', 'cpushare']:
if _cloud_get(i, None):
try:
lxc_init_interface[i] = vm_[i]
except KeyError:
lxc_init_interface[i] = profile[i]
return lxc_init_interface
def _get_profile(key, name, **kwargs):
if isinstance(name, dict):
profilename = name.pop('name', None)
return _get_profile(key, profilename, **name)
if name is None:
profile_match = {}
else:
profile_match = \
__salt__['config.get'](
'lxc.{1}:{0}'.format(name, key),
default=None,
merge='recurse'
)
if profile_match is None:
# No matching profile, make the profile an empty dict so that
# overrides can be applied below.
profile_match = {}
if not isinstance(profile_match, dict):
raise CommandExecutionError('lxc.{0} must be a dictionary'.format(key))
# Overlay the kwargs to override matched profile data
overrides = salt.utils.args.clean_kwargs(**copy.deepcopy(kwargs))
profile_match = salt.utils.dictupdate.update(
copy.deepcopy(profile_match),
overrides
)
return profile_match
def get_container_profile(name=None, **kwargs):
'''
.. versionadded:: 2015.5.0
Gather a pre-configured set of container configuration parameters. If no
arguments are passed, an empty profile is returned.
Profiles can be defined in the minion or master config files, or in pillar
or grains, and are loaded using :mod:`config.get
<salt.modules.config.get>`. The key under which LXC profiles must be
configured is ``lxc.container_profile.profile_name``. An example container
profile would be as follows:
.. code-block:: yaml
lxc.container_profile:
ubuntu:
template: ubuntu
backing: lvm
vgname: lxc
size: 1G
Parameters set in a profile can be overridden by passing additional
container creation arguments (such as the ones passed to :mod:`lxc.create
<salt.modules.lxc.create>`) to this function.
A profile can be defined either as the name of the profile, or a dictionary
of variable names and values. See the :ref:`LXC Tutorial
<tutorial-lxc-profiles>` for more information on how to use LXC profiles.
CLI Example:
.. code-block:: bash
salt-call lxc.get_container_profile centos
salt-call lxc.get_container_profile ubuntu template=ubuntu backing=overlayfs
'''
profile = _get_profile('container_profile', name, **kwargs)
return profile
def get_network_profile(name=None, **kwargs):
'''
.. versionadded:: 2015.5.0
Gather a pre-configured set of network configuration parameters. If no
arguments are passed, the following default profile is returned:
.. code-block:: python
{'eth0': {'link': 'br0', 'type': 'veth', 'flags': 'up'}}
Profiles can be defined in the minion or master config files, or in pillar
or grains, and are loaded using :mod:`config.get
<salt.modules.config.get>`. The key under which LXC profiles must be
configured is ``lxc.network_profile``. An example network profile would be
as follows:
.. code-block:: yaml
lxc.network_profile.centos:
eth0:
link: br0
type: veth
flags: up
To disable networking entirely:
.. code-block:: yaml
lxc.network_profile.centos:
eth0:
disable: true
Parameters set in a profile can be overridden by passing additional
arguments to this function.
A profile can be passed either as the name of the profile, or a
dictionary of variable names and values. See the :ref:`LXC Tutorial
<tutorial-lxc-profiles>` for more information on how to use network
profiles.
.. warning::
The ``ipv4``, ``ipv6``, ``gateway``, and ``link`` (bridge) settings in
network profiles will only work if the container doesn't redefine the
network configuration (for example in
``/etc/sysconfig/network-scripts/ifcfg-<interface_name>`` on
RHEL/CentOS, or ``/etc/network/interfaces`` on Debian/Ubuntu/etc.)
CLI Example:
.. code-block:: bash
salt-call lxc.get_network_profile default
'''
profile = _get_profile('network_profile', name, **kwargs)
return profile
def _rand_cpu_str(cpu):
'''
Return a random subset of cpus for the cpuset config
'''
cpu = int(cpu)
avail = __salt__['status.nproc']()
if cpu < avail:
return '0-{0}'.format(avail)
to_set = set()
while len(to_set) < cpu:
choice = random.randint(0, avail - 1)
if choice not in to_set:
to_set.add(six.text_type(choice))
return ','.join(sorted(to_set))
def _get_lxc_default_data(**kwargs):
kwargs = copy.deepcopy(kwargs)
ret = {}
for k in ['utsname', 'rootfs']:
val = kwargs.get(k, None)
if val is not None:
ret['lxc.{0}'.format(k)] = val
autostart = kwargs.get('autostart')
# autostart can have made in kwargs, but with the None
# value which is invalid, we need an explicit boolean
# autostart = on is the default.
if autostart is None:
autostart = True
# we will set the regular lxc marker to restart container at
# machine (re)boot only if we did not explicitly ask
# not to touch to the autostart settings via
# autostart == 'keep'
if autostart != 'keep':
if autostart:
ret['lxc.start.auto'] = '1'
else:
ret['lxc.start.auto'] = '0'
memory = kwargs.get('memory')
if memory is not None:
# converting the config value from MB to bytes
ret['lxc.cgroup.memory.limit_in_bytes'] = memory * 1024 * 1024
cpuset = kwargs.get('cpuset')
if cpuset:
ret['lxc.cgroup.cpuset.cpus'] = cpuset
cpushare = kwargs.get('cpushare')
cpu = kwargs.get('cpu')
if cpushare:
ret['lxc.cgroup.cpu.shares'] = cpushare
if cpu and not cpuset:
ret['lxc.cgroup.cpuset.cpus'] = _rand_cpu_str(cpu)
return ret
def _config_list(conf_tuples=None, only_net=False, **kwargs):
'''
Return a list of dicts from the salt level configurations
conf_tuples
_LXCConfig compatible list of entries which can contain
- string line
- tuple (lxc config param,value)
- dict of one entry: {lxc config param: value)
only_net
by default we add to the tuples a reflection of both
the real config if avalaible and a certain amount of
default values like the cpu parameters, the memory
and etc.
On the other hand, we also no matter the case reflect
the network configuration computed from the actual config if
available and given values.
if no_default_loads is set, we will only
reflect the network configuration back to the conf tuples
list
'''
# explicit cast
only_net = bool(only_net)
if not conf_tuples:
conf_tuples = []
kwargs = copy.deepcopy(kwargs)
ret = []
if not only_net:
default_data = _get_lxc_default_data(**kwargs)
for k, val in six.iteritems(default_data):
ret.append({k: val})
net_datas = _network_conf(conf_tuples=conf_tuples, **kwargs)
ret.extend(net_datas)
return ret
def _get_veths(net_data):
'''
Parse the nic setup inside lxc conf tuples back to a dictionary indexed by
network interface
'''
if isinstance(net_data, dict):
net_data = list(net_data.items())
nics = salt.utils.odict.OrderedDict()
current_nic = salt.utils.odict.OrderedDict()
no_names = True
for item in net_data:
if item and isinstance(item, dict):
item = list(item.items())[0]
# skip LXC configuration comment lines, and play only with tuples conf
elif isinstance(item, six.string_types):
# deal with reflection of commented lxc configs
sitem = item.strip()
if sitem.startswith('#') or not sitem:
continue
elif '=' in item:
item = tuple([a.strip() for a in item.split('=', 1)])
if item[0] == 'lxc.network.type':
current_nic = salt.utils.odict.OrderedDict()
if item[0] == 'lxc.network.name':
no_names = False
nics[item[1].strip()] = current_nic
current_nic[item[0].strip()] = item[1].strip()
# if not ethernet card name has been collected, assuming we collected
# data for eth0
if no_names and current_nic:
nics[DEFAULT_NIC] = current_nic
return nics
class _LXCConfig(object):
'''
LXC configuration data
'''
pattern = re.compile(r'^(\S+)(\s*)(=)(\s*)(.*)')
non_interpretable_pattern = re.compile(r'^((#.*)|(\s*))$')
def __init__(self, **kwargs):
kwargs = copy.deepcopy(kwargs)
self.name = kwargs.pop('name', None)
path = get_root_path(kwargs.get('path', None))
self.data = []
if self.name:
self.path = os.path.join(path, self.name, 'config')
if os.path.isfile(self.path):
with salt.utils.files.fopen(self.path) as fhr:
for line in salt.utils.data.decode(fhr.readlines()):
match = self.pattern.findall((line.strip()))
if match:
self.data.append((match[0][0], match[0][-1]))
match = self.non_interpretable_pattern.findall(
(line.strip()))
if match:
self.data.append(('', match[0][0]))
else:
self.path = None
def _replace(key, val):
if val:
self._filter_data(key)
self.data.append((key, val))
default_data = _get_lxc_default_data(**kwargs)
for key, val in six.iteritems(default_data):
_replace(key, val)
old_net = self._filter_data('lxc.network')
net_datas = _network_conf(conf_tuples=old_net, **kwargs)
if net_datas:
for row in net_datas:
self.data.extend(list(row.items()))
# be sure to reset harmful settings
for idx in ['lxc.cgroup.memory.limit_in_bytes']:
if not default_data.get(idx):
self._filter_data(idx)
def as_string(self):
chunks = ('{0[0]}{1}{0[1]}'.format(item, (' = ' if item[0] else '')) for item in self.data)
return '\n'.join(chunks) + '\n'
def write(self):
if self.path:
content = self.as_string()
# 2 step rendering to be sure not to open/wipe the config
# before as_string succeeds.
with salt.utils.files.fopen(self.path, 'w') as fic:
fic.write(salt.utils.stringutils.to_str(content))
fic.flush()
def tempfile(self):
# this might look like the function name is shadowing the
# module, but it's not since the method belongs to the class
ntf = tempfile.NamedTemporaryFile()
ntf.write(self.as_string())
ntf.flush()
return ntf
def _filter_data(self, pattern):
'''
Removes parameters which match the pattern from the config data
'''
removed = []
filtered = []
for param in self.data:
if not param[0].startswith(pattern):
filtered.append(param)
else:
removed.append(param)
self.data = filtered
return removed
def _get_base(**kwargs):
'''
If the needed base does not exist, then create it, if it does exist
create nothing and return the name of the base lxc container so
it can be cloned.
'''
profile = get_container_profile(copy.deepcopy(kwargs.get('profile')))
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, _marker)
profile_match = profile.pop(key, default)
# let kwarg overrides be the preferred choice
if kw_overrides_match is _marker:
return profile_match
return kw_overrides_match
template = select('template')
image = select('image')
vgname = select('vgname')
path = kwargs.get('path', None)
# remove the above three variables from kwargs, if they exist, to avoid
# duplicates if create() is invoked below.
for param in ('path', 'image', 'vgname', 'template'):
kwargs.pop(param, None)
if image:
proto = _urlparse(image).scheme
img_tar = __salt__['cp.cache_file'](image)
img_name = os.path.basename(img_tar)
hash_ = salt.utils.hashutils.get_hash(
img_tar,
__salt__['config.get']('hash_type'))
name = '__base_{0}_{1}_{2}'.format(proto, img_name, hash_)
if not exists(name, path=path):
create(name, template=template, image=image,
path=path, vgname=vgname, **kwargs)
if vgname:
rootfs = os.path.join('/dev', vgname, name)
edit_conf(info(name, path=path)['config'],
out_format='commented', **{'lxc.rootfs': rootfs})
return name
elif template:
name = '__base_{0}'.format(template)
if not exists(name, path=path):
create(name, template=template, image=image, path=path,
vgname=vgname, **kwargs)
if vgname:
rootfs = os.path.join('/dev', vgname, name)
edit_conf(info(name, path=path)['config'],
out_format='commented', **{'lxc.rootfs': rootfs})
return name
return ''
def init(name,
config=None,
cpuset=None,
cpushare=None,
memory=None,
profile=None,
network_profile=None,
nic_opts=None,
cpu=None,
autostart=True,
password=None,
password_encrypted=None,
users=None,
dnsservers=None,
searchdomains=None,
bridge=None,
gateway=None,
pub_key=None,
priv_key=None,
force_install=False,
unconditional_install=False,
bootstrap_delay=None,
bootstrap_args=None,
bootstrap_shell=None,
bootstrap_url=None,
**kwargs):
'''
Initialize a new container.
This is a partial idempotent function as if it is already provisioned, we
will reset a bit the lxc configuration file but much of the hard work will
be escaped as markers will prevent re-execution of harmful tasks.
name
Name of the container
image
A tar archive to use as the rootfs for the container. Conflicts with
the ``template`` argument.
cpus
Select a random number of cpu cores and assign it to the cpuset, if the
cpuset option is set then this option will be ignored
cpuset
Explicitly define the cpus this container will be bound to
cpushare
cgroups cpu shares
autostart
autostart container on reboot
memory
cgroups memory limit, in MB
.. versionchanged:: 2015.5.0
If no value is passed, no limit is set. In earlier Salt versions,
not passing this value causes a 1024MB memory limit to be set, and
it was necessary to pass ``memory=0`` to set no limit.
gateway
the ipv4 gateway to use
the default does nothing more than lxcutils does
bridge
the bridge to use
the default does nothing more than lxcutils does
network_profile
Network profile to use for the container
.. versionadded:: 2015.5.0
nic_opts
Extra options for network interfaces, will override
``{"eth0": {"hwaddr": "aa:bb:cc:dd:ee:ff", "ipv4": "10.1.1.1", "ipv6": "2001:db8::ff00:42:8329"}}``
or
``{"eth0": {"hwaddr": "aa:bb:cc:dd:ee:ff", "ipv4": "10.1.1.1/24", "ipv6": "2001:db8::ff00:42:8329"}}``
users
Users for which the password defined in the ``password`` param should
be set. Can be passed as a comma separated list or a python list.
Defaults to just the ``root`` user.
password
Set the initial password for the users defined in the ``users``
parameter
password_encrypted : False
Set to ``True`` to denote a password hash instead of a plaintext
password
.. versionadded:: 2015.5.0
profile
A LXC profile (defined in config or pillar).
This can be either a real profile mapping or a string
to retrieve it in configuration
start
Start the newly-created container
dnsservers
list of dns servers to set in the container, default [] (no setting)
seed
Seed the container with the minion config. Default: ``True``
install
If salt-minion is not already installed, install it. Default: ``True``
config
Optional config parameters. By default, the id is set to
the name of the container.
master
salt master (default to minion's master)
master_port
salt master port (default to minion's master port)
pub_key
Explicit public key to preseed the minion with (optional).
This can be either a filepath or a string representing the key
priv_key
Explicit private key to preseed the minion with (optional).
This can be either a filepath or a string representing the key
approve_key
If explicit preseeding is not used;
Attempt to request key approval from the master. Default: ``True``
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
clone_from
Original from which to use a clone operation to create the container.
Default: ``None``
bootstrap_delay
Delay in seconds between end of container creation and bootstrapping.
Useful when waiting for container to obtain a DHCP lease.
.. versionadded:: 2015.5.0
bootstrap_url
See lxc.bootstrap
bootstrap_shell
See lxc.bootstrap
bootstrap_args
See lxc.bootstrap
force_install
Force installation even if salt-minion is detected,
this is the way to run vendor bootstrap scripts even
if a salt minion is already present in the container
unconditional_install
Run the script even if the container seems seeded
CLI Example:
.. code-block:: bash
salt 'minion' lxc.init name [cpuset=cgroups_cpuset] \\
[cpushare=cgroups_cpushare] [memory=cgroups_memory] \\
[nic=nic_profile] [profile=lxc_profile] \\
[nic_opts=nic_opts] [start=(True|False)] \\
[seed=(True|False)] [install=(True|False)] \\
[config=minion_config] [approve_key=(True|False) \\
[clone_from=original] [autostart=True] \\
[priv_key=/path_or_content] [pub_key=/path_or_content] \\
[bridge=lxcbr0] [gateway=10.0.3.1] \\
[dnsservers[dns1,dns2]] \\
[users=[foo]] [password='secret'] \\
[password_encrypted=(True|False)]
'''
ret = {'name': name,
'changes': {}}
profile = get_container_profile(copy.deepcopy(profile))
if not network_profile:
network_profile = profile.get('network_profile')
if not network_profile:
network_profile = DEFAULT_NIC
# Changes is a pointer to changes_dict['init']. This method is used so that
# we can have a list of changes as they are made, providing an ordered list
# of things that were changed.
changes_dict = {'init': []}
changes = changes_dict.get('init')
if users is None:
users = []
dusers = ['root']
for user in dusers:
if user not in users:
users.append(user)
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, _marker)
profile_match = profile.pop(key, default)
# let kwarg overrides be the preferred choice
if kw_overrides_match is _marker:
return profile_match
return kw_overrides_match
path = select('path')
bpath = get_root_path(path)
state_pre = state(name, path=path)
tvg = select('vgname')
vgname = tvg if tvg else __salt__['config.get']('lxc.vgname')
start_ = select('start', True)
autostart = select('autostart', autostart)
seed = select('seed', True)
install = select('install', True)
seed_cmd = select('seed_cmd')
salt_config = _get_salt_config(config, **kwargs)
approve_key = select('approve_key', True)
clone_from = select('clone_from')
# If using a volume group then set up to make snapshot cow clones
if vgname and not clone_from:
try:
kwargs['vgname'] = vgname
clone_from = _get_base(profile=profile, **kwargs)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = exc.strerror
if changes:
ret['changes'] = changes_dict
return ret
if not kwargs.get('snapshot') is False:
kwargs['snapshot'] = True
does_exist = exists(name, path=path)
to_reboot = False
remove_seed_marker = False
if does_exist:
pass
elif clone_from:
remove_seed_marker = True
try:
clone(name, clone_from, profile=profile, **kwargs)
changes.append({'create': 'Container cloned'})
except (SaltInvocationError, CommandExecutionError) as exc:
if 'already exists' in exc.strerror:
changes.append({'create': 'Container already exists'})
else:
ret['result'] = False
ret['comment'] = exc.strerror
if changes:
ret['changes'] = changes_dict
return ret
cfg = _LXCConfig(name=name, network_profile=network_profile,
nic_opts=nic_opts, bridge=bridge, path=path,
gateway=gateway, autostart=autostart,
cpuset=cpuset, cpushare=cpushare, memory=memory)
old_chunks = read_conf(cfg.path, out_format='commented')
cfg.write()
chunks = read_conf(cfg.path, out_format='commented')
if old_chunks != chunks:
to_reboot = True
else:
remove_seed_marker = True
cfg = _LXCConfig(network_profile=network_profile,
nic_opts=nic_opts, cpuset=cpuset, path=path,
bridge=bridge, gateway=gateway,
autostart=autostart,
cpushare=cpushare, memory=memory)
with cfg.tempfile() as cfile:
try:
create(name, config=cfile.name, profile=profile, **kwargs)
changes.append({'create': 'Container created'})
except (SaltInvocationError, CommandExecutionError) as exc:
if 'already exists' in exc.strerror:
changes.append({'create': 'Container already exists'})
else:
ret['comment'] = exc.strerror
if changes:
ret['changes'] = changes_dict
return ret
cpath = os.path.join(bpath, name, 'config')
old_chunks = []
if os.path.exists(cpath):
old_chunks = read_conf(cpath, out_format='commented')
new_cfg = _config_list(conf_tuples=old_chunks,
cpu=cpu,
network_profile=network_profile,
nic_opts=nic_opts, bridge=bridge,
cpuset=cpuset, cpushare=cpushare,
memory=memory)
if new_cfg:
edit_conf(cpath, out_format='commented', lxc_config=new_cfg)
chunks = read_conf(cpath, out_format='commented')
if old_chunks != chunks:
to_reboot = True
# last time to be sure any of our property is correctly applied
cfg = _LXCConfig(name=name, network_profile=network_profile,
nic_opts=nic_opts, bridge=bridge, path=path,
gateway=gateway, autostart=autostart,
cpuset=cpuset, cpushare=cpushare, memory=memory)
old_chunks = []
if os.path.exists(cfg.path):
old_chunks = read_conf(cfg.path, out_format='commented')
cfg.write()
chunks = read_conf(cfg.path, out_format='commented')
if old_chunks != chunks:
changes.append({'config': 'Container configuration updated'})
to_reboot = True
if to_reboot:
try:
stop(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
if changes:
ret['changes'] = changes_dict
return ret
if not does_exist or (does_exist and state(name, path=path) != 'running'):
try:
start(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
if changes:
ret['changes'] = changes_dict
return ret
if remove_seed_marker:
run(name,
'rm -f \'{0}\''.format(SEED_MARKER),
path=path,
chroot_fallback=False,
python_shell=False)
# set the default user/password, only the first time
if ret.get('result', True) and password:
gid = '/.lxc.initial_pass'
gids = [gid,
'/lxc.initial_pass',
'/.lxc.{0}.initial_pass'.format(name)]
if not any(retcode(name,
'test -e "{0}"'.format(x),
chroot_fallback=True,
path=path,
ignore_retcode=True) == 0
for x in gids):
# think to touch the default user generated by default templates
# which has a really unsecure passwords...
# root is defined as a member earlier in the code
for default_user in ['ubuntu']:
if (
default_user not in users and
retcode(name,
'id {0}'.format(default_user),
python_shell=False,
path=path,
chroot_fallback=True,
ignore_retcode=True) == 0
):
users.append(default_user)
for user in users:
try:
cret = set_password(name,
users=[user],
path=path,
password=password,
encrypted=password_encrypted)
except (SaltInvocationError, CommandExecutionError) as exc:
msg = '{0}: Failed to set password'.format(
user) + exc.strerror
# only hardfail in unrecoverable situation:
# root cannot be setted up
if user == 'root':
ret['comment'] = msg
ret['result'] = False
else:
log.debug(msg)
if ret.get('result', True):
changes.append({'password': 'Password(s) updated'})
if retcode(name,
('sh -c \'touch "{0}"; test -e "{0}"\''
.format(gid)),
path=path,
chroot_fallback=True,
ignore_retcode=True) != 0:
ret['comment'] = 'Failed to set password marker'
changes[-1]['password'] += '. ' + ret['comment'] + '.'
ret['result'] = False
# set dns servers if any, only the first time
if ret.get('result', True) and dnsservers:
# retro compatibility, test also old markers
gid = '/.lxc.initial_dns'
gids = [gid,
'/lxc.initial_dns',
'/lxc.{0}.initial_dns'.format(name)]
if not any(retcode(name,
'test -e "{0}"'.format(x),
chroot_fallback=True,
path=path,
ignore_retcode=True) == 0
for x in gids):
try:
set_dns(name,
path=path,
dnsservers=dnsservers,
searchdomains=searchdomains)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Failed to set DNS: ' + exc.strerror
ret['result'] = False
else:
changes.append({'dns': 'DNS updated'})
if retcode(name,
('sh -c \'touch "{0}"; test -e "{0}"\''
.format(gid)),
chroot_fallback=True,
path=path,
ignore_retcode=True) != 0:
ret['comment'] = 'Failed to set DNS marker'
changes[-1]['dns'] += '. ' + ret['comment'] + '.'
ret['result'] = False
# retro compatibility, test also old markers
if remove_seed_marker:
run(name,
'rm -f \'{0}\''.format(SEED_MARKER),
path=path,
python_shell=False)
gid = '/.lxc.initial_seed'
gids = [gid, '/lxc.initial_seed']
if (
any(retcode(name,
'test -e {0}'.format(x),
path=path,
chroot_fallback=True,
ignore_retcode=True) == 0
for x in gids) or not ret.get('result', True)
):
pass
elif seed or seed_cmd:
if seed:
try:
result = bootstrap(
name, config=salt_config, path=path,
approve_key=approve_key,
pub_key=pub_key, priv_key=priv_key,
install=install,
force_install=force_install,
unconditional_install=unconditional_install,
bootstrap_delay=bootstrap_delay,
bootstrap_url=bootstrap_url,
bootstrap_shell=bootstrap_shell,
bootstrap_args=bootstrap_args)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Bootstrap failed: ' + exc.strerror
ret['result'] = False
else:
if not result:
ret['comment'] = ('Bootstrap failed, see minion log for '
'more information')
ret['result'] = False
else:
changes.append(
{'bootstrap': 'Container successfully bootstrapped'}
)
elif seed_cmd:
try:
result = __salt__[seed_cmd](info(name, path=path)['rootfs'],
name,
salt_config)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = ('Bootstrap via seed_cmd \'{0}\' failed: {1}'
.format(seed_cmd, exc.strerror))
ret['result'] = False
else:
if not result:
ret['comment'] = ('Bootstrap via seed_cmd \'{0}\' failed, '
'see minion log for more information '
.format(seed_cmd))
ret['result'] = False
else:
changes.append(
{'bootstrap': 'Container successfully bootstrapped '
'using seed_cmd \'{0}\''
.format(seed_cmd)}
)
if ret.get('result', True) and not start_:
try:
stop(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
ret['result'] = False
state_post = state(name, path=path)
if state_pre != state_post:
changes.append({'state': {'old': state_pre, 'new': state_post}})
if ret.get('result', True):
ret['comment'] = ('Container \'{0}\' successfully initialized'
.format(name))
ret['result'] = True
if changes:
ret['changes'] = changes_dict
return ret
def cloud_init(name, vm_=None, **kwargs):
'''
Thin wrapper to lxc.init to be used from the saltcloud lxc driver
name
Name of the container
may be None and then guessed from saltcloud mapping
`vm_`
saltcloud mapping defaults for the vm
CLI Example:
.. code-block:: bash
salt '*' lxc.cloud_init foo
'''
init_interface = cloud_init_interface(name, vm_, **kwargs)
name = init_interface.pop('name', name)
return init(name, **init_interface)
def images(dist=None):
'''
.. versionadded:: 2015.5.0
List the available images for LXC's ``download`` template.
dist : None
Filter results to a single Linux distribution
CLI Examples:
.. code-block:: bash
salt myminion lxc.images
salt myminion lxc.images dist=centos
'''
out = __salt__['cmd.run_stdout'](
'lxc-create -n __imgcheck -t download -- --list',
ignore_retcode=True
)
if 'DIST' not in out:
raise CommandExecutionError(
'Unable to run the \'download\' template script. Is it installed?'
)
ret = {}
passed_header = False
for line in out.splitlines():
try:
distro, release, arch, variant, build_time = line.split()
except ValueError:
continue
if not passed_header:
if distro == 'DIST':
passed_header = True
continue
dist_list = ret.setdefault(distro, [])
dist_list.append({
'release': release,
'arch': arch,
'variant': variant,
'build_time': build_time,
})
if dist is not None:
return dict([(dist, ret.get(dist, []))])
return ret
def templates():
'''
.. versionadded:: 2015.5.0
List the available LXC template scripts installed on the minion
CLI Examples:
.. code-block:: bash
salt myminion lxc.templates
'''
try:
template_scripts = os.listdir('/usr/share/lxc/templates')
except OSError:
return []
else:
return [x[4:] for x in template_scripts if x.startswith('lxc-')]
def _after_ignition_network_profile(cmd,
ret,
name,
network_profile,
path,
nic_opts):
_clear_context()
if ret['retcode'] == 0 and exists(name, path=path):
if network_profile:
network_changes = apply_network_profile(name,
network_profile,
path=path,
nic_opts=nic_opts)
if network_changes:
log.info(
'Network changes from applying network profile \'%s\' '
'to newly-created container \'%s\':\n%s',
network_profile, name, network_changes
)
c_state = state(name, path=path)
return {'result': True,
'state': {'old': None, 'new': c_state}}
else:
if exists(name, path=path):
# destroy the container if it was partially created
cmd = 'lxc-destroy'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0}'.format(name)
__salt__['cmd.retcode'](cmd, python_shell=False)
raise CommandExecutionError(
'Container could not be created with cmd \'{0}\': {1}'
.format(cmd, ret['stderr'])
)
def create(name,
config=None,
profile=None,
network_profile=None,
nic_opts=None,
**kwargs):
'''
Create a new container.
name
Name of the container
config
The config file to use for the container. Defaults to system-wide
config (usually in /etc/lxc/lxc.conf).
profile
Profile to use in container creation (see
:mod:`lxc.get_container_profile
<salt.modules.lxc.get_container_profile>`). Values in a profile will be
overridden by the **Container Creation Arguments** listed below.
network_profile
Network profile to use for container
.. versionadded:: 2015.5.0
**Container Creation Arguments**
template
The template to use. For example, ``ubuntu`` or ``fedora``.
For a full list of available templates, check out
the :mod:`lxc.templates <salt.modules.lxc.templates>` function.
Conflicts with the ``image`` argument.
.. note::
The ``download`` template requires the following three parameters
to be defined in ``options``:
* **dist** - The name of the distribution
* **release** - Release name/version
* **arch** - Architecture of the container
The available images can be listed using the :mod:`lxc.images
<salt.modules.lxc.images>` function.
options
Template-specific options to pass to the lxc-create command. These
correspond to the long options (ones beginning with two dashes) that
the template script accepts. For example:
.. code-block:: bash
options='{"dist": "centos", "release": "6", "arch": "amd64"}'
For available template options, refer to the lxc template scripts
which are ususally located under ``/usr/share/lxc/templates``,
or run ``lxc-create -t <template> -h``.
image
A tar archive to use as the rootfs for the container. Conflicts with
the ``template`` argument.
backing
The type of storage to use. Set to ``lvm`` to use an LVM group.
Defaults to filesystem within /var/lib/lxc.
fstype
Filesystem type to use on LVM logical volume
size : 1G
Size of the volume to create. Only applicable if ``backing=lvm``.
vgname : lxc
Name of the LVM volume group in which to create the volume for this
container. Only applicable if ``backing=lvm``.
lvname
Name of the LVM logical volume in which to create the volume for this
container. Only applicable if ``backing=lvm``.
thinpool
Name of a pool volume that will be used for thin-provisioning this
container. Only applicable if ``backing=lvm``.
nic_opts
give extra opts overriding network profile values
path
parent path for the container creation (default: /var/lib/lxc)
zfsroot
Name of the ZFS root in which to create the volume for this container.
Only applicable if ``backing=zfs``. (default: tank/lxc)
.. versionadded:: 2015.8.0
'''
# Required params for 'download' template
download_template_deps = ('dist', 'release', 'arch')
cmd = 'lxc-create -n {0}'.format(name)
profile = get_container_profile(copy.deepcopy(profile))
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, None)
profile_match = profile.pop(key, default)
# Return the profile match if the the kwarg match was None, as the
# lxc.present state will pass these kwargs set to None by default.
if kw_overrides_match is None:
return profile_match
return kw_overrides_match
path = select('path')
if exists(name, path=path):
raise CommandExecutionError(
'Container \'{0}\' already exists'.format(name)
)
tvg = select('vgname')
vgname = tvg if tvg else __salt__['config.get']('lxc.vgname')
# The 'template' and 'image' params conflict
template = select('template')
image = select('image')
if template and image:
raise SaltInvocationError(
'Only one of \'template\' and \'image\' is permitted'
)
elif not any((template, image, profile)):
raise SaltInvocationError(
'At least one of \'template\', \'image\', and \'profile\' is '
'required'
)
options = select('options') or {}
backing = select('backing')
if vgname and not backing:
backing = 'lvm'
lvname = select('lvname')
thinpool = select('thinpool')
fstype = select('fstype')
size = select('size', '1G')
zfsroot = select('zfsroot')
if backing in ('dir', 'overlayfs', 'btrfs', 'zfs'):
fstype = None
size = None
# some backends won't support some parameters
if backing in ('aufs', 'dir', 'overlayfs', 'btrfs'):
lvname = vgname = thinpool = None
if image:
img_tar = __salt__['cp.cache_file'](image)
template = os.path.join(
os.path.dirname(salt.__file__),
'templates',
'lxc',
'salt_tarball')
options['imgtar'] = img_tar
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
if not os.path.exists(path):
os.makedirs(path)
if config:
cmd += ' -f {0}'.format(config)
if template:
cmd += ' -t {0}'.format(template)
if backing:
backing = backing.lower()
cmd += ' -B {0}'.format(backing)
if backing in ('zfs',):
if zfsroot:
cmd += ' --zfsroot {0}'.format(zfsroot)
if backing in ('lvm',):
if lvname:
cmd += ' --lvname {0}'.format(lvname)
if vgname:
cmd += ' --vgname {0}'.format(vgname)
if thinpool:
cmd += ' --thinpool {0}'.format(thinpool)
if backing not in ('dir', 'overlayfs'):
if fstype:
cmd += ' --fstype {0}'.format(fstype)
if size:
cmd += ' --fssize {0}'.format(size)
if options:
if template == 'download':
missing_deps = [x for x in download_template_deps
if x not in options]
if missing_deps:
raise SaltInvocationError(
'Missing params in \'options\' dict: {0}'
.format(', '.join(missing_deps))
)
cmd += ' --'
for key, val in six.iteritems(options):
cmd += ' --{0} {1}'.format(key, val)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
# please do not merge extra conflicting stuff
# inside those two line (ret =, return)
return _after_ignition_network_profile(cmd,
ret,
name,
network_profile,
path,
nic_opts)
def clone(name,
orig,
profile=None,
network_profile=None,
nic_opts=None,
**kwargs):
'''
Create a new container as a clone of another container
name
Name of the container
orig
Name of the original container to be cloned
profile
Profile to use in container cloning (see
:mod:`lxc.get_container_profile
<salt.modules.lxc.get_container_profile>`). Values in a profile will be
overridden by the **Container Cloning Arguments** listed below.
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
**Container Cloning Arguments**
snapshot
Use Copy On Write snapshots (LVM)
size : 1G
Size of the volume to create. Only applicable if ``backing=lvm``.
backing
The type of storage to use. Set to ``lvm`` to use an LVM group.
Defaults to filesystem within /var/lib/lxc.
network_profile
Network profile to use for container
.. versionadded:: 2015.8.0
nic_opts
give extra opts overriding network profile values
.. versionadded:: 2015.8.0
CLI Examples:
.. code-block:: bash
salt '*' lxc.clone myclone orig=orig_container
salt '*' lxc.clone myclone orig=orig_container snapshot=True
'''
profile = get_container_profile(copy.deepcopy(profile))
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, None)
profile_match = profile.pop(key, default)
# let kwarg overrides be the preferred choice
if kw_overrides_match is None:
return profile_match
return kw_overrides_match
path = select('path')
if exists(name, path=path):
raise CommandExecutionError(
'Container \'{0}\' already exists'.format(name)
)
_ensure_exists(orig, path=path)
if state(orig, path=path) != 'stopped':
raise CommandExecutionError(
'Container \'{0}\' must be stopped to be cloned'.format(orig)
)
backing = select('backing')
snapshot = select('snapshot')
if backing in ('dir',):
snapshot = False
if not snapshot:
snapshot = ''
else:
snapshot = '-s'
size = select('size', '1G')
if backing in ('dir', 'overlayfs', 'btrfs'):
size = None
# LXC commands and options changed in 2.0 - CF issue #34086 for details
if _LooseVersion(version()) >= _LooseVersion('2.0'):
# https://linuxcontainers.org/lxc/manpages//man1/lxc-copy.1.html
cmd = 'lxc-copy'
cmd += ' {0} -n {1} -N {2}'.format(snapshot, orig, name)
else:
# https://linuxcontainers.org/lxc/manpages//man1/lxc-clone.1.html
cmd = 'lxc-clone'
cmd += ' {0} -o {1} -n {2}'.format(snapshot, orig, name)
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
if not os.path.exists(path):
os.makedirs(path)
if backing:
backing = backing.lower()
cmd += ' -B {0}'.format(backing)
if backing not in ('dir', 'overlayfs'):
if size:
cmd += ' -L {0}'.format(size)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
# please do not merge extra conflicting stuff
# inside those two line (ret =, return)
return _after_ignition_network_profile(cmd,
ret,
name,
network_profile,
path,
nic_opts)
def ls_(active=None, cache=True, path=None):
'''
Return a list of the containers available on the minion
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
active
If ``True``, return only active (i.e. running) containers
.. versionadded:: 2015.5.0
CLI Example:
.. code-block:: bash
salt '*' lxc.ls
salt '*' lxc.ls active=True
'''
contextvar = 'lxc.ls{0}'.format(path)
if active:
contextvar += '.active'
if cache and (contextvar in __context__):
return __context__[contextvar]
else:
ret = []
cmd = 'lxc-ls'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
if active:
cmd += ' --active'
output = __salt__['cmd.run_stdout'](cmd, python_shell=False)
for line in output.splitlines():
ret.extend(line.split())
__context__[contextvar] = ret
return ret
def list_(extra=False, limit=None, path=None):
'''
List containers classified by state
extra
Also get per-container specific info. This will change the return data.
Instead of returning a list of containers, a dictionary of containers
and each container's output from :mod:`lxc.info
<salt.modules.lxc.info>`.
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
limit
Return output matching a specific state (**frozen**, **running**, or
**stopped**).
.. versionadded:: 2015.5.0
CLI Examples:
.. code-block:: bash
salt '*' lxc.list
salt '*' lxc.list extra=True
salt '*' lxc.list limit=running
'''
ctnrs = ls_(path=path)
if extra:
stopped = {}
frozen = {}
running = {}
else:
stopped = []
frozen = []
running = []
ret = {'running': running,
'stopped': stopped,
'frozen': frozen}
for container in ctnrs:
cmd = 'lxc-info'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0}'.format(container)
c_info = __salt__['cmd.run'](
cmd,
python_shell=False,
output_loglevel='debug'
)
c_state = None
for line in c_info.splitlines():
stat = line.split(':')
if stat[0] in ('State', 'state'):
c_state = stat[1].strip()
break
if not c_state or (limit is not None and c_state.lower() != limit):
continue
if extra:
infos = info(container, path=path)
method = 'update'
value = {container: infos}
else:
method = 'append'
value = container
if c_state == 'STOPPED':
getattr(stopped, method)(value)
continue
if c_state == 'FROZEN':
getattr(frozen, method)(value)
continue
if c_state == 'RUNNING':
getattr(running, method)(value)
continue
if limit is not None:
return ret.get(limit, {} if extra else [])
return ret
def _change_state(cmd,
name,
expected,
stdin=_marker,
stdout=_marker,
stderr=_marker,
with_communicate=_marker,
use_vt=_marker,
path=None):
pre = state(name, path=path)
if pre == expected:
return {'result': True,
'state': {'old': expected, 'new': expected},
'comment': 'Container \'{0}\' already {1}'
.format(name, expected)}
if cmd == 'lxc-destroy':
# Kill the container first
scmd = 'lxc-stop'
if path:
scmd += ' -P {0}'.format(pipes.quote(path))
scmd += ' -k -n {0}'.format(name)
__salt__['cmd.run'](scmd,
python_shell=False)
if path and ' -P ' not in cmd:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0}'.format(name)
# certain lxc commands need to be taken with care (lxc-start)
# as te command itself mess with double forks; we must not
# communicate with it, but just wait for the exit status
pkwargs = {'python_shell': False,
'redirect_stderr': True,
'with_communicate': with_communicate,
'use_vt': use_vt,
'stdin': stdin,
'stdout': stdout}
for i in [a for a in pkwargs]:
val = pkwargs[i]
if val is _marker:
pkwargs.pop(i, None)
_cmdout = __salt__['cmd.run_all'](cmd, **pkwargs)
if _cmdout['retcode'] != 0:
raise CommandExecutionError(
'Error changing state for container \'{0}\' using command '
'\'{1}\': {2}'.format(name, cmd, _cmdout['stdout'])
)
if expected is not None:
# some commands do not wait, so we will
rcmd = 'lxc-wait'
if path:
rcmd += ' -P {0}'.format(pipes.quote(path))
rcmd += ' -n {0} -s {1}'.format(name, expected.upper())
__salt__['cmd.run'](rcmd, python_shell=False, timeout=30)
_clear_context()
post = state(name, path=path)
ret = {'result': post == expected,
'state': {'old': pre, 'new': post}}
return ret
def _ensure_exists(name, path=None):
'''
Raise an exception if the container does not exist
'''
if not exists(name, path=path):
raise CommandExecutionError(
'Container \'{0}\' does not exist'.format(name)
)
def _ensure_running(name, no_start=False, path=None):
'''
If the container is not currently running, start it. This function returns
the state that the container was in before changing
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
'''
_ensure_exists(name, path=path)
pre = state(name, path=path)
if pre == 'running':
# This will be a no-op but running the function will give us a pretty
# return dict.
return start(name, path=path)
elif pre == 'stopped':
if no_start:
raise CommandExecutionError(
'Container \'{0}\' is not running'.format(name)
)
return start(name, path=path)
elif pre == 'frozen':
if no_start:
raise CommandExecutionError(
'Container \'{0}\' is not running'.format(name)
)
return unfreeze(name, path=path)
def restart(name, path=None, lxc_config=None, force=False):
'''
.. versionadded:: 2015.5.0
Restart the named container. If the container was not running, the
container will merely be started.
name
The name of the container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
lxc_config
path to a lxc config file
config file will be guessed from container name otherwise
.. versionadded:: 2015.8.0
force : False
If ``True``, the container will be force-stopped instead of gracefully
shut down
CLI Example:
.. code-block:: bash
salt myminion lxc.restart name
'''
_ensure_exists(name, path=path)
orig_state = state(name, path=path)
if orig_state != 'stopped':
stop(name, kill=force, path=path)
ret = start(name, path=path, lxc_config=lxc_config)
ret['state']['old'] = orig_state
if orig_state != 'stopped':
ret['restarted'] = True
return ret
def start(name, **kwargs):
'''
Start the named container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
lxc_config
path to a lxc config file
config file will be guessed from container name otherwise
.. versionadded:: 2015.8.0
use_vt
run the command through VT
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.start name
'''
path = kwargs.get('path', None)
cpath = get_root_path(path)
lxc_config = kwargs.get('lxc_config', None)
cmd = 'lxc-start'
if not lxc_config:
lxc_config = os.path.join(cpath, name, 'config')
# we try to start, even without config, if global opts are there
if os.path.exists(lxc_config):
cmd += ' -f {0}'.format(pipes.quote(lxc_config))
cmd += ' -d'
_ensure_exists(name, path=path)
if state(name, path=path) == 'frozen':
raise CommandExecutionError(
'Container \'{0}\' is frozen, use lxc.unfreeze'.format(name)
)
# lxc-start daemonize itself violently, we must not communicate with it
use_vt = kwargs.get('use_vt', None)
with_communicate = kwargs.get('with_communicate', False)
return _change_state(cmd, name, 'running',
stdout=None,
stderr=None,
stdin=None,
with_communicate=with_communicate,
path=path,
use_vt=use_vt)
def stop(name, kill=False, path=None, use_vt=None):
'''
Stop the named container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
kill: False
Do not wait for the container to stop, kill all tasks in the container.
Older LXC versions will stop containers like this irrespective of this
argument.
.. versionchanged:: 2015.5.0
Default value changed to ``False``
use_vt
run the command through VT
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.stop name
'''
_ensure_exists(name, path=path)
orig_state = state(name, path=path)
if orig_state == 'frozen' and not kill:
# Gracefully stopping a frozen container is slower than unfreezing and
# then stopping it (at least in my testing), so if we're not
# force-stopping the container, unfreeze it first.
unfreeze(name, path=path)
cmd = 'lxc-stop'
if kill:
cmd += ' -k'
ret = _change_state(cmd, name, 'stopped', use_vt=use_vt, path=path)
ret['state']['old'] = orig_state
return ret
def freeze(name, **kwargs):
'''
Freeze the named container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
start : False
If ``True`` and the container is stopped, the container will be started
before attempting to freeze.
.. versionadded:: 2015.5.0
use_vt
run the command through VT
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.freeze name
'''
use_vt = kwargs.get('use_vt', None)
path = kwargs.get('path', None)
_ensure_exists(name, path=path)
orig_state = state(name, path=path)
start_ = kwargs.get('start', False)
if orig_state == 'stopped':
if not start_:
raise CommandExecutionError(
'Container \'{0}\' is stopped'.format(name)
)
start(name, path=path)
cmd = 'lxc-freeze'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
ret = _change_state(cmd, name, 'frozen', use_vt=use_vt, path=path)
if orig_state == 'stopped' and start_:
ret['state']['old'] = orig_state
ret['started'] = True
ret['state']['new'] = state(name, path=path)
return ret
def unfreeze(name, path=None, use_vt=None):
'''
Unfreeze the named container.
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
use_vt
run the command through VT
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.unfreeze name
'''
_ensure_exists(name, path=path)
if state(name, path=path) == 'stopped':
raise CommandExecutionError(
'Container \'{0}\' is stopped'.format(name)
)
cmd = 'lxc-unfreeze'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
return _change_state(cmd, name, 'running', path=path, use_vt=use_vt)
def destroy(name, stop=False, path=None):
'''
Destroy the named container.
.. warning::
Destroys all data associated with the container.
path
path to the container parent directory (default: /var/lib/lxc)
.. versionadded:: 2015.8.0
stop : False
If ``True``, the container will be destroyed even if it is
running/frozen.
.. versionchanged:: 2015.5.0
Default value changed to ``False``. This more closely matches the
behavior of ``lxc-destroy(1)``, and also makes it less likely that
an accidental command will destroy a running container that was
being used for important things.
CLI Examples:
.. code-block:: bash
salt '*' lxc.destroy foo
salt '*' lxc.destroy foo stop=True
'''
_ensure_exists(name, path=path)
if not stop and state(name, path=path) != 'stopped':
raise CommandExecutionError(
'Container \'{0}\' is not stopped'.format(name)
)
return _change_state('lxc-destroy', name, None, path=path)
# Compatibility between LXC and nspawn
remove = salt.utils.functools.alias_function(destroy, 'remove')
def exists(name, path=None):
'''
Returns whether the named container exists.
path
path to the container parent directory (default: /var/lib/lxc)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.exists name
'''
_exists = name in ls_(path=path)
# container may be just created but we did cached earlier the
# lxc-ls results
if not _exists:
_exists = name in ls_(cache=False, path=path)
return _exists
def state(name, path=None):
'''
Returns the state of a container.
path
path to the container parent directory (default: /var/lib/lxc)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.state name
'''
# Don't use _ensure_exists() here, it will mess with _change_state()
cachekey = 'lxc.state.{0}{1}'.format(name, path)
try:
return __context__[cachekey]
except KeyError:
if not exists(name, path=path):
__context__[cachekey] = None
else:
cmd = 'lxc-info'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0}'.format(name)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
if ret['retcode'] != 0:
_clear_context()
raise CommandExecutionError(
'Unable to get state of container \'{0}\''.format(name)
)
c_infos = ret['stdout'].splitlines()
c_state = None
for c_info in c_infos:
stat = c_info.split(':')
if stat[0].lower() == 'state':
c_state = stat[1].strip().lower()
break
__context__[cachekey] = c_state
return __context__[cachekey]
def get_parameter(name, parameter, path=None):
'''
Returns the value of a cgroup parameter for a container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.get_parameter container_name memory.limit_in_bytes
'''
_ensure_exists(name, path=path)
cmd = 'lxc-cgroup'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0} {1}'.format(name, parameter)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
if ret['retcode'] != 0:
raise CommandExecutionError(
'Unable to retrieve value for \'{0}\''.format(parameter)
)
return ret['stdout'].strip()
def set_parameter(name, parameter, value, path=None):
'''
Set the value of a cgroup parameter for a container.
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.set_parameter name parameter value
'''
if not exists(name, path=path):
return None
cmd = 'lxc-cgroup'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0} {1} {2}'.format(name, parameter, value)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
if ret['retcode'] != 0:
return False
else:
return True
def info(name, path=None):
'''
Returns information about a container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.info name
'''
cachekey = 'lxc.info.{0}{1}'.format(name, path)
try:
return __context__[cachekey]
except KeyError:
_ensure_exists(name, path=path)
cpath = get_root_path(path)
try:
conf_file = os.path.join(cpath, name, 'config')
except AttributeError:
conf_file = os.path.join(cpath, six.text_type(name), 'config')
if not os.path.isfile(conf_file):
raise CommandExecutionError(
'LXC config file {0} does not exist'.format(conf_file)
)
ret = {}
config = []
with salt.utils.files.fopen(conf_file) as fp_:
for line in fp_:
line = salt.utils.stringutils.to_unicode(line)
comps = [x.strip() for x in
line.split('#', 1)[0].strip().split('=', 1)]
if len(comps) == 2:
config.append(tuple(comps))
ifaces = []
current = None
for key, val in config:
if key == 'lxc.network.type':
current = {'type': val}
ifaces.append(current)
elif not current:
continue
elif key.startswith('lxc.network.'):
current[key.replace('lxc.network.', '', 1)] = val
if ifaces:
ret['nics'] = ifaces
ret['rootfs'] = next(
(x[1] for x in config if x[0] == 'lxc.rootfs'),
None
)
ret['state'] = state(name, path=path)
ret['ips'] = []
ret['public_ips'] = []
ret['private_ips'] = []
ret['public_ipv4_ips'] = []
ret['public_ipv6_ips'] = []
ret['private_ipv4_ips'] = []
ret['private_ipv6_ips'] = []
ret['ipv4_ips'] = []
ret['ipv6_ips'] = []
ret['size'] = None
ret['config'] = conf_file
if ret['state'] == 'running':
try:
limit = int(get_parameter(name, 'memory.limit_in_bytes'))
except (CommandExecutionError, TypeError, ValueError):
limit = 0
try:
usage = int(get_parameter(name, 'memory.usage_in_bytes'))
except (CommandExecutionError, TypeError, ValueError):
usage = 0
free = limit - usage
ret['memory_limit'] = limit
ret['memory_free'] = free
size = run_stdout(name, 'df /', path=path, python_shell=False)
# The size is the 2nd column of the last line
ret['size'] = size.splitlines()[-1].split()[1]
# First try iproute2
ip_cmd = run_all(
name, 'ip link show', path=path, python_shell=False)
if ip_cmd['retcode'] == 0:
ip_data = ip_cmd['stdout']
ip_cmd = run_all(
name, 'ip addr show', path=path, python_shell=False)
ip_data += '\n' + ip_cmd['stdout']
ip_data = salt.utils.network._interfaces_ip(ip_data)
else:
# That didn't work, try ifconfig
ip_cmd = run_all(
name, 'ifconfig', path=path, python_shell=False)
if ip_cmd['retcode'] == 0:
ip_data = \
salt.utils.network._interfaces_ifconfig(
ip_cmd['stdout'])
else:
# Neither was successful, give up
log.warning(
'Unable to run ip or ifconfig in container \'%s\'', name
)
ip_data = {}
ret['ipv4_ips'] = salt.utils.network.ip_addrs(
include_loopback=True,
interface_data=ip_data
)
ret['ipv6_ips'] = salt.utils.network.ip_addrs6(
include_loopback=True,
interface_data=ip_data
)
ret['ips'] = ret['ipv4_ips'] + ret['ipv6_ips']
for address in ret['ipv4_ips']:
if address == '127.0.0.1':
ret['private_ips'].append(address)
ret['private_ipv4_ips'].append(address)
elif salt.utils.cloud.is_public_ip(address):
ret['public_ips'].append(address)
ret['public_ipv4_ips'].append(address)
else:
ret['private_ips'].append(address)
ret['private_ipv4_ips'].append(address)
for address in ret['ipv6_ips']:
if address == '::1' or address.startswith('fe80'):
ret['private_ips'].append(address)
ret['private_ipv6_ips'].append(address)
else:
ret['public_ips'].append(address)
ret['public_ipv6_ips'].append(address)
for key in [x for x in ret if x == 'ips' or x.endswith('ips')]:
ret[key].sort(key=_ip_sort)
__context__[cachekey] = ret
return __context__[cachekey]
def set_password(name, users, password, encrypted=True, path=None):
'''
.. versionchanged:: 2015.5.0
Function renamed from ``set_pass`` to ``set_password``. Additionally,
this function now supports (and defaults to using) a password hash
instead of a plaintext password.
Set the password of one or more system users inside containers
users
Comma-separated list (or python list) of users to change password
password
Password to set for the specified user(s)
encrypted : True
If true, ``password`` must be a password hash. Set to ``False`` to set
a plaintext password (not recommended).
.. versionadded:: 2015.5.0
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.set_pass container-name root '$6$uJ2uAyLU$KoI67t8As/0fXtJOPcHKGXmUpcoYUcVR2K6x93walnShTCQvjRwq25yIkiCBOqgbfdKQSFnAo28/ek6716vEV1'
salt '*' lxc.set_pass container-name root foo encrypted=False
'''
def _bad_user_input():
raise SaltInvocationError('Invalid input for \'users\' parameter')
if not isinstance(users, list):
try:
users = users.split(',')
except AttributeError:
_bad_user_input()
if not users:
_bad_user_input()
failed_users = []
for user in users:
result = retcode(name,
'chpasswd{0}'.format(' -e' if encrypted else ''),
stdin=':'.join((user, password)),
python_shell=False,
path=path,
chroot_fallback=True,
output_loglevel='quiet')
if result != 0:
failed_users.append(user)
if failed_users:
raise CommandExecutionError(
'Password change failed for the following user(s): {0}'
.format(', '.join(failed_users))
)
return True
set_pass = salt.utils.functools.alias_function(set_password, 'set_pass')
def update_lxc_conf(name, lxc_conf, lxc_conf_unset, path=None):
'''
Edit LXC configuration options
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.update_lxc_conf ubuntu \\
lxc_conf="[{'network.ipv4.ip':'10.0.3.5'}]" \\
lxc_conf_unset="['lxc.utsname']"
'''
_ensure_exists(name, path=path)
cpath = get_root_path(path)
lxc_conf_p = os.path.join(cpath, name, 'config')
if not os.path.exists(lxc_conf_p):
raise SaltInvocationError(
'Configuration file {0} does not exist'.format(lxc_conf_p)
)
changes = {'edited': [], 'added': [], 'removed': []}
ret = {'changes': changes, 'result': True, 'comment': ''}
# do not use salt.utils.files.fopen !
with salt.utils.files.fopen(lxc_conf_p, 'r') as fic:
filtered_lxc_conf = []
for row in lxc_conf:
if not row:
continue
for conf in row:
filtered_lxc_conf.append((conf.strip(),
row[conf].strip()))
ret['comment'] = 'lxc.conf is up to date'
lines = []
orig_config = salt.utils.stringutils.to_unicode(fic.read())
for line in orig_config.splitlines():
if line.startswith('#') or not line.strip():
lines.append([line, ''])
else:
line = line.split('=')
index = line.pop(0)
val = (index.strip(), '='.join(line).strip())
if val not in lines:
lines.append(val)
for key, item in filtered_lxc_conf:
matched = False
for idx, line in enumerate(lines[:]):
if line[0] == key:
matched = True
lines[idx] = (key, item)
if '='.join(line[1:]).strip() != item.strip():
changes['edited'].append(
({line[0]: line[1:]}, {key: item}))
break
if not matched:
if (key, item) not in lines:
lines.append((key, item))
changes['added'].append({key: item})
dest_lxc_conf = []
# filter unset
if lxc_conf_unset:
for line in lines:
for opt in lxc_conf_unset:
if (
not line[0].startswith(opt) and
line not in dest_lxc_conf
):
dest_lxc_conf.append(line)
else:
changes['removed'].append(opt)
else:
dest_lxc_conf = lines
conf = ''
for key, val in dest_lxc_conf:
if not val:
conf += '{0}\n'.format(key)
else:
conf += '{0} = {1}\n'.format(key.strip(), val.strip())
conf_changed = conf != orig_config
chrono = datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S')
if conf_changed:
# DO NOT USE salt.utils.files.fopen here, i got (kiorky)
# problems with lxc configs which were wiped !
with salt.utils.files.fopen('{0}.{1}'.format(lxc_conf_p, chrono), 'w') as wfic:
wfic.write(salt.utils.stringutils.to_str(conf))
with salt.utils.files.fopen(lxc_conf_p, 'w') as wfic:
wfic.write(salt.utils.stringutils.to_str(conf))
ret['comment'] = 'Updated'
ret['result'] = True
if not any(changes[x] for x in changes):
# Ensure an empty changes dict if nothing was modified
ret['changes'] = {}
return ret
def set_dns(name, dnsservers=None, searchdomains=None, path=None):
'''
.. versionchanged:: 2015.5.0
The ``dnsservers`` and ``searchdomains`` parameters can now be passed
as a comma-separated list.
Update /etc/resolv.confo
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.set_dns ubuntu "['8.8.8.8', '4.4.4.4']"
'''
if dnsservers is None:
dnsservers = ['8.8.8.8', '4.4.4.4']
elif not isinstance(dnsservers, list):
try:
dnsservers = dnsservers.split(',')
except AttributeError:
raise SaltInvocationError(
'Invalid input for \'dnsservers\' parameter'
)
if searchdomains is None:
searchdomains = []
elif not isinstance(searchdomains, list):
try:
searchdomains = searchdomains.split(',')
except AttributeError:
raise SaltInvocationError(
'Invalid input for \'searchdomains\' parameter'
)
dns = ['nameserver {0}'.format(x) for x in dnsservers]
dns.extend(['search {0}'.format(x) for x in searchdomains])
dns = '\n'.join(dns) + '\n'
# we may be using resolvconf in the container
# We need to handle that case with care:
# - we create the resolv.conf runtime directory (the
# linked directory) as anyway it will be shadowed when the real
# runned tmpfs mountpoint will be mounted.
# ( /etc/resolv.conf -> ../run/resolvconf/resolv.conf)
# Indeed, it can save us in any other case (running, eg, in a
# bare chroot when repairing or preparing the container for
# operation.
# - We also teach resolvconf to use the aforementioned dns.
# - We finally also set /etc/resolv.conf in all cases
rstr = __salt__['test.random_hash']()
# no tmp here, apparmor won't let us execute !
script = '/sbin/{0}_dns.sh'.format(rstr)
DNS_SCRIPT = "\n".join([
# 'set -x',
'#!/usr/bin/env bash',
'if [ -h /etc/resolv.conf ];then',
' if [ "x$(readlink /etc/resolv.conf)"'
' = "x../run/resolvconf/resolv.conf" ];then',
' if [ ! -d /run/resolvconf/ ];then',
' mkdir -p /run/resolvconf',
' fi',
' cat > /etc/resolvconf/resolv.conf.d/head <<EOF',
dns,
'EOF',
'',
' fi',
'fi',
'cat > /etc/resolv.conf <<EOF',
dns,
'EOF',
''])
result = run_all(
name, 'tee {0}'.format(script), path=path,
stdin=DNS_SCRIPT, python_shell=True)
if result['retcode'] == 0:
result = run_all(
name, 'sh -c "chmod +x {0};{0}"'.format(script),
path=path, python_shell=True)
# blindly delete the setter file
run_all(name,
'sh -c \'if [ -f "{0}" ];then rm -f "{0}";fi\''.format(script),
path=path, python_shell=True)
if result['retcode'] != 0:
error = ('Unable to write to /etc/resolv.conf in container \'{0}\''
.format(name))
if result['stderr']:
error += ': {0}'.format(result['stderr'])
raise CommandExecutionError(error)
return True
def running_systemd(name, cache=True, path=None):
'''
Determine if systemD is running
path
path to the container parent
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.running_systemd ubuntu
'''
k = 'lxc.systemd.test.{0}{1}'.format(name, path)
ret = __context__.get(k, None)
if ret is None or not cache:
rstr = __salt__['test.random_hash']()
# no tmp here, apparmor won't let us execute !
script = '/sbin/{0}_testsystemd.sh'.format(rstr)
# ubuntu already had since trusty some bits of systemd but was
# still using upstart ...
# we need to be a bit more careful that just testing that systemd
# is present
_script = textwrap.dedent(
'''\
#!/usr/bin/env bash
set -x
if ! command -v systemctl 1>/dev/null 2>/dev/null;then exit 2;fi
for i in \\
/run/systemd/journal/dev-log\\
/run/systemd/journal/flushed\\
/run/systemd/journal/kernel-seqnum\\
/run/systemd/journal/socket\\
/run/systemd/journal/stdout\\
/var/run/systemd/journal/dev-log\\
/var/run/systemd/journal/flushed\\
/var/run/systemd/journal/kernel-seqnum\\
/var/run/systemd/journal/socket\\
/var/run/systemd/journal/stdout\\
;do\\
if test -e ${i};then exit 0;fi
done
if test -d /var/systemd/system;then exit 0;fi
exit 2
''')
result = run_all(
name, 'tee {0}'.format(script), path=path,
stdin=_script, python_shell=True)
if result['retcode'] == 0:
result = run_all(name,
'sh -c "chmod +x {0};{0}"'''.format(script),
path=path,
python_shell=True)
else:
raise CommandExecutionError(
'lxc {0} failed to copy initd tester'.format(name))
run_all(name,
'sh -c \'if [ -f "{0}" ];then rm -f "{0}";fi\''
''.format(script),
path=path,
ignore_retcode=True,
python_shell=True)
if result['retcode'] != 0:
error = ('Unable to determine if the container \'{0}\''
' was running systemd, assmuming it is not.'
''.format(name))
if result['stderr']:
error += ': {0}'.format(result['stderr'])
# only cache result if we got a known exit code
if result['retcode'] in (0, 2):
__context__[k] = ret = not result['retcode']
return ret
def systemd_running_state(name, path=None):
'''
Get the operational state of a systemd based container
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.systemd_running_state ubuntu
'''
try:
ret = run_all(name,
'systemctl is-system-running',
path=path,
ignore_retcode=True)['stdout']
except CommandExecutionError:
ret = ''
return ret
def test_sd_started_state(name, path=None):
'''
Test if a systemd container is fully started
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.test_sd_started_state ubuntu
'''
qstate = systemd_running_state(name, path=path)
if qstate in ('initializing', 'starting'):
return False
elif qstate == '':
return None
else:
return True
def test_bare_started_state(name, path=None):
'''
Test if a non systemd container is fully started
For now, it consists only to test if the container is attachable
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.test_bare_started_state ubuntu
'''
try:
ret = run_all(
name, 'ls', path=path, ignore_retcode=True
)['retcode'] == 0
except (CommandExecutionError,):
ret = None
return ret
def wait_started(name, path=None, timeout=300):
'''
Check that the system has fully inited
This is actually very important for systemD based containers
see https://github.com/saltstack/salt/issues/23847
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.wait_started ubuntu
'''
if not exists(name, path=path):
raise CommandExecutionError(
'Container {0} does does exists'.format(name))
if not state(name, path=path) == 'running':
raise CommandExecutionError(
'Container {0} is not running'.format(name))
ret = False
if running_systemd(name, path=path):
test_started = test_sd_started_state
logger = log.error
else:
test_started = test_bare_started_state
logger = log.debug
now = time.time()
expire = now + timeout
now = time.time()
started = test_started(name, path=path)
while time.time() < expire and not started:
time.sleep(0.3)
started = test_started(name, path=path)
if started is None:
logger(
'Assuming %s is started, although we failed to detect that'
' is fully started correctly', name)
ret = True
else:
ret = started
return ret
def _needs_install(name, path=None):
ret = 0
has_minion = retcode(name,
'which salt-minion',
path=path,
ignore_retcode=True)
# we assume that installing is when no minion is running
# but testing the executable presence is not enougth for custom
# installs where the bootstrap can do much more than installing
# the bare salt binaries.
if has_minion:
processes = run_stdout(name, "ps aux", path=path)
if 'salt-minion' not in processes:
ret = 1
else:
retcode(name, 'salt-call --local service.stop salt-minion')
else:
ret = 1
return ret
def bootstrap(name,
config=None,
approve_key=True,
install=True,
pub_key=None,
priv_key=None,
bootstrap_url=None,
force_install=False,
unconditional_install=False,
path=None,
bootstrap_delay=None,
bootstrap_args=None,
bootstrap_shell=None):
'''
Install and configure salt in a container.
config
Minion configuration options. By default, the ``master`` option is set
to the target host's master.
approve_key
Request a pre-approval of the generated minion key. Requires
that the salt-master be configured to either auto-accept all keys or
expect a signing request from the target host. Default: ``True``
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
pub_key
Explicit public key to pressed the minion with (optional).
This can be either a filepath or a string representing the key
priv_key
Explicit private key to pressed the minion with (optional).
This can be either a filepath or a string representing the key
bootstrap_delay
Delay in seconds between end of container creation and bootstrapping.
Useful when waiting for container to obtain a DHCP lease.
.. versionadded:: 2015.5.0
bootstrap_url
url, content or filepath to the salt bootstrap script
bootstrap_args
salt bootstrap script arguments
bootstrap_shell
shell to execute the script into
install
Whether to attempt a full installation of salt-minion if needed.
force_install
Force installation even if salt-minion is detected,
this is the way to run vendor bootstrap scripts even
if a salt minion is already present in the container
unconditional_install
Run the script even if the container seems seeded
CLI Examples:
.. code-block:: bash
salt 'minion' lxc.bootstrap container_name [config=config_data] \\
[approve_key=(True|False)] [install=(True|False)]
'''
wait_started(name, path=path)
if bootstrap_delay is not None:
try:
log.info('LXC %s: bootstrap_delay: %s', name, bootstrap_delay)
time.sleep(bootstrap_delay)
except TypeError:
# Bad input, but assume since a value was passed that
# a delay was desired, and sleep for 5 seconds
time.sleep(5)
c_info = info(name, path=path)
if not c_info:
return None
# default set here as we cannot set them
# in def as it can come from a chain of procedures.
if bootstrap_args:
# custom bootstrap args can be totally customized, and user could
# have inserted the placeholder for the config directory.
# For example, some salt bootstrap script do not use at all -c
if '{0}' not in bootstrap_args:
bootstrap_args += ' -c {0}'
else:
bootstrap_args = '-c {0}'
if not bootstrap_shell:
bootstrap_shell = 'sh'
orig_state = _ensure_running(name, path=path)
if not orig_state:
return orig_state
if not force_install:
needs_install = _needs_install(name, path=path)
else:
needs_install = True
seeded = retcode(name,
'test -e \'{0}\''.format(SEED_MARKER),
path=path,
chroot_fallback=True,
ignore_retcode=True) == 0
tmp = tempfile.mkdtemp()
if seeded and not unconditional_install:
ret = True
else:
ret = False
cfg_files = __salt__['seed.mkconfig'](
config, tmp=tmp, id_=name, approve_key=approve_key,
pub_key=pub_key, priv_key=priv_key)
if needs_install or force_install or unconditional_install:
if install:
rstr = __salt__['test.random_hash']()
configdir = '/var/tmp/.c_{0}'.format(rstr)
cmd = 'install -m 0700 -d {0}'.format(configdir)
if run_all(
name, cmd, path=path, python_shell=False
)['retcode'] != 0:
log.error('tmpdir %s creation failed %s', configdir, cmd)
return False
bs_ = __salt__['config.gather_bootstrap_script'](
bootstrap=bootstrap_url)
script = '/sbin/{0}_bootstrap.sh'.format(rstr)
copy_to(name, bs_, script, path=path)
result = run_all(name,
'sh -c "chmod +x {0}"'.format(script),
path=path,
python_shell=True)
copy_to(name, cfg_files['config'],
os.path.join(configdir, 'minion'),
path=path)
copy_to(name, cfg_files['privkey'],
os.path.join(configdir, 'minion.pem'),
path=path)
copy_to(name, cfg_files['pubkey'],
os.path.join(configdir, 'minion.pub'),
path=path)
bootstrap_args = bootstrap_args.format(configdir)
cmd = ('{0} {2} {1}'
.format(bootstrap_shell,
bootstrap_args.replace("'", "''"),
script))
# log ASAP the forged bootstrap command which can be wrapped
# out of the output in case of unexpected problem
log.info('Running %s in LXC container \'%s\'', cmd, name)
ret = retcode(name, cmd, output_loglevel='info',
path=path, use_vt=True) == 0
run_all(name,
'sh -c \'if [ -f "{0}" ];then rm -f "{0}";fi\''
''.format(script),
path=path,
ignore_retcode=True,
python_shell=True)
else:
ret = False
else:
minion_config = salt.config.minion_config(cfg_files['config'])
pki_dir = minion_config['pki_dir']
copy_to(name,
cfg_files['config'],
'/etc/salt/minion',
path=path)
copy_to(name,
cfg_files['privkey'],
os.path.join(pki_dir, 'minion.pem'),
path=path)
copy_to(name,
cfg_files['pubkey'],
os.path.join(pki_dir, 'minion.pub'),
path=path)
run(name,
'salt-call --local service.enable salt-minion',
path=path,
python_shell=False)
ret = True
shutil.rmtree(tmp)
if orig_state == 'stopped':
stop(name, path=path)
elif orig_state == 'frozen':
freeze(name, path=path)
# mark seeded upon successful install
if ret:
run(name,
'touch \'{0}\''.format(SEED_MARKER),
path=path,
python_shell=False)
return ret
def attachable(name, path=None):
'''
Return True if the named container can be attached to via the lxc-attach
command
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt 'minion' lxc.attachable ubuntu
'''
cachekey = 'lxc.attachable{0}{1}'.format(name, path)
try:
return __context__[cachekey]
except KeyError:
_ensure_exists(name, path=path)
# Can't use run() here because it uses attachable() and would
# endlessly recurse, resulting in a traceback
log.debug('Checking if LXC container %s is attachable', name)
cmd = 'lxc-attach'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' --clear-env -n {0} -- /usr/bin/env'.format(name)
result = __salt__['cmd.retcode'](cmd,
python_shell=False,
output_loglevel='quiet',
ignore_retcode=True) == 0
__context__[cachekey] = result
return __context__[cachekey]
def _run(name,
cmd,
output=None,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=None,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
Common logic for lxc.run functions
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
'''
orig_state = state(name, path=path)
try:
if attachable(name, path=path):
ret = __salt__['container_resource.run'](
name,
cmd,
path=path,
container_type=__virtualname__,
exec_driver=EXEC_DRIVER,
output=output,
no_start=no_start,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
ignore_retcode=ignore_retcode,
use_vt=use_vt,
keep_env=keep_env)
else:
if not chroot_fallback:
raise CommandExecutionError(
'{0} is not attachable.'.format(name))
rootfs = info(name, path=path).get('rootfs')
# Set context var to make cmd.run_chroot run cmd.run instead of
# cmd.run_all.
__context__['cmd.run_chroot.func'] = __salt__['cmd.run']
ret = __salt__['cmd.run_chroot'](rootfs,
cmd,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
ignore_retcode=ignore_retcode)
except Exception:
raise
finally:
# Make sure we honor preserve_state, even if there was an exception
new_state = state(name, path=path)
if preserve_state:
if orig_state == 'stopped' and new_state != 'stopped':
stop(name, path=path)
elif orig_state == 'frozen' and new_state != 'frozen':
freeze(name, start=True, path=path)
if output in (None, 'all'):
return ret
else:
return ret[output]
def run(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.8.0
Run :mod:`cmd.run <salt.modules.cmdmod.run>` within a container
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed in stderr if the command being run
does not exist. If no output is returned using this function, try using
:mod:`lxc.run_stderr <salt.modules.lxc.run_stderr>` or
:mod:`lxc.run_all <salt.modules.lxc.run_all>`.
name
Name of the container in which to run the command
cmd
Command to run
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console. Assumes
``output=all``.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
CLI Example:
.. code-block:: bash
salt myminion lxc.run mycontainer 'ifconfig -a'
'''
return _run(name,
cmd,
path=path,
output=None,
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def run_stdout(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.5.0
Run :mod:`cmd.run_stdout <salt.modules.cmdmod.run_stdout>` within a container
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed in stderr if the command being run
does not exist. If no output is returned using this function, try using
:mod:`lxc.run_stderr <salt.modules.lxc.run_stderr>` or
:mod:`lxc.run_all <salt.modules.lxc.run_all>`.
name
Name of the container in which to run the command
cmd
Command to run
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console
``output=all``.
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
CLI Example:
.. code-block:: bash
salt myminion lxc.run_stdout mycontainer 'ifconfig -a'
'''
return _run(name,
cmd,
path=path,
output='stdout',
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def run_stderr(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.5.0
Run :mod:`cmd.run_stderr <salt.modules.cmdmod.run_stderr>` within a container
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed if the command being run does not
exist.
name
Name of the container in which to run the command
cmd
Command to run
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console
``output=all``.
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
CLI Example:
.. code-block:: bash
salt myminion lxc.run_stderr mycontainer 'ip addr show'
'''
return _run(name,
cmd,
path=path,
output='stderr',
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def retcode(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.5.0
Run :mod:`cmd.retcode <salt.modules.cmdmod.retcode>` within a container
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed in stderr if the command being run
does not exist. If the retcode is nonzero and not what was expected,
try using :mod:`lxc.run_stderr <salt.modules.lxc.run_stderr>`
or :mod:`lxc.run_all <salt.modules.lxc.run_all>`.
name
Name of the container in which to run the command
cmd
Command to run
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console
``output=all``.
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
CLI Example:
.. code-block:: bash
salt myminion lxc.retcode mycontainer 'ip addr show'
'''
return _run(name,
cmd,
output='retcode',
path=path,
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def run_all(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.5.0
Run :mod:`cmd.run_all <salt.modules.cmdmod.run_all>` within a container
.. note::
While the command is run within the container, it is initiated from the
host. Therefore, the PID in the return dict is from the host, not from
the container.
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed in stderr if the command being run
does not exist.
name
Name of the container in which to run the command
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
cmd
Command to run
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console
``output=all``.
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
CLI Example:
.. code-block:: bash
salt myminion lxc.run_all mycontainer 'ip addr show'
'''
return _run(name,
cmd,
output='all',
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
path=path,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def _get_md5(name, path):
'''
Get the MD5 checksum of a file from a container
'''
output = run_stdout(name, 'md5sum "{0}"'.format(path),
chroot_fallback=True,
ignore_retcode=True)
try:
return output.split()[0]
except IndexError:
# Destination file does not exist or could not be accessed
return None
def copy_to(name, source, dest, overwrite=False, makedirs=False, path=None):
'''
.. versionchanged:: 2015.8.0
Function renamed from ``lxc.cp`` to ``lxc.copy_to`` for consistency
with other container types. ``lxc.cp`` will continue to work, however.
For versions 2015.2.x and earlier, use ``lxc.cp``.
Copy a file or directory from the host into a container
name
Container name
source
File to be copied to the container
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
dest
Destination on the container. Must be an absolute path.
.. versionchanged:: 2015.5.0
If the destination is a directory, the file will be copied into
that directory.
overwrite : False
Unless this option is set to ``True``, then if a file exists at the
location specified by the ``dest`` argument, an error will be raised.
.. versionadded:: 2015.8.0
makedirs : False
Create the parent directory on the container if it does not already
exist.
.. versionadded:: 2015.5.0
CLI Example:
.. code-block:: bash
salt 'minion' lxc.copy_to /tmp/foo /root/foo
salt 'minion' lxc.cp /tmp/foo /root/foo
'''
_ensure_running(name, no_start=True, path=path)
return __salt__['container_resource.copy_to'](
name,
source,
dest,
container_type=__virtualname__,
path=path,
exec_driver=EXEC_DRIVER,
overwrite=overwrite,
makedirs=makedirs)
cp = salt.utils.functools.alias_function(copy_to, 'cp')
def read_conf(conf_file, out_format='simple'):
'''
Read in an LXC configuration file. By default returns a simple, unsorted
dict, but can also return a more detailed structure including blank lines
and comments.
out_format:
set to 'simple' if you need the old and unsupported behavior.
This won't support the multiple lxc values (eg: multiple network nics)
CLI Examples:
.. code-block:: bash
salt 'minion' lxc.read_conf /etc/lxc/mycontainer.conf
salt 'minion' lxc.read_conf /etc/lxc/mycontainer.conf out_format=commented
'''
ret_commented = []
ret_simple = {}
with salt.utils.files.fopen(conf_file, 'r') as fp_:
for line in salt.utils.data.decode(fp_.readlines()):
if '=' not in line:
ret_commented.append(line)
continue
comps = line.split('=')
value = '='.join(comps[1:]).strip()
comment = None
if value.strip().startswith('#'):
vcomps = value.strip().split('#')
value = vcomps[1].strip()
comment = '#'.join(vcomps[1:]).strip()
ret_commented.append({comps[0].strip(): {
'value': value,
'comment': comment,
}})
else:
ret_commented.append({comps[0].strip(): value})
ret_simple[comps[0].strip()] = value
if out_format == 'simple':
return ret_simple
return ret_commented
def write_conf(conf_file, conf):
'''
Write out an LXC configuration file
This is normally only used internally. The format of the data structure
must match that which is returned from ``lxc.read_conf()``, with
``out_format`` set to ``commented``.
An example might look like:
.. code-block:: python
[
{'lxc.utsname': '$CONTAINER_NAME'},
'# This is a commented line\\n',
'\\n',
{'lxc.mount': '$CONTAINER_FSTAB'},
{'lxc.rootfs': {'comment': 'This is another test',
'value': 'This is another test'}},
'\\n',
{'lxc.network.type': 'veth'},
{'lxc.network.flags': 'up'},
{'lxc.network.link': 'br0'},
{'lxc.network.mac': '$CONTAINER_MACADDR'},
{'lxc.network.ipv4': '$CONTAINER_IPADDR'},
{'lxc.network.name': '$CONTAINER_DEVICENAME'},
]
CLI Example:
.. code-block:: bash
salt 'minion' lxc.write_conf /etc/lxc/mycontainer.conf \\
out_format=commented
'''
if not isinstance(conf, list):
raise SaltInvocationError('Configuration must be passed as a list')
# construct the content prior to write to the file
# to avoid half written configs
content = ''
for line in conf:
if isinstance(line, (six.text_type, six.string_types)):
content += line
elif isinstance(line, dict):
for key in list(line.keys()):
out_line = None
if isinstance(
line[key],
(six.text_type, six.string_types, six.integer_types, float)
):
out_line = ' = '.join((key, "{0}".format(line[key])))
elif isinstance(line[key], dict):
out_line = ' = '.join((key, line[key]['value']))
if 'comment' in line[key]:
out_line = ' # '.join((out_line, line[key]['comment']))
if out_line:
content += out_line
content += '\n'
with salt.utils.files.fopen(conf_file, 'w') as fp_:
fp_.write(salt.utils.stringutils.to_str(content))
return {}
def edit_conf(conf_file,
out_format='simple',
read_only=False,
lxc_config=None,
**kwargs):
'''
Edit an LXC configuration file. If a setting is already present inside the
file, its value will be replaced. If it does not exist, it will be appended
to the end of the file. Comments and blank lines will be kept in-tact if
they already exist in the file.
out_format:
Set to simple if you need backward compatibility (multiple items for a
simple key is not supported)
read_only:
return only the edited configuration without applying it
to the underlying lxc configuration file
lxc_config:
List of dict containning lxc configuration items
For network configuration, you also need to add the device it belongs
to, otherwise it will default to eth0.
Also, any change to a network parameter will result in the whole
network reconfiguration to avoid mismatchs, be aware of that !
After the file is edited, its contents will be returned. By default, it
will be returned in ``simple`` format, meaning an unordered dict (which
may not represent the actual file order). Passing in an ``out_format`` of
``commented`` will return a data structure which accurately represents the
order and content of the file.
CLI Example:
.. code-block:: bash
salt 'minion' lxc.edit_conf /etc/lxc/mycontainer.conf \\
out_format=commented lxc.network.type=veth
salt 'minion' lxc.edit_conf /etc/lxc/mycontainer.conf \\
out_format=commented \\
lxc_config="[{'lxc.network.name': 'eth0', \\
'lxc.network.ipv4': '1.2.3.4'},
{'lxc.network.name': 'eth2', \\
'lxc.network.ipv4': '1.2.3.5',\\
'lxc.network.gateway': '1.2.3.1'}]"
'''
data = []
try:
conf = read_conf(conf_file, out_format=out_format)
except Exception:
conf = []
if not lxc_config:
lxc_config = []
lxc_config = copy.deepcopy(lxc_config)
# search if we want to access net config
# in that case, we will replace all the net configuration
net_config = []
for lxc_kws in lxc_config + [kwargs]:
net_params = {}
for kwarg in [a for a in lxc_kws]:
if kwarg.startswith('__'):
continue
if kwarg.startswith('lxc.network.'):
net_params[kwarg] = lxc_kws[kwarg]
lxc_kws.pop(kwarg, None)
if net_params:
net_config.append(net_params)
nic_opts = salt.utils.odict.OrderedDict()
for params in net_config:
dev = params.get('lxc.network.name', DEFAULT_NIC)
dev_opts = nic_opts.setdefault(dev, salt.utils.odict.OrderedDict())
for param in params:
opt = param.replace('lxc.network.', '')
opt = {'hwaddr': 'mac'}.get(opt, opt)
dev_opts[opt] = params[param]
net_changes = []
if nic_opts:
net_changes = _config_list(conf, only_net=True,
**{'network_profile': DEFAULT_NIC,
'nic_opts': nic_opts})
if net_changes:
lxc_config.extend(net_changes)
for line in conf:
if not isinstance(line, dict):
data.append(line)
continue
else:
for key in list(line.keys()):
val = line[key]
if net_changes and key.startswith('lxc.network.'):
continue
found = False
for ix in range(len(lxc_config)):
kw = lxc_config[ix]
if key in kw:
found = True
data.append({key: kw[key]})
del kw[key]
if not found:
data.append({key: val})
for lxc_kws in lxc_config:
for kwarg in lxc_kws:
data.append({kwarg: lxc_kws[kwarg]})
if read_only:
return data
write_conf(conf_file, data)
return read_conf(conf_file, out_format)
def reboot(name, path=None):
'''
Reboot a container.
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Examples:
.. code-block:: bash
salt 'minion' lxc.reboot myvm
'''
ret = {'result': True,
'changes': {},
'comment': '{0} rebooted'.format(name)}
does_exist = exists(name, path=path)
if does_exist and (state(name, path=path) == 'running'):
try:
stop(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
ret['result'] = False
return ret
if does_exist and (state(name, path=path) != 'running'):
try:
start(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
ret['result'] = False
return ret
ret['changes'][name] = 'rebooted'
return ret
def reconfigure(name,
cpu=None,
cpuset=None,
cpushare=None,
memory=None,
profile=None,
network_profile=None,
nic_opts=None,
bridge=None,
gateway=None,
autostart=None,
utsname=None,
rootfs=None,
path=None,
**kwargs):
'''
Reconfigure a container.
This only applies to a few property
name
Name of the container.
utsname
utsname of the container.
.. versionadded:: 2016.3.0
rootfs
rootfs of the container.
.. versionadded:: 2016.3.0
cpu
Select a random number of cpu cores and assign it to the cpuset, if the
cpuset option is set then this option will be ignored
cpuset
Explicitly define the cpus this container will be bound to
cpushare
cgroups cpu shares.
autostart
autostart container on reboot
memory
cgroups memory limit, in MB.
(0 for nolimit, None for old default 1024MB)
gateway
the ipv4 gateway to use
the default does nothing more than lxcutils does
bridge
the bridge to use
the default does nothing more than lxcutils does
nic
Network interfaces profile (defined in config or pillar).
nic_opts
Extra options for network interfaces, will override
``{"eth0": {"mac": "aa:bb:cc:dd:ee:ff", "ipv4": "10.1.1.1", "ipv6": "2001:db8::ff00:42:8329"}}``
or
``{"eth0": {"mac": "aa:bb:cc:dd:ee:ff", "ipv4": "10.1.1.1/24", "ipv6": "2001:db8::ff00:42:8329"}}``
path
path to the container parent
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt-call -lall mc_lxc_fork.reconfigure foobar nic_opts="{'eth1': {'mac': '00:16:3e:dd:ee:44'}}" memory=4
'''
changes = {}
cpath = get_root_path(path)
path = os.path.join(cpath, name, 'config')
ret = {'name': name,
'comment': 'config for {0} up to date'.format(name),
'result': True,
'changes': changes}
profile = get_container_profile(copy.deepcopy(profile))
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, _marker)
profile_match = profile.pop(key, default)
# let kwarg overrides be the preferred choice
if kw_overrides_match is _marker:
return profile_match
return kw_overrides_match
if nic_opts is not None and not network_profile:
network_profile = DEFAULT_NIC
if autostart is not None:
autostart = select('autostart', autostart)
else:
autostart = 'keep'
if not utsname:
utsname = select('utsname', utsname)
if os.path.exists(path):
old_chunks = read_conf(path, out_format='commented')
make_kw = salt.utils.odict.OrderedDict([
('utsname', utsname),
('rootfs', rootfs),
('autostart', autostart),
('cpu', cpu),
('gateway', gateway),
('cpuset', cpuset),
('cpushare', cpushare),
('network_profile', network_profile),
('nic_opts', nic_opts),
('bridge', bridge)])
# match 0 and none as memory = 0 in lxc config is harmful
if memory:
make_kw['memory'] = memory
kw = salt.utils.odict.OrderedDict()
for key, val in six.iteritems(make_kw):
if val is not None:
kw[key] = val
new_cfg = _config_list(conf_tuples=old_chunks, **kw)
if new_cfg:
edit_conf(path, out_format='commented', lxc_config=new_cfg)
chunks = read_conf(path, out_format='commented')
if old_chunks != chunks:
ret['comment'] = '{0} lxc config updated'.format(name)
if state(name, path=path) == 'running':
cret = reboot(name, path=path)
ret['result'] = cret['result']
return ret
def apply_network_profile(name, network_profile, nic_opts=None, path=None):
'''
.. versionadded:: 2015.5.0
Apply a network profile to a container
network_profile
profile name or default values (dict)
nic_opts
values to override in defaults (dict)
indexed by nic card names
path
path to the container parent
.. versionadded:: 2015.8.0
CLI Examples:
.. code-block:: bash
salt 'minion' lxc.apply_network_profile web1 centos
salt 'minion' lxc.apply_network_profile web1 centos \\
nic_opts="{'eth0': {'mac': 'xx:xx:xx:xx:xx:xx'}}"
salt 'minion' lxc.apply_network_profile web1 \\
"{'eth0': {'mac': 'xx:xx:xx:xx:xx:yy'}}"
nic_opts="{'eth0': {'mac': 'xx:xx:xx:xx:xx:xx'}}"
The special case to disable use of ethernet nics:
.. code-block:: bash
salt 'minion' lxc.apply_network_profile web1 centos \\
"{eth0: {disable: true}}"
'''
cpath = get_root_path(path)
cfgpath = os.path.join(cpath, name, 'config')
before = []
with salt.utils.files.fopen(cfgpath, 'r') as fp_:
for line in fp_:
before.append(line)
lxcconfig = _LXCConfig(name=name, path=path)
old_net = lxcconfig._filter_data('lxc.network')
network_params = {}
for param in _network_conf(
conf_tuples=old_net,
network_profile=network_profile, nic_opts=nic_opts
):
network_params.update(param)
if network_params:
edit_conf(cfgpath, out_format='commented', **network_params)
after = []
with salt.utils.files.fopen(cfgpath, 'r') as fp_:
for line in fp_:
after.append(line)
diff = ''
for line in difflib.unified_diff(before,
after,
fromfile='before',
tofile='after'):
diff += line
return diff
def get_pid(name, path=None):
'''
Returns a container pid.
Throw an exception if the container isn't running.
CLI Example:
.. code-block:: bash
salt '*' lxc.get_pid name
'''
if name not in list_(limit='running', path=path):
raise CommandExecutionError('Container {0} is not running, can\'t determine PID'.format(name))
info = __salt__['cmd.run']('lxc-info -n {0}'.format(name)).split("\n")
pid = [line.split(':')[1].strip() for line in info if re.match(r'\s*PID', line)][0]
return pid
def add_veth(name, interface_name, bridge=None, path=None):
'''
Add a veth to a container.
Note : this function doesn't update the container config, just add the interface at runtime
name
Name of the container
interface_name
Name of the interface in the container
bridge
Name of the bridge to attach the interface to (facultative)
CLI Examples:
.. code-block:: bash
salt '*' lxc.add_veth container_name eth1 br1
salt '*' lxc.add_veth container_name eth1
'''
# Get container init PID
pid = get_pid(name, path=path)
# Generate a ramdom string for veth and ensure that is isn't present on the system
while True:
random_veth = 'veth'+''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(6))
if random_veth not in __salt__['network.interfaces']().keys():
break
# Check prerequisites
if not __salt__['file.directory_exists']('/var/run/'):
raise CommandExecutionError('Directory /var/run required for lxc.add_veth doesn\'t exists')
if not __salt__['file.file_exists']('/proc/{0}/ns/net'.format(pid)):
raise CommandExecutionError('Proc file for container {0} network namespace doesn\'t exists'.format(name))
if not __salt__['file.directory_exists']('/var/run/netns'):
__salt__['file.mkdir']('/var/run/netns')
# Ensure that the symlink is up to date (change on container restart)
if __salt__['file.is_link']('/var/run/netns/{0}'.format(name)):
__salt__['file.remove']('/var/run/netns/{0}'.format(name))
__salt__['file.symlink']('/proc/{0}/ns/net'.format(pid), '/var/run/netns/{0}'.format(name))
# Ensure that interface doesn't exists
interface_exists = 0 == __salt__['cmd.retcode']('ip netns exec {netns} ip address list {interface}'.format(
netns=name,
interface=interface_name
))
if interface_exists:
raise CommandExecutionError('Interface {interface} already exists in {container}'.format(
interface=interface_name,
container=name
))
# Create veth and bring it up
if __salt__['cmd.retcode']('ip link add name {veth} type veth peer name {veth}_c'.format(veth=random_veth)) != 0:
raise CommandExecutionError('Error while creating the veth pair {0}'.format(random_veth))
if __salt__['cmd.retcode']('ip link set dev {0} up'.format(random_veth)) != 0:
raise CommandExecutionError('Error while bringing up host-side veth {0}'.format(random_veth))
# Attach it to the container
attached = 0 == __salt__['cmd.retcode']('ip link set dev {veth}_c netns {container} name {interface_name}'.format(
veth=random_veth,
container=name,
interface_name=interface_name
))
if not attached:
raise CommandExecutionError('Error while attaching the veth {veth} to container {container}'.format(
veth=random_veth,
container=name
))
__salt__['file.remove']('/var/run/netns/{0}'.format(name))
if bridge is not None:
__salt__['bridge.addif'](bridge, random_veth)
|
saltstack/salt
|
salt/modules/lxc.py
|
_config_list
|
python
|
def _config_list(conf_tuples=None, only_net=False, **kwargs):
'''
Return a list of dicts from the salt level configurations
conf_tuples
_LXCConfig compatible list of entries which can contain
- string line
- tuple (lxc config param,value)
- dict of one entry: {lxc config param: value)
only_net
by default we add to the tuples a reflection of both
the real config if avalaible and a certain amount of
default values like the cpu parameters, the memory
and etc.
On the other hand, we also no matter the case reflect
the network configuration computed from the actual config if
available and given values.
if no_default_loads is set, we will only
reflect the network configuration back to the conf tuples
list
'''
# explicit cast
only_net = bool(only_net)
if not conf_tuples:
conf_tuples = []
kwargs = copy.deepcopy(kwargs)
ret = []
if not only_net:
default_data = _get_lxc_default_data(**kwargs)
for k, val in six.iteritems(default_data):
ret.append({k: val})
net_datas = _network_conf(conf_tuples=conf_tuples, **kwargs)
ret.extend(net_datas)
return ret
|
Return a list of dicts from the salt level configurations
conf_tuples
_LXCConfig compatible list of entries which can contain
- string line
- tuple (lxc config param,value)
- dict of one entry: {lxc config param: value)
only_net
by default we add to the tuples a reflection of both
the real config if avalaible and a certain amount of
default values like the cpu parameters, the memory
and etc.
On the other hand, we also no matter the case reflect
the network configuration computed from the actual config if
available and given values.
if no_default_loads is set, we will only
reflect the network configuration back to the conf tuples
list
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/lxc.py#L915-L951
|
[
"def _network_conf(conf_tuples=None, **kwargs):\n '''\n Network configuration defaults\n\n network_profile\n as for containers, we can either call this function\n either with a network_profile dict or network profile name\n in the kwargs\n nic_opts\n overrides or extra nics in the form {nic_name: {set: tings}\n\n '''\n nic = kwargs.get('network_profile', None)\n ret = []\n nic_opts = kwargs.get('nic_opts', {})\n if nic_opts is None:\n # coming from elsewhere\n nic_opts = {}\n if not conf_tuples:\n conf_tuples = []\n old = _get_veths(conf_tuples)\n if not old:\n old = {}\n\n # if we have a profile name, get the profile and load the network settings\n # this will obviously by default look for a profile called \"eth0\"\n # or by what is defined in nic_opts\n # and complete each nic settings by sane defaults\n if nic and isinstance(nic, (six.string_types, dict)):\n nicp = get_network_profile(nic)\n else:\n nicp = {}\n if DEFAULT_NIC not in nicp:\n nicp[DEFAULT_NIC] = {}\n\n kwargs = copy.deepcopy(kwargs)\n gateway = kwargs.pop('gateway', None)\n bridge = kwargs.get('bridge', None)\n if nic_opts:\n for dev, args in six.iteritems(nic_opts):\n ethx = nicp.setdefault(dev, {})\n try:\n ethx = salt.utils.dictupdate.update(ethx, args)\n except AttributeError:\n raise SaltInvocationError('Invalid nic_opts configuration')\n ifs = [a for a in nicp]\n ifs += [a for a in old if a not in nicp]\n ifs.sort()\n gateway_set = False\n for dev in ifs:\n args = nicp.get(dev, {})\n opts = nic_opts.get(dev, {}) if nic_opts else {}\n old_if = old.get(dev, {})\n disable = opts.get('disable', args.get('disable', False))\n if disable:\n continue\n mac = opts.get('mac',\n opts.get('hwaddr',\n args.get('mac',\n args.get('hwaddr', ''))))\n type_ = opts.get('type', args.get('type', ''))\n flags = opts.get('flags', args.get('flags', ''))\n link = opts.get('link', args.get('link', ''))\n ipv4 = opts.get('ipv4', args.get('ipv4', ''))\n ipv6 = opts.get('ipv6', args.get('ipv6', ''))\n infos = salt.utils.odict.OrderedDict([\n ('lxc.network.type', {\n 'test': not type_,\n 'value': type_,\n 'old': old_if.get('lxc.network.type'),\n 'default': 'veth'}),\n ('lxc.network.name', {\n 'test': False,\n 'value': dev,\n 'old': dev,\n 'default': dev}),\n ('lxc.network.flags', {\n 'test': not flags,\n 'value': flags,\n 'old': old_if.get('lxc.network.flags'),\n 'default': 'up'}),\n ('lxc.network.link', {\n 'test': not link,\n 'value': link,\n 'old': old_if.get('lxc.network.link'),\n 'default': search_lxc_bridge()}),\n ('lxc.network.hwaddr', {\n 'test': not mac,\n 'value': mac,\n 'old': old_if.get('lxc.network.hwaddr'),\n 'default': salt.utils.network.gen_mac()}),\n ('lxc.network.ipv4', {\n 'test': not ipv4,\n 'value': ipv4,\n 'old': old_if.get('lxc.network.ipv4', ''),\n 'default': None}),\n ('lxc.network.ipv6', {\n 'test': not ipv6,\n 'value': ipv6,\n 'old': old_if.get('lxc.network.ipv6', ''),\n 'default': None})])\n # for each parameter, if not explicitly set, the\n # config value present in the LXC configuration should\n # take precedence over the profile configuration\n for info in list(infos.keys()):\n bundle = infos[info]\n if bundle['test']:\n if bundle['old']:\n bundle['value'] = bundle['old']\n elif bundle['default']:\n bundle['value'] = bundle['default']\n for info, data in six.iteritems(infos):\n if data['value']:\n ret.append({info: data['value']})\n for key, val in six.iteritems(args):\n if key == 'link' and bridge:\n val = bridge\n val = opts.get(key, val)\n if key in [\n 'type', 'flags', 'name',\n 'gateway', 'mac', 'link', 'ipv4', 'ipv6'\n ]:\n continue\n ret.append({'lxc.network.{0}'.format(key): val})\n # gateway (in automode) must be appended following network conf !\n if not gateway:\n gateway = args.get('gateway', None)\n if gateway is not None and not gateway_set:\n ret.append({'lxc.network.ipv4.gateway': gateway})\n # only one network gateway ;)\n gateway_set = True\n # normally, this won't happen\n # set the gateway if specified even if we did\n # not managed the network underlying\n if gateway is not None and not gateway_set:\n ret.append({'lxc.network.ipv4.gateway': gateway})\n # only one network gateway ;)\n gateway_set = True\n\n new = _get_veths(ret)\n # verify that we did not loose the mac settings\n for iface in [a for a in new]:\n ndata = new[iface]\n nmac = ndata.get('lxc.network.hwaddr', '')\n ntype = ndata.get('lxc.network.type', '')\n omac, otype = '', ''\n if iface in old:\n odata = old[iface]\n omac = odata.get('lxc.network.hwaddr', '')\n otype = odata.get('lxc.network.type', '')\n # default for network type is setted here\n # attention not to change the network type\n # without a good and explicit reason to.\n if otype and not ntype:\n ntype = otype\n if not ntype:\n ntype = 'veth'\n new[iface]['lxc.network.type'] = ntype\n if omac and not nmac:\n new[iface]['lxc.network.hwaddr'] = omac\n\n ret = []\n for val in six.itervalues(new):\n for row in val:\n ret.append(salt.utils.odict.OrderedDict([(row, val[row])]))\n # on old versions of lxc, still support the gateway auto mode\n # if we didn't explicitly say no to\n # (lxc.network.ipv4.gateway: auto)\n if _LooseVersion(version()) <= _LooseVersion('1.0.7') and \\\n True not in ['lxc.network.ipv4.gateway' in a for a in ret] and \\\n True in ['lxc.network.ipv4' in a for a in ret]:\n ret.append({'lxc.network.ipv4.gateway': 'auto'})\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Control Linux Containers via Salt
:depends: lxc package for distribution
lxc >= 1.0 (even beta alpha) is required
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import datetime
import copy
import string
import textwrap
import difflib
import logging
import tempfile
import os
import pipes
import time
import shutil
import re
import random
# Import salt libs
import salt.utils.args
import salt.utils.cloud
import salt.utils.data
import salt.utils.dictupdate
import salt.utils.files
import salt.utils.functools
import salt.utils.hashutils
import salt.utils.network
import salt.utils.odict
import salt.utils.path
import salt.utils.stringutils
from salt.exceptions import CommandExecutionError, SaltInvocationError
import salt.config
from salt.utils.versions import LooseVersion as _LooseVersion
# Import 3rd-party libs
from salt.ext import six
# pylint: disable=import-error,no-name-in-module
from salt.ext.six.moves import range # pylint: disable=redefined-builtin
from salt.ext.six.moves.urllib.parse import urlparse as _urlparse
# pylint: enable=import-error,no-name-in-module
# Set up logging
log = logging.getLogger(__name__)
# Don't shadow built-in's.
__func_alias__ = {
'list_': 'list',
'ls_': 'ls'
}
__virtualname__ = 'lxc'
DEFAULT_NIC = 'eth0'
DEFAULT_BR = 'br0'
SEED_MARKER = '/lxc.initial_seed'
EXEC_DRIVER = 'lxc-attach'
DEFAULT_PATH = '/var/lib/lxc'
_marker = object()
def __virtual__():
if salt.utils.path.which('lxc-start'):
return __virtualname__
# To speed up the whole thing, we decided to not use the
# subshell way and assume things are in place for lxc
# Discussion made by @kiorky and @thatch45
# lxc-version presence is not sufficient, in lxc1.0 alpha
# (precise backports), we have it and it is sufficient
# for the module to execute.
# elif salt.utils.path.which('lxc-version'):
# passed = False
# try:
# passed = subprocess.check_output(
# 'lxc-version').split(':')[1].strip() >= '1.0'
# except Exception:
# pass
# if not passed:
# log.warning('Support for lxc < 1.0 may be incomplete.')
# return 'lxc'
# return False
#
return (False, 'The lxc execution module cannot be loaded: the lxc-start binary is not in the path.')
def get_root_path(path):
'''
Get the configured lxc root for containers
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.get_root_path
'''
if not path:
path = __opts__.get('lxc.root_path', DEFAULT_PATH)
return path
def version():
'''
Return the actual lxc client version
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.version
'''
k = 'lxc.version'
if not __context__.get(k, None):
cversion = __salt__['cmd.run_all']('lxc-info --version')
if not cversion['retcode']:
ver = _LooseVersion(cversion['stdout'])
if ver < _LooseVersion('1.0'):
raise CommandExecutionError('LXC should be at least 1.0')
__context__[k] = "{0}".format(ver)
return __context__.get(k, None)
def _clear_context():
'''
Clear any lxc variables set in __context__
'''
for var in [x for x in __context__ if x.startswith('lxc.')]:
log.trace('Clearing __context__[\'%s\']', var)
__context__.pop(var, None)
def _ip_sort(ip):
'''Ip sorting'''
idx = '001'
if ip == '127.0.0.1':
idx = '200'
if ip == '::1':
idx = '201'
elif '::' in ip:
idx = '100'
return '{0}___{1}'.format(idx, ip)
def search_lxc_bridges():
'''
Search which bridges are potentially available as LXC bridges
CLI Example:
.. code-block:: bash
salt '*' lxc.search_lxc_bridges
'''
bridges = __context__.get('lxc.bridges', None)
# either match not yet called or no bridges were found
# to handle the case where lxc was not installed on the first
# call
if not bridges:
bridges = set()
running_bridges = set()
bridges.add(DEFAULT_BR)
try:
output = __salt__['cmd.run_all']('brctl show')
for line in output['stdout'].splitlines()[1:]:
if not line.startswith(' '):
running_bridges.add(line.split()[0].strip())
except (SaltInvocationError, CommandExecutionError):
pass
for ifc, ip in six.iteritems(
__grains__.get('ip_interfaces', {})
):
if ifc in running_bridges:
bridges.add(ifc)
elif os.path.exists(
'/sys/devices/virtual/net/{0}/bridge'.format(ifc)
):
bridges.add(ifc)
bridges = list(bridges)
# if we found interfaces that have lxc in their names
# we filter them as being the potential lxc bridges
# we also try to default on br0 on other cases
def sort_bridges(a):
pref = 'z'
if 'lxc' in a:
pref = 'a'
elif 'br0' == a:
pref = 'c'
return '{0}_{1}'.format(pref, a)
bridges.sort(key=sort_bridges)
__context__['lxc.bridges'] = bridges
return bridges
def search_lxc_bridge():
'''
Search the first bridge which is potentially available as LXC bridge
CLI Example:
.. code-block:: bash
salt '*' lxc.search_lxc_bridge
'''
return search_lxc_bridges()[0]
def _get_salt_config(config, **kwargs):
if not config:
config = kwargs.get('minion', {})
if not config:
config = {}
config.setdefault('master',
kwargs.get('master',
__opts__.get('master',
__opts__['id'])))
config.setdefault(
'master_port',
kwargs.get('master_port',
__opts__.get('master_port',
__opts__.get('ret_port',
__opts__.get('4506')))))
if not config['master']:
config = {}
return config
def cloud_init_interface(name, vm_=None, **kwargs):
'''
Interface between salt.cloud.lxc driver and lxc.init
``vm_`` is a mapping of vm opts in the salt.cloud format
as documented for the lxc driver.
This can be used either:
- from the salt cloud driver
- because you find the argument to give easier here
than using directly lxc.init
.. warning::
BE REALLY CAREFUL CHANGING DEFAULTS !!!
IT'S A RETRO COMPATIBLE INTERFACE WITH
THE SALT CLOUD DRIVER (ask kiorky).
name
name of the lxc container to create
pub_key
public key to preseed the minion with.
Can be the keycontent or a filepath
priv_key
private key to preseed the minion with.
Can be the keycontent or a filepath
path
path to the container parent directory (default: /var/lib/lxc)
.. versionadded:: 2015.8.0
profile
:ref:`profile <tutorial-lxc-profiles-container>` selection
network_profile
:ref:`network profile <tutorial-lxc-profiles-network>` selection
nic_opts
per interface settings compatibles with
network profile (ipv4/ipv6/link/gateway/mac/netmask)
eg::
- {'eth0': {'mac': '00:16:3e:01:29:40',
'gateway': None, (default)
'link': 'br0', (default)
'gateway': None, (default)
'netmask': '', (default)
'ip': '22.1.4.25'}}
unconditional_install
given to lxc.bootstrap (see relative doc)
force_install
given to lxc.bootstrap (see relative doc)
config
any extra argument for the salt minion config
dnsservers
list of DNS servers to set inside the container
dns_via_dhcp
do not set the dns servers, let them be set by the dhcp.
autostart
autostart the container at boot time
password
administrative password for the container
bootstrap_delay
delay before launching bootstrap script at Container init
.. warning::
Legacy but still supported options:
from_container
which container we use as a template
when running lxc.clone
image
which template do we use when we
are using lxc.create. This is the default
mode unless you specify something in from_container
backing
which backing store to use.
Values can be: overlayfs, dir(default), lvm, zfs, brtfs
fstype
When using a blockdevice level backing store,
which filesystem to use on
size
When using a blockdevice level backing store,
which size for the filesystem to use on
snapshot
Use snapshot when cloning the container source
vgname
if using LVM: vgname
lvname
if using LVM: lvname
thinpool:
if using LVM: thinpool
ip
ip for the primary nic
mac
mac address for the primary nic
netmask
netmask for the primary nic (24)
= ``vm_.get('netmask', '24')``
bridge
bridge for the primary nic (lxcbr0)
gateway
network gateway for the container
additional_ips
additional ips which will be wired on the main bridge (br0)
which is connected to internet.
Be aware that you may use manual virtual mac addresses
providen by you provider (online, ovh, etc).
This is a list of mappings {ip: '', mac: '', netmask:''}
Set gateway to None and an interface with a gateway
to escape from another interface that eth0.
eg::
- {'mac': '00:16:3e:01:29:40',
'gateway': None, (default)
'link': 'br0', (default)
'netmask': '', (default)
'ip': '22.1.4.25'}
users
administrative users for the container
default: [root] and [root, ubuntu] on ubuntu
default_nic
name of the first interface, you should
really not override this
CLI Example:
.. code-block:: bash
salt '*' lxc.cloud_init_interface foo
'''
if vm_ is None:
vm_ = {}
vm_ = copy.deepcopy(vm_)
vm_ = salt.utils.dictupdate.update(vm_, kwargs)
profile_data = copy.deepcopy(
vm_.get('lxc_profile',
vm_.get('profile', {})))
if not isinstance(profile_data, (dict, six.string_types)):
profile_data = {}
profile = get_container_profile(profile_data)
def _cloud_get(k, default=None):
return vm_.get(k, profile.get(k, default))
if name is None:
name = vm_['name']
# if we are on ubuntu, default to ubuntu
default_template = ''
if __grains__.get('os', '') in ['Ubuntu']:
default_template = 'ubuntu'
image = _cloud_get('image')
if not image:
_cloud_get('template', default_template)
backing = _cloud_get('backing', 'dir')
if image:
profile['template'] = image
vgname = _cloud_get('vgname', None)
if vgname:
profile['vgname'] = vgname
if backing:
profile['backing'] = backing
snapshot = _cloud_get('snapshot', False)
autostart = bool(_cloud_get('autostart', True))
dnsservers = _cloud_get('dnsservers', [])
dns_via_dhcp = _cloud_get('dns_via_dhcp', True)
password = _cloud_get('password', 's3cr3t')
password_encrypted = _cloud_get('password_encrypted', False)
fstype = _cloud_get('fstype', None)
lvname = _cloud_get('lvname', None)
thinpool = _cloud_get('thinpool', None)
pub_key = _cloud_get('pub_key', None)
priv_key = _cloud_get('priv_key', None)
size = _cloud_get('size', '20G')
script = _cloud_get('script', None)
script_args = _cloud_get('script_args', None)
users = _cloud_get('users', None)
if users is None:
users = []
ssh_username = _cloud_get('ssh_username', None)
if ssh_username and (ssh_username not in users):
users.append(ssh_username)
network_profile = _cloud_get('network_profile', None)
nic_opts = kwargs.get('nic_opts', None)
netmask = _cloud_get('netmask', '24')
path = _cloud_get('path', None)
bridge = _cloud_get('bridge', None)
gateway = _cloud_get('gateway', None)
unconditional_install = _cloud_get('unconditional_install', False)
force_install = _cloud_get('force_install', True)
config = _get_salt_config(_cloud_get('config', {}), **vm_)
default_nic = _cloud_get('default_nic', DEFAULT_NIC)
# do the interface with lxc.init mainly via nic_opts
# to avoid extra and confusing extra use cases.
if not isinstance(nic_opts, dict):
nic_opts = salt.utils.odict.OrderedDict()
# have a reference to the default nic
eth0 = nic_opts.setdefault(default_nic,
salt.utils.odict.OrderedDict())
# lxc config is based of ifc order, be sure to use odicts.
if not isinstance(nic_opts, salt.utils.odict.OrderedDict):
bnic_opts = salt.utils.odict.OrderedDict()
bnic_opts.update(nic_opts)
nic_opts = bnic_opts
gw = None
# legacy salt.cloud scheme for network interfaces settings support
bridge = _cloud_get('bridge', None)
ip = _cloud_get('ip', None)
mac = _cloud_get('mac', None)
if ip:
fullip = ip
if netmask:
fullip += '/{0}'.format(netmask)
eth0['ipv4'] = fullip
if mac is not None:
eth0['mac'] = mac
for ix, iopts in enumerate(_cloud_get("additional_ips", [])):
ifh = "eth{0}".format(ix+1)
ethx = nic_opts.setdefault(ifh, {})
if gw is None:
gw = iopts.get('gateway', ethx.get('gateway', None))
if gw:
# only one and only one default gateway is allowed !
eth0.pop('gateway', None)
gateway = None
# even if the gateway if on default "eth0" nic
# and we popped it will work
# as we reinject or set it here.
ethx['gateway'] = gw
elink = iopts.get('link', ethx.get('link', None))
if elink:
ethx['link'] = elink
# allow dhcp
aip = iopts.get('ipv4', iopts.get('ip', None))
if aip:
ethx['ipv4'] = aip
nm = iopts.get('netmask', '')
if nm:
ethx['ipv4'] += '/{0}'.format(nm)
for i in ('mac', 'hwaddr'):
if i in iopts:
ethx['mac'] = iopts[i]
break
if 'mac' not in ethx:
ethx['mac'] = salt.utils.network.gen_mac()
# last round checking for unique gateway and such
gw = None
for ethx in [a for a in nic_opts]:
ndata = nic_opts[ethx]
if gw:
ndata.pop('gateway', None)
if 'gateway' in ndata:
gw = ndata['gateway']
gateway = None
# only use a default bridge / gateway if we configured them
# via the legacy salt cloud configuration style.
# On other cases, we should rely on settings provided by the new
# salt lxc network profile style configuration which can
# be also be overridden or a per interface basis via the nic_opts dict.
if bridge:
eth0['link'] = bridge
if gateway:
eth0['gateway'] = gateway
#
lxc_init_interface = {}
lxc_init_interface['name'] = name
lxc_init_interface['config'] = config
lxc_init_interface['memory'] = _cloud_get('memory', 0) # nolimit
lxc_init_interface['pub_key'] = pub_key
lxc_init_interface['priv_key'] = priv_key
lxc_init_interface['nic_opts'] = nic_opts
for clone_from in ['clone_from', 'clone', 'from_container']:
# clone_from should default to None if not available
lxc_init_interface['clone_from'] = _cloud_get(clone_from, None)
if lxc_init_interface['clone_from'] is not None:
break
lxc_init_interface['profile'] = profile
lxc_init_interface['snapshot'] = snapshot
lxc_init_interface['dnsservers'] = dnsservers
lxc_init_interface['fstype'] = fstype
lxc_init_interface['path'] = path
lxc_init_interface['vgname'] = vgname
lxc_init_interface['size'] = size
lxc_init_interface['lvname'] = lvname
lxc_init_interface['thinpool'] = thinpool
lxc_init_interface['force_install'] = force_install
lxc_init_interface['unconditional_install'] = (
unconditional_install
)
lxc_init_interface['bootstrap_url'] = script
lxc_init_interface['bootstrap_args'] = script_args
lxc_init_interface['bootstrap_shell'] = _cloud_get('bootstrap_shell', 'sh')
lxc_init_interface['bootstrap_delay'] = _cloud_get('bootstrap_delay', None)
lxc_init_interface['autostart'] = autostart
lxc_init_interface['users'] = users
lxc_init_interface['password'] = password
lxc_init_interface['password_encrypted'] = password_encrypted
# be sure not to let objects goes inside the return
# as this return will be msgpacked for use in the runner !
lxc_init_interface['network_profile'] = network_profile
for i in ['cpu', 'cpuset', 'cpushare']:
if _cloud_get(i, None):
try:
lxc_init_interface[i] = vm_[i]
except KeyError:
lxc_init_interface[i] = profile[i]
return lxc_init_interface
def _get_profile(key, name, **kwargs):
if isinstance(name, dict):
profilename = name.pop('name', None)
return _get_profile(key, profilename, **name)
if name is None:
profile_match = {}
else:
profile_match = \
__salt__['config.get'](
'lxc.{1}:{0}'.format(name, key),
default=None,
merge='recurse'
)
if profile_match is None:
# No matching profile, make the profile an empty dict so that
# overrides can be applied below.
profile_match = {}
if not isinstance(profile_match, dict):
raise CommandExecutionError('lxc.{0} must be a dictionary'.format(key))
# Overlay the kwargs to override matched profile data
overrides = salt.utils.args.clean_kwargs(**copy.deepcopy(kwargs))
profile_match = salt.utils.dictupdate.update(
copy.deepcopy(profile_match),
overrides
)
return profile_match
def get_container_profile(name=None, **kwargs):
'''
.. versionadded:: 2015.5.0
Gather a pre-configured set of container configuration parameters. If no
arguments are passed, an empty profile is returned.
Profiles can be defined in the minion or master config files, or in pillar
or grains, and are loaded using :mod:`config.get
<salt.modules.config.get>`. The key under which LXC profiles must be
configured is ``lxc.container_profile.profile_name``. An example container
profile would be as follows:
.. code-block:: yaml
lxc.container_profile:
ubuntu:
template: ubuntu
backing: lvm
vgname: lxc
size: 1G
Parameters set in a profile can be overridden by passing additional
container creation arguments (such as the ones passed to :mod:`lxc.create
<salt.modules.lxc.create>`) to this function.
A profile can be defined either as the name of the profile, or a dictionary
of variable names and values. See the :ref:`LXC Tutorial
<tutorial-lxc-profiles>` for more information on how to use LXC profiles.
CLI Example:
.. code-block:: bash
salt-call lxc.get_container_profile centos
salt-call lxc.get_container_profile ubuntu template=ubuntu backing=overlayfs
'''
profile = _get_profile('container_profile', name, **kwargs)
return profile
def get_network_profile(name=None, **kwargs):
'''
.. versionadded:: 2015.5.0
Gather a pre-configured set of network configuration parameters. If no
arguments are passed, the following default profile is returned:
.. code-block:: python
{'eth0': {'link': 'br0', 'type': 'veth', 'flags': 'up'}}
Profiles can be defined in the minion or master config files, or in pillar
or grains, and are loaded using :mod:`config.get
<salt.modules.config.get>`. The key under which LXC profiles must be
configured is ``lxc.network_profile``. An example network profile would be
as follows:
.. code-block:: yaml
lxc.network_profile.centos:
eth0:
link: br0
type: veth
flags: up
To disable networking entirely:
.. code-block:: yaml
lxc.network_profile.centos:
eth0:
disable: true
Parameters set in a profile can be overridden by passing additional
arguments to this function.
A profile can be passed either as the name of the profile, or a
dictionary of variable names and values. See the :ref:`LXC Tutorial
<tutorial-lxc-profiles>` for more information on how to use network
profiles.
.. warning::
The ``ipv4``, ``ipv6``, ``gateway``, and ``link`` (bridge) settings in
network profiles will only work if the container doesn't redefine the
network configuration (for example in
``/etc/sysconfig/network-scripts/ifcfg-<interface_name>`` on
RHEL/CentOS, or ``/etc/network/interfaces`` on Debian/Ubuntu/etc.)
CLI Example:
.. code-block:: bash
salt-call lxc.get_network_profile default
'''
profile = _get_profile('network_profile', name, **kwargs)
return profile
def _rand_cpu_str(cpu):
'''
Return a random subset of cpus for the cpuset config
'''
cpu = int(cpu)
avail = __salt__['status.nproc']()
if cpu < avail:
return '0-{0}'.format(avail)
to_set = set()
while len(to_set) < cpu:
choice = random.randint(0, avail - 1)
if choice not in to_set:
to_set.add(six.text_type(choice))
return ','.join(sorted(to_set))
def _network_conf(conf_tuples=None, **kwargs):
'''
Network configuration defaults
network_profile
as for containers, we can either call this function
either with a network_profile dict or network profile name
in the kwargs
nic_opts
overrides or extra nics in the form {nic_name: {set: tings}
'''
nic = kwargs.get('network_profile', None)
ret = []
nic_opts = kwargs.get('nic_opts', {})
if nic_opts is None:
# coming from elsewhere
nic_opts = {}
if not conf_tuples:
conf_tuples = []
old = _get_veths(conf_tuples)
if not old:
old = {}
# if we have a profile name, get the profile and load the network settings
# this will obviously by default look for a profile called "eth0"
# or by what is defined in nic_opts
# and complete each nic settings by sane defaults
if nic and isinstance(nic, (six.string_types, dict)):
nicp = get_network_profile(nic)
else:
nicp = {}
if DEFAULT_NIC not in nicp:
nicp[DEFAULT_NIC] = {}
kwargs = copy.deepcopy(kwargs)
gateway = kwargs.pop('gateway', None)
bridge = kwargs.get('bridge', None)
if nic_opts:
for dev, args in six.iteritems(nic_opts):
ethx = nicp.setdefault(dev, {})
try:
ethx = salt.utils.dictupdate.update(ethx, args)
except AttributeError:
raise SaltInvocationError('Invalid nic_opts configuration')
ifs = [a for a in nicp]
ifs += [a for a in old if a not in nicp]
ifs.sort()
gateway_set = False
for dev in ifs:
args = nicp.get(dev, {})
opts = nic_opts.get(dev, {}) if nic_opts else {}
old_if = old.get(dev, {})
disable = opts.get('disable', args.get('disable', False))
if disable:
continue
mac = opts.get('mac',
opts.get('hwaddr',
args.get('mac',
args.get('hwaddr', ''))))
type_ = opts.get('type', args.get('type', ''))
flags = opts.get('flags', args.get('flags', ''))
link = opts.get('link', args.get('link', ''))
ipv4 = opts.get('ipv4', args.get('ipv4', ''))
ipv6 = opts.get('ipv6', args.get('ipv6', ''))
infos = salt.utils.odict.OrderedDict([
('lxc.network.type', {
'test': not type_,
'value': type_,
'old': old_if.get('lxc.network.type'),
'default': 'veth'}),
('lxc.network.name', {
'test': False,
'value': dev,
'old': dev,
'default': dev}),
('lxc.network.flags', {
'test': not flags,
'value': flags,
'old': old_if.get('lxc.network.flags'),
'default': 'up'}),
('lxc.network.link', {
'test': not link,
'value': link,
'old': old_if.get('lxc.network.link'),
'default': search_lxc_bridge()}),
('lxc.network.hwaddr', {
'test': not mac,
'value': mac,
'old': old_if.get('lxc.network.hwaddr'),
'default': salt.utils.network.gen_mac()}),
('lxc.network.ipv4', {
'test': not ipv4,
'value': ipv4,
'old': old_if.get('lxc.network.ipv4', ''),
'default': None}),
('lxc.network.ipv6', {
'test': not ipv6,
'value': ipv6,
'old': old_if.get('lxc.network.ipv6', ''),
'default': None})])
# for each parameter, if not explicitly set, the
# config value present in the LXC configuration should
# take precedence over the profile configuration
for info in list(infos.keys()):
bundle = infos[info]
if bundle['test']:
if bundle['old']:
bundle['value'] = bundle['old']
elif bundle['default']:
bundle['value'] = bundle['default']
for info, data in six.iteritems(infos):
if data['value']:
ret.append({info: data['value']})
for key, val in six.iteritems(args):
if key == 'link' and bridge:
val = bridge
val = opts.get(key, val)
if key in [
'type', 'flags', 'name',
'gateway', 'mac', 'link', 'ipv4', 'ipv6'
]:
continue
ret.append({'lxc.network.{0}'.format(key): val})
# gateway (in automode) must be appended following network conf !
if not gateway:
gateway = args.get('gateway', None)
if gateway is not None and not gateway_set:
ret.append({'lxc.network.ipv4.gateway': gateway})
# only one network gateway ;)
gateway_set = True
# normally, this won't happen
# set the gateway if specified even if we did
# not managed the network underlying
if gateway is not None and not gateway_set:
ret.append({'lxc.network.ipv4.gateway': gateway})
# only one network gateway ;)
gateway_set = True
new = _get_veths(ret)
# verify that we did not loose the mac settings
for iface in [a for a in new]:
ndata = new[iface]
nmac = ndata.get('lxc.network.hwaddr', '')
ntype = ndata.get('lxc.network.type', '')
omac, otype = '', ''
if iface in old:
odata = old[iface]
omac = odata.get('lxc.network.hwaddr', '')
otype = odata.get('lxc.network.type', '')
# default for network type is setted here
# attention not to change the network type
# without a good and explicit reason to.
if otype and not ntype:
ntype = otype
if not ntype:
ntype = 'veth'
new[iface]['lxc.network.type'] = ntype
if omac and not nmac:
new[iface]['lxc.network.hwaddr'] = omac
ret = []
for val in six.itervalues(new):
for row in val:
ret.append(salt.utils.odict.OrderedDict([(row, val[row])]))
# on old versions of lxc, still support the gateway auto mode
# if we didn't explicitly say no to
# (lxc.network.ipv4.gateway: auto)
if _LooseVersion(version()) <= _LooseVersion('1.0.7') and \
True not in ['lxc.network.ipv4.gateway' in a for a in ret] and \
True in ['lxc.network.ipv4' in a for a in ret]:
ret.append({'lxc.network.ipv4.gateway': 'auto'})
return ret
def _get_lxc_default_data(**kwargs):
kwargs = copy.deepcopy(kwargs)
ret = {}
for k in ['utsname', 'rootfs']:
val = kwargs.get(k, None)
if val is not None:
ret['lxc.{0}'.format(k)] = val
autostart = kwargs.get('autostart')
# autostart can have made in kwargs, but with the None
# value which is invalid, we need an explicit boolean
# autostart = on is the default.
if autostart is None:
autostart = True
# we will set the regular lxc marker to restart container at
# machine (re)boot only if we did not explicitly ask
# not to touch to the autostart settings via
# autostart == 'keep'
if autostart != 'keep':
if autostart:
ret['lxc.start.auto'] = '1'
else:
ret['lxc.start.auto'] = '0'
memory = kwargs.get('memory')
if memory is not None:
# converting the config value from MB to bytes
ret['lxc.cgroup.memory.limit_in_bytes'] = memory * 1024 * 1024
cpuset = kwargs.get('cpuset')
if cpuset:
ret['lxc.cgroup.cpuset.cpus'] = cpuset
cpushare = kwargs.get('cpushare')
cpu = kwargs.get('cpu')
if cpushare:
ret['lxc.cgroup.cpu.shares'] = cpushare
if cpu and not cpuset:
ret['lxc.cgroup.cpuset.cpus'] = _rand_cpu_str(cpu)
return ret
def _get_veths(net_data):
'''
Parse the nic setup inside lxc conf tuples back to a dictionary indexed by
network interface
'''
if isinstance(net_data, dict):
net_data = list(net_data.items())
nics = salt.utils.odict.OrderedDict()
current_nic = salt.utils.odict.OrderedDict()
no_names = True
for item in net_data:
if item and isinstance(item, dict):
item = list(item.items())[0]
# skip LXC configuration comment lines, and play only with tuples conf
elif isinstance(item, six.string_types):
# deal with reflection of commented lxc configs
sitem = item.strip()
if sitem.startswith('#') or not sitem:
continue
elif '=' in item:
item = tuple([a.strip() for a in item.split('=', 1)])
if item[0] == 'lxc.network.type':
current_nic = salt.utils.odict.OrderedDict()
if item[0] == 'lxc.network.name':
no_names = False
nics[item[1].strip()] = current_nic
current_nic[item[0].strip()] = item[1].strip()
# if not ethernet card name has been collected, assuming we collected
# data for eth0
if no_names and current_nic:
nics[DEFAULT_NIC] = current_nic
return nics
class _LXCConfig(object):
'''
LXC configuration data
'''
pattern = re.compile(r'^(\S+)(\s*)(=)(\s*)(.*)')
non_interpretable_pattern = re.compile(r'^((#.*)|(\s*))$')
def __init__(self, **kwargs):
kwargs = copy.deepcopy(kwargs)
self.name = kwargs.pop('name', None)
path = get_root_path(kwargs.get('path', None))
self.data = []
if self.name:
self.path = os.path.join(path, self.name, 'config')
if os.path.isfile(self.path):
with salt.utils.files.fopen(self.path) as fhr:
for line in salt.utils.data.decode(fhr.readlines()):
match = self.pattern.findall((line.strip()))
if match:
self.data.append((match[0][0], match[0][-1]))
match = self.non_interpretable_pattern.findall(
(line.strip()))
if match:
self.data.append(('', match[0][0]))
else:
self.path = None
def _replace(key, val):
if val:
self._filter_data(key)
self.data.append((key, val))
default_data = _get_lxc_default_data(**kwargs)
for key, val in six.iteritems(default_data):
_replace(key, val)
old_net = self._filter_data('lxc.network')
net_datas = _network_conf(conf_tuples=old_net, **kwargs)
if net_datas:
for row in net_datas:
self.data.extend(list(row.items()))
# be sure to reset harmful settings
for idx in ['lxc.cgroup.memory.limit_in_bytes']:
if not default_data.get(idx):
self._filter_data(idx)
def as_string(self):
chunks = ('{0[0]}{1}{0[1]}'.format(item, (' = ' if item[0] else '')) for item in self.data)
return '\n'.join(chunks) + '\n'
def write(self):
if self.path:
content = self.as_string()
# 2 step rendering to be sure not to open/wipe the config
# before as_string succeeds.
with salt.utils.files.fopen(self.path, 'w') as fic:
fic.write(salt.utils.stringutils.to_str(content))
fic.flush()
def tempfile(self):
# this might look like the function name is shadowing the
# module, but it's not since the method belongs to the class
ntf = tempfile.NamedTemporaryFile()
ntf.write(self.as_string())
ntf.flush()
return ntf
def _filter_data(self, pattern):
'''
Removes parameters which match the pattern from the config data
'''
removed = []
filtered = []
for param in self.data:
if not param[0].startswith(pattern):
filtered.append(param)
else:
removed.append(param)
self.data = filtered
return removed
def _get_base(**kwargs):
'''
If the needed base does not exist, then create it, if it does exist
create nothing and return the name of the base lxc container so
it can be cloned.
'''
profile = get_container_profile(copy.deepcopy(kwargs.get('profile')))
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, _marker)
profile_match = profile.pop(key, default)
# let kwarg overrides be the preferred choice
if kw_overrides_match is _marker:
return profile_match
return kw_overrides_match
template = select('template')
image = select('image')
vgname = select('vgname')
path = kwargs.get('path', None)
# remove the above three variables from kwargs, if they exist, to avoid
# duplicates if create() is invoked below.
for param in ('path', 'image', 'vgname', 'template'):
kwargs.pop(param, None)
if image:
proto = _urlparse(image).scheme
img_tar = __salt__['cp.cache_file'](image)
img_name = os.path.basename(img_tar)
hash_ = salt.utils.hashutils.get_hash(
img_tar,
__salt__['config.get']('hash_type'))
name = '__base_{0}_{1}_{2}'.format(proto, img_name, hash_)
if not exists(name, path=path):
create(name, template=template, image=image,
path=path, vgname=vgname, **kwargs)
if vgname:
rootfs = os.path.join('/dev', vgname, name)
edit_conf(info(name, path=path)['config'],
out_format='commented', **{'lxc.rootfs': rootfs})
return name
elif template:
name = '__base_{0}'.format(template)
if not exists(name, path=path):
create(name, template=template, image=image, path=path,
vgname=vgname, **kwargs)
if vgname:
rootfs = os.path.join('/dev', vgname, name)
edit_conf(info(name, path=path)['config'],
out_format='commented', **{'lxc.rootfs': rootfs})
return name
return ''
def init(name,
config=None,
cpuset=None,
cpushare=None,
memory=None,
profile=None,
network_profile=None,
nic_opts=None,
cpu=None,
autostart=True,
password=None,
password_encrypted=None,
users=None,
dnsservers=None,
searchdomains=None,
bridge=None,
gateway=None,
pub_key=None,
priv_key=None,
force_install=False,
unconditional_install=False,
bootstrap_delay=None,
bootstrap_args=None,
bootstrap_shell=None,
bootstrap_url=None,
**kwargs):
'''
Initialize a new container.
This is a partial idempotent function as if it is already provisioned, we
will reset a bit the lxc configuration file but much of the hard work will
be escaped as markers will prevent re-execution of harmful tasks.
name
Name of the container
image
A tar archive to use as the rootfs for the container. Conflicts with
the ``template`` argument.
cpus
Select a random number of cpu cores and assign it to the cpuset, if the
cpuset option is set then this option will be ignored
cpuset
Explicitly define the cpus this container will be bound to
cpushare
cgroups cpu shares
autostart
autostart container on reboot
memory
cgroups memory limit, in MB
.. versionchanged:: 2015.5.0
If no value is passed, no limit is set. In earlier Salt versions,
not passing this value causes a 1024MB memory limit to be set, and
it was necessary to pass ``memory=0`` to set no limit.
gateway
the ipv4 gateway to use
the default does nothing more than lxcutils does
bridge
the bridge to use
the default does nothing more than lxcutils does
network_profile
Network profile to use for the container
.. versionadded:: 2015.5.0
nic_opts
Extra options for network interfaces, will override
``{"eth0": {"hwaddr": "aa:bb:cc:dd:ee:ff", "ipv4": "10.1.1.1", "ipv6": "2001:db8::ff00:42:8329"}}``
or
``{"eth0": {"hwaddr": "aa:bb:cc:dd:ee:ff", "ipv4": "10.1.1.1/24", "ipv6": "2001:db8::ff00:42:8329"}}``
users
Users for which the password defined in the ``password`` param should
be set. Can be passed as a comma separated list or a python list.
Defaults to just the ``root`` user.
password
Set the initial password for the users defined in the ``users``
parameter
password_encrypted : False
Set to ``True`` to denote a password hash instead of a plaintext
password
.. versionadded:: 2015.5.0
profile
A LXC profile (defined in config or pillar).
This can be either a real profile mapping or a string
to retrieve it in configuration
start
Start the newly-created container
dnsservers
list of dns servers to set in the container, default [] (no setting)
seed
Seed the container with the minion config. Default: ``True``
install
If salt-minion is not already installed, install it. Default: ``True``
config
Optional config parameters. By default, the id is set to
the name of the container.
master
salt master (default to minion's master)
master_port
salt master port (default to minion's master port)
pub_key
Explicit public key to preseed the minion with (optional).
This can be either a filepath or a string representing the key
priv_key
Explicit private key to preseed the minion with (optional).
This can be either a filepath or a string representing the key
approve_key
If explicit preseeding is not used;
Attempt to request key approval from the master. Default: ``True``
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
clone_from
Original from which to use a clone operation to create the container.
Default: ``None``
bootstrap_delay
Delay in seconds between end of container creation and bootstrapping.
Useful when waiting for container to obtain a DHCP lease.
.. versionadded:: 2015.5.0
bootstrap_url
See lxc.bootstrap
bootstrap_shell
See lxc.bootstrap
bootstrap_args
See lxc.bootstrap
force_install
Force installation even if salt-minion is detected,
this is the way to run vendor bootstrap scripts even
if a salt minion is already present in the container
unconditional_install
Run the script even if the container seems seeded
CLI Example:
.. code-block:: bash
salt 'minion' lxc.init name [cpuset=cgroups_cpuset] \\
[cpushare=cgroups_cpushare] [memory=cgroups_memory] \\
[nic=nic_profile] [profile=lxc_profile] \\
[nic_opts=nic_opts] [start=(True|False)] \\
[seed=(True|False)] [install=(True|False)] \\
[config=minion_config] [approve_key=(True|False) \\
[clone_from=original] [autostart=True] \\
[priv_key=/path_or_content] [pub_key=/path_or_content] \\
[bridge=lxcbr0] [gateway=10.0.3.1] \\
[dnsservers[dns1,dns2]] \\
[users=[foo]] [password='secret'] \\
[password_encrypted=(True|False)]
'''
ret = {'name': name,
'changes': {}}
profile = get_container_profile(copy.deepcopy(profile))
if not network_profile:
network_profile = profile.get('network_profile')
if not network_profile:
network_profile = DEFAULT_NIC
# Changes is a pointer to changes_dict['init']. This method is used so that
# we can have a list of changes as they are made, providing an ordered list
# of things that were changed.
changes_dict = {'init': []}
changes = changes_dict.get('init')
if users is None:
users = []
dusers = ['root']
for user in dusers:
if user not in users:
users.append(user)
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, _marker)
profile_match = profile.pop(key, default)
# let kwarg overrides be the preferred choice
if kw_overrides_match is _marker:
return profile_match
return kw_overrides_match
path = select('path')
bpath = get_root_path(path)
state_pre = state(name, path=path)
tvg = select('vgname')
vgname = tvg if tvg else __salt__['config.get']('lxc.vgname')
start_ = select('start', True)
autostart = select('autostart', autostart)
seed = select('seed', True)
install = select('install', True)
seed_cmd = select('seed_cmd')
salt_config = _get_salt_config(config, **kwargs)
approve_key = select('approve_key', True)
clone_from = select('clone_from')
# If using a volume group then set up to make snapshot cow clones
if vgname and not clone_from:
try:
kwargs['vgname'] = vgname
clone_from = _get_base(profile=profile, **kwargs)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = exc.strerror
if changes:
ret['changes'] = changes_dict
return ret
if not kwargs.get('snapshot') is False:
kwargs['snapshot'] = True
does_exist = exists(name, path=path)
to_reboot = False
remove_seed_marker = False
if does_exist:
pass
elif clone_from:
remove_seed_marker = True
try:
clone(name, clone_from, profile=profile, **kwargs)
changes.append({'create': 'Container cloned'})
except (SaltInvocationError, CommandExecutionError) as exc:
if 'already exists' in exc.strerror:
changes.append({'create': 'Container already exists'})
else:
ret['result'] = False
ret['comment'] = exc.strerror
if changes:
ret['changes'] = changes_dict
return ret
cfg = _LXCConfig(name=name, network_profile=network_profile,
nic_opts=nic_opts, bridge=bridge, path=path,
gateway=gateway, autostart=autostart,
cpuset=cpuset, cpushare=cpushare, memory=memory)
old_chunks = read_conf(cfg.path, out_format='commented')
cfg.write()
chunks = read_conf(cfg.path, out_format='commented')
if old_chunks != chunks:
to_reboot = True
else:
remove_seed_marker = True
cfg = _LXCConfig(network_profile=network_profile,
nic_opts=nic_opts, cpuset=cpuset, path=path,
bridge=bridge, gateway=gateway,
autostart=autostart,
cpushare=cpushare, memory=memory)
with cfg.tempfile() as cfile:
try:
create(name, config=cfile.name, profile=profile, **kwargs)
changes.append({'create': 'Container created'})
except (SaltInvocationError, CommandExecutionError) as exc:
if 'already exists' in exc.strerror:
changes.append({'create': 'Container already exists'})
else:
ret['comment'] = exc.strerror
if changes:
ret['changes'] = changes_dict
return ret
cpath = os.path.join(bpath, name, 'config')
old_chunks = []
if os.path.exists(cpath):
old_chunks = read_conf(cpath, out_format='commented')
new_cfg = _config_list(conf_tuples=old_chunks,
cpu=cpu,
network_profile=network_profile,
nic_opts=nic_opts, bridge=bridge,
cpuset=cpuset, cpushare=cpushare,
memory=memory)
if new_cfg:
edit_conf(cpath, out_format='commented', lxc_config=new_cfg)
chunks = read_conf(cpath, out_format='commented')
if old_chunks != chunks:
to_reboot = True
# last time to be sure any of our property is correctly applied
cfg = _LXCConfig(name=name, network_profile=network_profile,
nic_opts=nic_opts, bridge=bridge, path=path,
gateway=gateway, autostart=autostart,
cpuset=cpuset, cpushare=cpushare, memory=memory)
old_chunks = []
if os.path.exists(cfg.path):
old_chunks = read_conf(cfg.path, out_format='commented')
cfg.write()
chunks = read_conf(cfg.path, out_format='commented')
if old_chunks != chunks:
changes.append({'config': 'Container configuration updated'})
to_reboot = True
if to_reboot:
try:
stop(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
if changes:
ret['changes'] = changes_dict
return ret
if not does_exist or (does_exist and state(name, path=path) != 'running'):
try:
start(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
if changes:
ret['changes'] = changes_dict
return ret
if remove_seed_marker:
run(name,
'rm -f \'{0}\''.format(SEED_MARKER),
path=path,
chroot_fallback=False,
python_shell=False)
# set the default user/password, only the first time
if ret.get('result', True) and password:
gid = '/.lxc.initial_pass'
gids = [gid,
'/lxc.initial_pass',
'/.lxc.{0}.initial_pass'.format(name)]
if not any(retcode(name,
'test -e "{0}"'.format(x),
chroot_fallback=True,
path=path,
ignore_retcode=True) == 0
for x in gids):
# think to touch the default user generated by default templates
# which has a really unsecure passwords...
# root is defined as a member earlier in the code
for default_user in ['ubuntu']:
if (
default_user not in users and
retcode(name,
'id {0}'.format(default_user),
python_shell=False,
path=path,
chroot_fallback=True,
ignore_retcode=True) == 0
):
users.append(default_user)
for user in users:
try:
cret = set_password(name,
users=[user],
path=path,
password=password,
encrypted=password_encrypted)
except (SaltInvocationError, CommandExecutionError) as exc:
msg = '{0}: Failed to set password'.format(
user) + exc.strerror
# only hardfail in unrecoverable situation:
# root cannot be setted up
if user == 'root':
ret['comment'] = msg
ret['result'] = False
else:
log.debug(msg)
if ret.get('result', True):
changes.append({'password': 'Password(s) updated'})
if retcode(name,
('sh -c \'touch "{0}"; test -e "{0}"\''
.format(gid)),
path=path,
chroot_fallback=True,
ignore_retcode=True) != 0:
ret['comment'] = 'Failed to set password marker'
changes[-1]['password'] += '. ' + ret['comment'] + '.'
ret['result'] = False
# set dns servers if any, only the first time
if ret.get('result', True) and dnsservers:
# retro compatibility, test also old markers
gid = '/.lxc.initial_dns'
gids = [gid,
'/lxc.initial_dns',
'/lxc.{0}.initial_dns'.format(name)]
if not any(retcode(name,
'test -e "{0}"'.format(x),
chroot_fallback=True,
path=path,
ignore_retcode=True) == 0
for x in gids):
try:
set_dns(name,
path=path,
dnsservers=dnsservers,
searchdomains=searchdomains)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Failed to set DNS: ' + exc.strerror
ret['result'] = False
else:
changes.append({'dns': 'DNS updated'})
if retcode(name,
('sh -c \'touch "{0}"; test -e "{0}"\''
.format(gid)),
chroot_fallback=True,
path=path,
ignore_retcode=True) != 0:
ret['comment'] = 'Failed to set DNS marker'
changes[-1]['dns'] += '. ' + ret['comment'] + '.'
ret['result'] = False
# retro compatibility, test also old markers
if remove_seed_marker:
run(name,
'rm -f \'{0}\''.format(SEED_MARKER),
path=path,
python_shell=False)
gid = '/.lxc.initial_seed'
gids = [gid, '/lxc.initial_seed']
if (
any(retcode(name,
'test -e {0}'.format(x),
path=path,
chroot_fallback=True,
ignore_retcode=True) == 0
for x in gids) or not ret.get('result', True)
):
pass
elif seed or seed_cmd:
if seed:
try:
result = bootstrap(
name, config=salt_config, path=path,
approve_key=approve_key,
pub_key=pub_key, priv_key=priv_key,
install=install,
force_install=force_install,
unconditional_install=unconditional_install,
bootstrap_delay=bootstrap_delay,
bootstrap_url=bootstrap_url,
bootstrap_shell=bootstrap_shell,
bootstrap_args=bootstrap_args)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Bootstrap failed: ' + exc.strerror
ret['result'] = False
else:
if not result:
ret['comment'] = ('Bootstrap failed, see minion log for '
'more information')
ret['result'] = False
else:
changes.append(
{'bootstrap': 'Container successfully bootstrapped'}
)
elif seed_cmd:
try:
result = __salt__[seed_cmd](info(name, path=path)['rootfs'],
name,
salt_config)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = ('Bootstrap via seed_cmd \'{0}\' failed: {1}'
.format(seed_cmd, exc.strerror))
ret['result'] = False
else:
if not result:
ret['comment'] = ('Bootstrap via seed_cmd \'{0}\' failed, '
'see minion log for more information '
.format(seed_cmd))
ret['result'] = False
else:
changes.append(
{'bootstrap': 'Container successfully bootstrapped '
'using seed_cmd \'{0}\''
.format(seed_cmd)}
)
if ret.get('result', True) and not start_:
try:
stop(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
ret['result'] = False
state_post = state(name, path=path)
if state_pre != state_post:
changes.append({'state': {'old': state_pre, 'new': state_post}})
if ret.get('result', True):
ret['comment'] = ('Container \'{0}\' successfully initialized'
.format(name))
ret['result'] = True
if changes:
ret['changes'] = changes_dict
return ret
def cloud_init(name, vm_=None, **kwargs):
'''
Thin wrapper to lxc.init to be used from the saltcloud lxc driver
name
Name of the container
may be None and then guessed from saltcloud mapping
`vm_`
saltcloud mapping defaults for the vm
CLI Example:
.. code-block:: bash
salt '*' lxc.cloud_init foo
'''
init_interface = cloud_init_interface(name, vm_, **kwargs)
name = init_interface.pop('name', name)
return init(name, **init_interface)
def images(dist=None):
'''
.. versionadded:: 2015.5.0
List the available images for LXC's ``download`` template.
dist : None
Filter results to a single Linux distribution
CLI Examples:
.. code-block:: bash
salt myminion lxc.images
salt myminion lxc.images dist=centos
'''
out = __salt__['cmd.run_stdout'](
'lxc-create -n __imgcheck -t download -- --list',
ignore_retcode=True
)
if 'DIST' not in out:
raise CommandExecutionError(
'Unable to run the \'download\' template script. Is it installed?'
)
ret = {}
passed_header = False
for line in out.splitlines():
try:
distro, release, arch, variant, build_time = line.split()
except ValueError:
continue
if not passed_header:
if distro == 'DIST':
passed_header = True
continue
dist_list = ret.setdefault(distro, [])
dist_list.append({
'release': release,
'arch': arch,
'variant': variant,
'build_time': build_time,
})
if dist is not None:
return dict([(dist, ret.get(dist, []))])
return ret
def templates():
'''
.. versionadded:: 2015.5.0
List the available LXC template scripts installed on the minion
CLI Examples:
.. code-block:: bash
salt myminion lxc.templates
'''
try:
template_scripts = os.listdir('/usr/share/lxc/templates')
except OSError:
return []
else:
return [x[4:] for x in template_scripts if x.startswith('lxc-')]
def _after_ignition_network_profile(cmd,
ret,
name,
network_profile,
path,
nic_opts):
_clear_context()
if ret['retcode'] == 0 and exists(name, path=path):
if network_profile:
network_changes = apply_network_profile(name,
network_profile,
path=path,
nic_opts=nic_opts)
if network_changes:
log.info(
'Network changes from applying network profile \'%s\' '
'to newly-created container \'%s\':\n%s',
network_profile, name, network_changes
)
c_state = state(name, path=path)
return {'result': True,
'state': {'old': None, 'new': c_state}}
else:
if exists(name, path=path):
# destroy the container if it was partially created
cmd = 'lxc-destroy'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0}'.format(name)
__salt__['cmd.retcode'](cmd, python_shell=False)
raise CommandExecutionError(
'Container could not be created with cmd \'{0}\': {1}'
.format(cmd, ret['stderr'])
)
def create(name,
config=None,
profile=None,
network_profile=None,
nic_opts=None,
**kwargs):
'''
Create a new container.
name
Name of the container
config
The config file to use for the container. Defaults to system-wide
config (usually in /etc/lxc/lxc.conf).
profile
Profile to use in container creation (see
:mod:`lxc.get_container_profile
<salt.modules.lxc.get_container_profile>`). Values in a profile will be
overridden by the **Container Creation Arguments** listed below.
network_profile
Network profile to use for container
.. versionadded:: 2015.5.0
**Container Creation Arguments**
template
The template to use. For example, ``ubuntu`` or ``fedora``.
For a full list of available templates, check out
the :mod:`lxc.templates <salt.modules.lxc.templates>` function.
Conflicts with the ``image`` argument.
.. note::
The ``download`` template requires the following three parameters
to be defined in ``options``:
* **dist** - The name of the distribution
* **release** - Release name/version
* **arch** - Architecture of the container
The available images can be listed using the :mod:`lxc.images
<salt.modules.lxc.images>` function.
options
Template-specific options to pass to the lxc-create command. These
correspond to the long options (ones beginning with two dashes) that
the template script accepts. For example:
.. code-block:: bash
options='{"dist": "centos", "release": "6", "arch": "amd64"}'
For available template options, refer to the lxc template scripts
which are ususally located under ``/usr/share/lxc/templates``,
or run ``lxc-create -t <template> -h``.
image
A tar archive to use as the rootfs for the container. Conflicts with
the ``template`` argument.
backing
The type of storage to use. Set to ``lvm`` to use an LVM group.
Defaults to filesystem within /var/lib/lxc.
fstype
Filesystem type to use on LVM logical volume
size : 1G
Size of the volume to create. Only applicable if ``backing=lvm``.
vgname : lxc
Name of the LVM volume group in which to create the volume for this
container. Only applicable if ``backing=lvm``.
lvname
Name of the LVM logical volume in which to create the volume for this
container. Only applicable if ``backing=lvm``.
thinpool
Name of a pool volume that will be used for thin-provisioning this
container. Only applicable if ``backing=lvm``.
nic_opts
give extra opts overriding network profile values
path
parent path for the container creation (default: /var/lib/lxc)
zfsroot
Name of the ZFS root in which to create the volume for this container.
Only applicable if ``backing=zfs``. (default: tank/lxc)
.. versionadded:: 2015.8.0
'''
# Required params for 'download' template
download_template_deps = ('dist', 'release', 'arch')
cmd = 'lxc-create -n {0}'.format(name)
profile = get_container_profile(copy.deepcopy(profile))
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, None)
profile_match = profile.pop(key, default)
# Return the profile match if the the kwarg match was None, as the
# lxc.present state will pass these kwargs set to None by default.
if kw_overrides_match is None:
return profile_match
return kw_overrides_match
path = select('path')
if exists(name, path=path):
raise CommandExecutionError(
'Container \'{0}\' already exists'.format(name)
)
tvg = select('vgname')
vgname = tvg if tvg else __salt__['config.get']('lxc.vgname')
# The 'template' and 'image' params conflict
template = select('template')
image = select('image')
if template and image:
raise SaltInvocationError(
'Only one of \'template\' and \'image\' is permitted'
)
elif not any((template, image, profile)):
raise SaltInvocationError(
'At least one of \'template\', \'image\', and \'profile\' is '
'required'
)
options = select('options') or {}
backing = select('backing')
if vgname and not backing:
backing = 'lvm'
lvname = select('lvname')
thinpool = select('thinpool')
fstype = select('fstype')
size = select('size', '1G')
zfsroot = select('zfsroot')
if backing in ('dir', 'overlayfs', 'btrfs', 'zfs'):
fstype = None
size = None
# some backends won't support some parameters
if backing in ('aufs', 'dir', 'overlayfs', 'btrfs'):
lvname = vgname = thinpool = None
if image:
img_tar = __salt__['cp.cache_file'](image)
template = os.path.join(
os.path.dirname(salt.__file__),
'templates',
'lxc',
'salt_tarball')
options['imgtar'] = img_tar
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
if not os.path.exists(path):
os.makedirs(path)
if config:
cmd += ' -f {0}'.format(config)
if template:
cmd += ' -t {0}'.format(template)
if backing:
backing = backing.lower()
cmd += ' -B {0}'.format(backing)
if backing in ('zfs',):
if zfsroot:
cmd += ' --zfsroot {0}'.format(zfsroot)
if backing in ('lvm',):
if lvname:
cmd += ' --lvname {0}'.format(lvname)
if vgname:
cmd += ' --vgname {0}'.format(vgname)
if thinpool:
cmd += ' --thinpool {0}'.format(thinpool)
if backing not in ('dir', 'overlayfs'):
if fstype:
cmd += ' --fstype {0}'.format(fstype)
if size:
cmd += ' --fssize {0}'.format(size)
if options:
if template == 'download':
missing_deps = [x for x in download_template_deps
if x not in options]
if missing_deps:
raise SaltInvocationError(
'Missing params in \'options\' dict: {0}'
.format(', '.join(missing_deps))
)
cmd += ' --'
for key, val in six.iteritems(options):
cmd += ' --{0} {1}'.format(key, val)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
# please do not merge extra conflicting stuff
# inside those two line (ret =, return)
return _after_ignition_network_profile(cmd,
ret,
name,
network_profile,
path,
nic_opts)
def clone(name,
orig,
profile=None,
network_profile=None,
nic_opts=None,
**kwargs):
'''
Create a new container as a clone of another container
name
Name of the container
orig
Name of the original container to be cloned
profile
Profile to use in container cloning (see
:mod:`lxc.get_container_profile
<salt.modules.lxc.get_container_profile>`). Values in a profile will be
overridden by the **Container Cloning Arguments** listed below.
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
**Container Cloning Arguments**
snapshot
Use Copy On Write snapshots (LVM)
size : 1G
Size of the volume to create. Only applicable if ``backing=lvm``.
backing
The type of storage to use. Set to ``lvm`` to use an LVM group.
Defaults to filesystem within /var/lib/lxc.
network_profile
Network profile to use for container
.. versionadded:: 2015.8.0
nic_opts
give extra opts overriding network profile values
.. versionadded:: 2015.8.0
CLI Examples:
.. code-block:: bash
salt '*' lxc.clone myclone orig=orig_container
salt '*' lxc.clone myclone orig=orig_container snapshot=True
'''
profile = get_container_profile(copy.deepcopy(profile))
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, None)
profile_match = profile.pop(key, default)
# let kwarg overrides be the preferred choice
if kw_overrides_match is None:
return profile_match
return kw_overrides_match
path = select('path')
if exists(name, path=path):
raise CommandExecutionError(
'Container \'{0}\' already exists'.format(name)
)
_ensure_exists(orig, path=path)
if state(orig, path=path) != 'stopped':
raise CommandExecutionError(
'Container \'{0}\' must be stopped to be cloned'.format(orig)
)
backing = select('backing')
snapshot = select('snapshot')
if backing in ('dir',):
snapshot = False
if not snapshot:
snapshot = ''
else:
snapshot = '-s'
size = select('size', '1G')
if backing in ('dir', 'overlayfs', 'btrfs'):
size = None
# LXC commands and options changed in 2.0 - CF issue #34086 for details
if _LooseVersion(version()) >= _LooseVersion('2.0'):
# https://linuxcontainers.org/lxc/manpages//man1/lxc-copy.1.html
cmd = 'lxc-copy'
cmd += ' {0} -n {1} -N {2}'.format(snapshot, orig, name)
else:
# https://linuxcontainers.org/lxc/manpages//man1/lxc-clone.1.html
cmd = 'lxc-clone'
cmd += ' {0} -o {1} -n {2}'.format(snapshot, orig, name)
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
if not os.path.exists(path):
os.makedirs(path)
if backing:
backing = backing.lower()
cmd += ' -B {0}'.format(backing)
if backing not in ('dir', 'overlayfs'):
if size:
cmd += ' -L {0}'.format(size)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
# please do not merge extra conflicting stuff
# inside those two line (ret =, return)
return _after_ignition_network_profile(cmd,
ret,
name,
network_profile,
path,
nic_opts)
def ls_(active=None, cache=True, path=None):
'''
Return a list of the containers available on the minion
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
active
If ``True``, return only active (i.e. running) containers
.. versionadded:: 2015.5.0
CLI Example:
.. code-block:: bash
salt '*' lxc.ls
salt '*' lxc.ls active=True
'''
contextvar = 'lxc.ls{0}'.format(path)
if active:
contextvar += '.active'
if cache and (contextvar in __context__):
return __context__[contextvar]
else:
ret = []
cmd = 'lxc-ls'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
if active:
cmd += ' --active'
output = __salt__['cmd.run_stdout'](cmd, python_shell=False)
for line in output.splitlines():
ret.extend(line.split())
__context__[contextvar] = ret
return ret
def list_(extra=False, limit=None, path=None):
'''
List containers classified by state
extra
Also get per-container specific info. This will change the return data.
Instead of returning a list of containers, a dictionary of containers
and each container's output from :mod:`lxc.info
<salt.modules.lxc.info>`.
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
limit
Return output matching a specific state (**frozen**, **running**, or
**stopped**).
.. versionadded:: 2015.5.0
CLI Examples:
.. code-block:: bash
salt '*' lxc.list
salt '*' lxc.list extra=True
salt '*' lxc.list limit=running
'''
ctnrs = ls_(path=path)
if extra:
stopped = {}
frozen = {}
running = {}
else:
stopped = []
frozen = []
running = []
ret = {'running': running,
'stopped': stopped,
'frozen': frozen}
for container in ctnrs:
cmd = 'lxc-info'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0}'.format(container)
c_info = __salt__['cmd.run'](
cmd,
python_shell=False,
output_loglevel='debug'
)
c_state = None
for line in c_info.splitlines():
stat = line.split(':')
if stat[0] in ('State', 'state'):
c_state = stat[1].strip()
break
if not c_state or (limit is not None and c_state.lower() != limit):
continue
if extra:
infos = info(container, path=path)
method = 'update'
value = {container: infos}
else:
method = 'append'
value = container
if c_state == 'STOPPED':
getattr(stopped, method)(value)
continue
if c_state == 'FROZEN':
getattr(frozen, method)(value)
continue
if c_state == 'RUNNING':
getattr(running, method)(value)
continue
if limit is not None:
return ret.get(limit, {} if extra else [])
return ret
def _change_state(cmd,
name,
expected,
stdin=_marker,
stdout=_marker,
stderr=_marker,
with_communicate=_marker,
use_vt=_marker,
path=None):
pre = state(name, path=path)
if pre == expected:
return {'result': True,
'state': {'old': expected, 'new': expected},
'comment': 'Container \'{0}\' already {1}'
.format(name, expected)}
if cmd == 'lxc-destroy':
# Kill the container first
scmd = 'lxc-stop'
if path:
scmd += ' -P {0}'.format(pipes.quote(path))
scmd += ' -k -n {0}'.format(name)
__salt__['cmd.run'](scmd,
python_shell=False)
if path and ' -P ' not in cmd:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0}'.format(name)
# certain lxc commands need to be taken with care (lxc-start)
# as te command itself mess with double forks; we must not
# communicate with it, but just wait for the exit status
pkwargs = {'python_shell': False,
'redirect_stderr': True,
'with_communicate': with_communicate,
'use_vt': use_vt,
'stdin': stdin,
'stdout': stdout}
for i in [a for a in pkwargs]:
val = pkwargs[i]
if val is _marker:
pkwargs.pop(i, None)
_cmdout = __salt__['cmd.run_all'](cmd, **pkwargs)
if _cmdout['retcode'] != 0:
raise CommandExecutionError(
'Error changing state for container \'{0}\' using command '
'\'{1}\': {2}'.format(name, cmd, _cmdout['stdout'])
)
if expected is not None:
# some commands do not wait, so we will
rcmd = 'lxc-wait'
if path:
rcmd += ' -P {0}'.format(pipes.quote(path))
rcmd += ' -n {0} -s {1}'.format(name, expected.upper())
__salt__['cmd.run'](rcmd, python_shell=False, timeout=30)
_clear_context()
post = state(name, path=path)
ret = {'result': post == expected,
'state': {'old': pre, 'new': post}}
return ret
def _ensure_exists(name, path=None):
'''
Raise an exception if the container does not exist
'''
if not exists(name, path=path):
raise CommandExecutionError(
'Container \'{0}\' does not exist'.format(name)
)
def _ensure_running(name, no_start=False, path=None):
'''
If the container is not currently running, start it. This function returns
the state that the container was in before changing
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
'''
_ensure_exists(name, path=path)
pre = state(name, path=path)
if pre == 'running':
# This will be a no-op but running the function will give us a pretty
# return dict.
return start(name, path=path)
elif pre == 'stopped':
if no_start:
raise CommandExecutionError(
'Container \'{0}\' is not running'.format(name)
)
return start(name, path=path)
elif pre == 'frozen':
if no_start:
raise CommandExecutionError(
'Container \'{0}\' is not running'.format(name)
)
return unfreeze(name, path=path)
def restart(name, path=None, lxc_config=None, force=False):
'''
.. versionadded:: 2015.5.0
Restart the named container. If the container was not running, the
container will merely be started.
name
The name of the container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
lxc_config
path to a lxc config file
config file will be guessed from container name otherwise
.. versionadded:: 2015.8.0
force : False
If ``True``, the container will be force-stopped instead of gracefully
shut down
CLI Example:
.. code-block:: bash
salt myminion lxc.restart name
'''
_ensure_exists(name, path=path)
orig_state = state(name, path=path)
if orig_state != 'stopped':
stop(name, kill=force, path=path)
ret = start(name, path=path, lxc_config=lxc_config)
ret['state']['old'] = orig_state
if orig_state != 'stopped':
ret['restarted'] = True
return ret
def start(name, **kwargs):
'''
Start the named container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
lxc_config
path to a lxc config file
config file will be guessed from container name otherwise
.. versionadded:: 2015.8.0
use_vt
run the command through VT
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.start name
'''
path = kwargs.get('path', None)
cpath = get_root_path(path)
lxc_config = kwargs.get('lxc_config', None)
cmd = 'lxc-start'
if not lxc_config:
lxc_config = os.path.join(cpath, name, 'config')
# we try to start, even without config, if global opts are there
if os.path.exists(lxc_config):
cmd += ' -f {0}'.format(pipes.quote(lxc_config))
cmd += ' -d'
_ensure_exists(name, path=path)
if state(name, path=path) == 'frozen':
raise CommandExecutionError(
'Container \'{0}\' is frozen, use lxc.unfreeze'.format(name)
)
# lxc-start daemonize itself violently, we must not communicate with it
use_vt = kwargs.get('use_vt', None)
with_communicate = kwargs.get('with_communicate', False)
return _change_state(cmd, name, 'running',
stdout=None,
stderr=None,
stdin=None,
with_communicate=with_communicate,
path=path,
use_vt=use_vt)
def stop(name, kill=False, path=None, use_vt=None):
'''
Stop the named container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
kill: False
Do not wait for the container to stop, kill all tasks in the container.
Older LXC versions will stop containers like this irrespective of this
argument.
.. versionchanged:: 2015.5.0
Default value changed to ``False``
use_vt
run the command through VT
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.stop name
'''
_ensure_exists(name, path=path)
orig_state = state(name, path=path)
if orig_state == 'frozen' and not kill:
# Gracefully stopping a frozen container is slower than unfreezing and
# then stopping it (at least in my testing), so if we're not
# force-stopping the container, unfreeze it first.
unfreeze(name, path=path)
cmd = 'lxc-stop'
if kill:
cmd += ' -k'
ret = _change_state(cmd, name, 'stopped', use_vt=use_vt, path=path)
ret['state']['old'] = orig_state
return ret
def freeze(name, **kwargs):
'''
Freeze the named container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
start : False
If ``True`` and the container is stopped, the container will be started
before attempting to freeze.
.. versionadded:: 2015.5.0
use_vt
run the command through VT
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.freeze name
'''
use_vt = kwargs.get('use_vt', None)
path = kwargs.get('path', None)
_ensure_exists(name, path=path)
orig_state = state(name, path=path)
start_ = kwargs.get('start', False)
if orig_state == 'stopped':
if not start_:
raise CommandExecutionError(
'Container \'{0}\' is stopped'.format(name)
)
start(name, path=path)
cmd = 'lxc-freeze'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
ret = _change_state(cmd, name, 'frozen', use_vt=use_vt, path=path)
if orig_state == 'stopped' and start_:
ret['state']['old'] = orig_state
ret['started'] = True
ret['state']['new'] = state(name, path=path)
return ret
def unfreeze(name, path=None, use_vt=None):
'''
Unfreeze the named container.
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
use_vt
run the command through VT
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.unfreeze name
'''
_ensure_exists(name, path=path)
if state(name, path=path) == 'stopped':
raise CommandExecutionError(
'Container \'{0}\' is stopped'.format(name)
)
cmd = 'lxc-unfreeze'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
return _change_state(cmd, name, 'running', path=path, use_vt=use_vt)
def destroy(name, stop=False, path=None):
'''
Destroy the named container.
.. warning::
Destroys all data associated with the container.
path
path to the container parent directory (default: /var/lib/lxc)
.. versionadded:: 2015.8.0
stop : False
If ``True``, the container will be destroyed even if it is
running/frozen.
.. versionchanged:: 2015.5.0
Default value changed to ``False``. This more closely matches the
behavior of ``lxc-destroy(1)``, and also makes it less likely that
an accidental command will destroy a running container that was
being used for important things.
CLI Examples:
.. code-block:: bash
salt '*' lxc.destroy foo
salt '*' lxc.destroy foo stop=True
'''
_ensure_exists(name, path=path)
if not stop and state(name, path=path) != 'stopped':
raise CommandExecutionError(
'Container \'{0}\' is not stopped'.format(name)
)
return _change_state('lxc-destroy', name, None, path=path)
# Compatibility between LXC and nspawn
remove = salt.utils.functools.alias_function(destroy, 'remove')
def exists(name, path=None):
'''
Returns whether the named container exists.
path
path to the container parent directory (default: /var/lib/lxc)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.exists name
'''
_exists = name in ls_(path=path)
# container may be just created but we did cached earlier the
# lxc-ls results
if not _exists:
_exists = name in ls_(cache=False, path=path)
return _exists
def state(name, path=None):
'''
Returns the state of a container.
path
path to the container parent directory (default: /var/lib/lxc)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.state name
'''
# Don't use _ensure_exists() here, it will mess with _change_state()
cachekey = 'lxc.state.{0}{1}'.format(name, path)
try:
return __context__[cachekey]
except KeyError:
if not exists(name, path=path):
__context__[cachekey] = None
else:
cmd = 'lxc-info'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0}'.format(name)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
if ret['retcode'] != 0:
_clear_context()
raise CommandExecutionError(
'Unable to get state of container \'{0}\''.format(name)
)
c_infos = ret['stdout'].splitlines()
c_state = None
for c_info in c_infos:
stat = c_info.split(':')
if stat[0].lower() == 'state':
c_state = stat[1].strip().lower()
break
__context__[cachekey] = c_state
return __context__[cachekey]
def get_parameter(name, parameter, path=None):
'''
Returns the value of a cgroup parameter for a container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.get_parameter container_name memory.limit_in_bytes
'''
_ensure_exists(name, path=path)
cmd = 'lxc-cgroup'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0} {1}'.format(name, parameter)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
if ret['retcode'] != 0:
raise CommandExecutionError(
'Unable to retrieve value for \'{0}\''.format(parameter)
)
return ret['stdout'].strip()
def set_parameter(name, parameter, value, path=None):
'''
Set the value of a cgroup parameter for a container.
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.set_parameter name parameter value
'''
if not exists(name, path=path):
return None
cmd = 'lxc-cgroup'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0} {1} {2}'.format(name, parameter, value)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
if ret['retcode'] != 0:
return False
else:
return True
def info(name, path=None):
'''
Returns information about a container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.info name
'''
cachekey = 'lxc.info.{0}{1}'.format(name, path)
try:
return __context__[cachekey]
except KeyError:
_ensure_exists(name, path=path)
cpath = get_root_path(path)
try:
conf_file = os.path.join(cpath, name, 'config')
except AttributeError:
conf_file = os.path.join(cpath, six.text_type(name), 'config')
if not os.path.isfile(conf_file):
raise CommandExecutionError(
'LXC config file {0} does not exist'.format(conf_file)
)
ret = {}
config = []
with salt.utils.files.fopen(conf_file) as fp_:
for line in fp_:
line = salt.utils.stringutils.to_unicode(line)
comps = [x.strip() for x in
line.split('#', 1)[0].strip().split('=', 1)]
if len(comps) == 2:
config.append(tuple(comps))
ifaces = []
current = None
for key, val in config:
if key == 'lxc.network.type':
current = {'type': val}
ifaces.append(current)
elif not current:
continue
elif key.startswith('lxc.network.'):
current[key.replace('lxc.network.', '', 1)] = val
if ifaces:
ret['nics'] = ifaces
ret['rootfs'] = next(
(x[1] for x in config if x[0] == 'lxc.rootfs'),
None
)
ret['state'] = state(name, path=path)
ret['ips'] = []
ret['public_ips'] = []
ret['private_ips'] = []
ret['public_ipv4_ips'] = []
ret['public_ipv6_ips'] = []
ret['private_ipv4_ips'] = []
ret['private_ipv6_ips'] = []
ret['ipv4_ips'] = []
ret['ipv6_ips'] = []
ret['size'] = None
ret['config'] = conf_file
if ret['state'] == 'running':
try:
limit = int(get_parameter(name, 'memory.limit_in_bytes'))
except (CommandExecutionError, TypeError, ValueError):
limit = 0
try:
usage = int(get_parameter(name, 'memory.usage_in_bytes'))
except (CommandExecutionError, TypeError, ValueError):
usage = 0
free = limit - usage
ret['memory_limit'] = limit
ret['memory_free'] = free
size = run_stdout(name, 'df /', path=path, python_shell=False)
# The size is the 2nd column of the last line
ret['size'] = size.splitlines()[-1].split()[1]
# First try iproute2
ip_cmd = run_all(
name, 'ip link show', path=path, python_shell=False)
if ip_cmd['retcode'] == 0:
ip_data = ip_cmd['stdout']
ip_cmd = run_all(
name, 'ip addr show', path=path, python_shell=False)
ip_data += '\n' + ip_cmd['stdout']
ip_data = salt.utils.network._interfaces_ip(ip_data)
else:
# That didn't work, try ifconfig
ip_cmd = run_all(
name, 'ifconfig', path=path, python_shell=False)
if ip_cmd['retcode'] == 0:
ip_data = \
salt.utils.network._interfaces_ifconfig(
ip_cmd['stdout'])
else:
# Neither was successful, give up
log.warning(
'Unable to run ip or ifconfig in container \'%s\'', name
)
ip_data = {}
ret['ipv4_ips'] = salt.utils.network.ip_addrs(
include_loopback=True,
interface_data=ip_data
)
ret['ipv6_ips'] = salt.utils.network.ip_addrs6(
include_loopback=True,
interface_data=ip_data
)
ret['ips'] = ret['ipv4_ips'] + ret['ipv6_ips']
for address in ret['ipv4_ips']:
if address == '127.0.0.1':
ret['private_ips'].append(address)
ret['private_ipv4_ips'].append(address)
elif salt.utils.cloud.is_public_ip(address):
ret['public_ips'].append(address)
ret['public_ipv4_ips'].append(address)
else:
ret['private_ips'].append(address)
ret['private_ipv4_ips'].append(address)
for address in ret['ipv6_ips']:
if address == '::1' or address.startswith('fe80'):
ret['private_ips'].append(address)
ret['private_ipv6_ips'].append(address)
else:
ret['public_ips'].append(address)
ret['public_ipv6_ips'].append(address)
for key in [x for x in ret if x == 'ips' or x.endswith('ips')]:
ret[key].sort(key=_ip_sort)
__context__[cachekey] = ret
return __context__[cachekey]
def set_password(name, users, password, encrypted=True, path=None):
'''
.. versionchanged:: 2015.5.0
Function renamed from ``set_pass`` to ``set_password``. Additionally,
this function now supports (and defaults to using) a password hash
instead of a plaintext password.
Set the password of one or more system users inside containers
users
Comma-separated list (or python list) of users to change password
password
Password to set for the specified user(s)
encrypted : True
If true, ``password`` must be a password hash. Set to ``False`` to set
a plaintext password (not recommended).
.. versionadded:: 2015.5.0
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.set_pass container-name root '$6$uJ2uAyLU$KoI67t8As/0fXtJOPcHKGXmUpcoYUcVR2K6x93walnShTCQvjRwq25yIkiCBOqgbfdKQSFnAo28/ek6716vEV1'
salt '*' lxc.set_pass container-name root foo encrypted=False
'''
def _bad_user_input():
raise SaltInvocationError('Invalid input for \'users\' parameter')
if not isinstance(users, list):
try:
users = users.split(',')
except AttributeError:
_bad_user_input()
if not users:
_bad_user_input()
failed_users = []
for user in users:
result = retcode(name,
'chpasswd{0}'.format(' -e' if encrypted else ''),
stdin=':'.join((user, password)),
python_shell=False,
path=path,
chroot_fallback=True,
output_loglevel='quiet')
if result != 0:
failed_users.append(user)
if failed_users:
raise CommandExecutionError(
'Password change failed for the following user(s): {0}'
.format(', '.join(failed_users))
)
return True
set_pass = salt.utils.functools.alias_function(set_password, 'set_pass')
def update_lxc_conf(name, lxc_conf, lxc_conf_unset, path=None):
'''
Edit LXC configuration options
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.update_lxc_conf ubuntu \\
lxc_conf="[{'network.ipv4.ip':'10.0.3.5'}]" \\
lxc_conf_unset="['lxc.utsname']"
'''
_ensure_exists(name, path=path)
cpath = get_root_path(path)
lxc_conf_p = os.path.join(cpath, name, 'config')
if not os.path.exists(lxc_conf_p):
raise SaltInvocationError(
'Configuration file {0} does not exist'.format(lxc_conf_p)
)
changes = {'edited': [], 'added': [], 'removed': []}
ret = {'changes': changes, 'result': True, 'comment': ''}
# do not use salt.utils.files.fopen !
with salt.utils.files.fopen(lxc_conf_p, 'r') as fic:
filtered_lxc_conf = []
for row in lxc_conf:
if not row:
continue
for conf in row:
filtered_lxc_conf.append((conf.strip(),
row[conf].strip()))
ret['comment'] = 'lxc.conf is up to date'
lines = []
orig_config = salt.utils.stringutils.to_unicode(fic.read())
for line in orig_config.splitlines():
if line.startswith('#') or not line.strip():
lines.append([line, ''])
else:
line = line.split('=')
index = line.pop(0)
val = (index.strip(), '='.join(line).strip())
if val not in lines:
lines.append(val)
for key, item in filtered_lxc_conf:
matched = False
for idx, line in enumerate(lines[:]):
if line[0] == key:
matched = True
lines[idx] = (key, item)
if '='.join(line[1:]).strip() != item.strip():
changes['edited'].append(
({line[0]: line[1:]}, {key: item}))
break
if not matched:
if (key, item) not in lines:
lines.append((key, item))
changes['added'].append({key: item})
dest_lxc_conf = []
# filter unset
if lxc_conf_unset:
for line in lines:
for opt in lxc_conf_unset:
if (
not line[0].startswith(opt) and
line not in dest_lxc_conf
):
dest_lxc_conf.append(line)
else:
changes['removed'].append(opt)
else:
dest_lxc_conf = lines
conf = ''
for key, val in dest_lxc_conf:
if not val:
conf += '{0}\n'.format(key)
else:
conf += '{0} = {1}\n'.format(key.strip(), val.strip())
conf_changed = conf != orig_config
chrono = datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S')
if conf_changed:
# DO NOT USE salt.utils.files.fopen here, i got (kiorky)
# problems with lxc configs which were wiped !
with salt.utils.files.fopen('{0}.{1}'.format(lxc_conf_p, chrono), 'w') as wfic:
wfic.write(salt.utils.stringutils.to_str(conf))
with salt.utils.files.fopen(lxc_conf_p, 'w') as wfic:
wfic.write(salt.utils.stringutils.to_str(conf))
ret['comment'] = 'Updated'
ret['result'] = True
if not any(changes[x] for x in changes):
# Ensure an empty changes dict if nothing was modified
ret['changes'] = {}
return ret
def set_dns(name, dnsservers=None, searchdomains=None, path=None):
'''
.. versionchanged:: 2015.5.0
The ``dnsservers`` and ``searchdomains`` parameters can now be passed
as a comma-separated list.
Update /etc/resolv.confo
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.set_dns ubuntu "['8.8.8.8', '4.4.4.4']"
'''
if dnsservers is None:
dnsservers = ['8.8.8.8', '4.4.4.4']
elif not isinstance(dnsservers, list):
try:
dnsservers = dnsservers.split(',')
except AttributeError:
raise SaltInvocationError(
'Invalid input for \'dnsservers\' parameter'
)
if searchdomains is None:
searchdomains = []
elif not isinstance(searchdomains, list):
try:
searchdomains = searchdomains.split(',')
except AttributeError:
raise SaltInvocationError(
'Invalid input for \'searchdomains\' parameter'
)
dns = ['nameserver {0}'.format(x) for x in dnsservers]
dns.extend(['search {0}'.format(x) for x in searchdomains])
dns = '\n'.join(dns) + '\n'
# we may be using resolvconf in the container
# We need to handle that case with care:
# - we create the resolv.conf runtime directory (the
# linked directory) as anyway it will be shadowed when the real
# runned tmpfs mountpoint will be mounted.
# ( /etc/resolv.conf -> ../run/resolvconf/resolv.conf)
# Indeed, it can save us in any other case (running, eg, in a
# bare chroot when repairing or preparing the container for
# operation.
# - We also teach resolvconf to use the aforementioned dns.
# - We finally also set /etc/resolv.conf in all cases
rstr = __salt__['test.random_hash']()
# no tmp here, apparmor won't let us execute !
script = '/sbin/{0}_dns.sh'.format(rstr)
DNS_SCRIPT = "\n".join([
# 'set -x',
'#!/usr/bin/env bash',
'if [ -h /etc/resolv.conf ];then',
' if [ "x$(readlink /etc/resolv.conf)"'
' = "x../run/resolvconf/resolv.conf" ];then',
' if [ ! -d /run/resolvconf/ ];then',
' mkdir -p /run/resolvconf',
' fi',
' cat > /etc/resolvconf/resolv.conf.d/head <<EOF',
dns,
'EOF',
'',
' fi',
'fi',
'cat > /etc/resolv.conf <<EOF',
dns,
'EOF',
''])
result = run_all(
name, 'tee {0}'.format(script), path=path,
stdin=DNS_SCRIPT, python_shell=True)
if result['retcode'] == 0:
result = run_all(
name, 'sh -c "chmod +x {0};{0}"'.format(script),
path=path, python_shell=True)
# blindly delete the setter file
run_all(name,
'sh -c \'if [ -f "{0}" ];then rm -f "{0}";fi\''.format(script),
path=path, python_shell=True)
if result['retcode'] != 0:
error = ('Unable to write to /etc/resolv.conf in container \'{0}\''
.format(name))
if result['stderr']:
error += ': {0}'.format(result['stderr'])
raise CommandExecutionError(error)
return True
def running_systemd(name, cache=True, path=None):
'''
Determine if systemD is running
path
path to the container parent
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.running_systemd ubuntu
'''
k = 'lxc.systemd.test.{0}{1}'.format(name, path)
ret = __context__.get(k, None)
if ret is None or not cache:
rstr = __salt__['test.random_hash']()
# no tmp here, apparmor won't let us execute !
script = '/sbin/{0}_testsystemd.sh'.format(rstr)
# ubuntu already had since trusty some bits of systemd but was
# still using upstart ...
# we need to be a bit more careful that just testing that systemd
# is present
_script = textwrap.dedent(
'''\
#!/usr/bin/env bash
set -x
if ! command -v systemctl 1>/dev/null 2>/dev/null;then exit 2;fi
for i in \\
/run/systemd/journal/dev-log\\
/run/systemd/journal/flushed\\
/run/systemd/journal/kernel-seqnum\\
/run/systemd/journal/socket\\
/run/systemd/journal/stdout\\
/var/run/systemd/journal/dev-log\\
/var/run/systemd/journal/flushed\\
/var/run/systemd/journal/kernel-seqnum\\
/var/run/systemd/journal/socket\\
/var/run/systemd/journal/stdout\\
;do\\
if test -e ${i};then exit 0;fi
done
if test -d /var/systemd/system;then exit 0;fi
exit 2
''')
result = run_all(
name, 'tee {0}'.format(script), path=path,
stdin=_script, python_shell=True)
if result['retcode'] == 0:
result = run_all(name,
'sh -c "chmod +x {0};{0}"'''.format(script),
path=path,
python_shell=True)
else:
raise CommandExecutionError(
'lxc {0} failed to copy initd tester'.format(name))
run_all(name,
'sh -c \'if [ -f "{0}" ];then rm -f "{0}";fi\''
''.format(script),
path=path,
ignore_retcode=True,
python_shell=True)
if result['retcode'] != 0:
error = ('Unable to determine if the container \'{0}\''
' was running systemd, assmuming it is not.'
''.format(name))
if result['stderr']:
error += ': {0}'.format(result['stderr'])
# only cache result if we got a known exit code
if result['retcode'] in (0, 2):
__context__[k] = ret = not result['retcode']
return ret
def systemd_running_state(name, path=None):
'''
Get the operational state of a systemd based container
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.systemd_running_state ubuntu
'''
try:
ret = run_all(name,
'systemctl is-system-running',
path=path,
ignore_retcode=True)['stdout']
except CommandExecutionError:
ret = ''
return ret
def test_sd_started_state(name, path=None):
'''
Test if a systemd container is fully started
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.test_sd_started_state ubuntu
'''
qstate = systemd_running_state(name, path=path)
if qstate in ('initializing', 'starting'):
return False
elif qstate == '':
return None
else:
return True
def test_bare_started_state(name, path=None):
'''
Test if a non systemd container is fully started
For now, it consists only to test if the container is attachable
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.test_bare_started_state ubuntu
'''
try:
ret = run_all(
name, 'ls', path=path, ignore_retcode=True
)['retcode'] == 0
except (CommandExecutionError,):
ret = None
return ret
def wait_started(name, path=None, timeout=300):
'''
Check that the system has fully inited
This is actually very important for systemD based containers
see https://github.com/saltstack/salt/issues/23847
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.wait_started ubuntu
'''
if not exists(name, path=path):
raise CommandExecutionError(
'Container {0} does does exists'.format(name))
if not state(name, path=path) == 'running':
raise CommandExecutionError(
'Container {0} is not running'.format(name))
ret = False
if running_systemd(name, path=path):
test_started = test_sd_started_state
logger = log.error
else:
test_started = test_bare_started_state
logger = log.debug
now = time.time()
expire = now + timeout
now = time.time()
started = test_started(name, path=path)
while time.time() < expire and not started:
time.sleep(0.3)
started = test_started(name, path=path)
if started is None:
logger(
'Assuming %s is started, although we failed to detect that'
' is fully started correctly', name)
ret = True
else:
ret = started
return ret
def _needs_install(name, path=None):
ret = 0
has_minion = retcode(name,
'which salt-minion',
path=path,
ignore_retcode=True)
# we assume that installing is when no minion is running
# but testing the executable presence is not enougth for custom
# installs where the bootstrap can do much more than installing
# the bare salt binaries.
if has_minion:
processes = run_stdout(name, "ps aux", path=path)
if 'salt-minion' not in processes:
ret = 1
else:
retcode(name, 'salt-call --local service.stop salt-minion')
else:
ret = 1
return ret
def bootstrap(name,
config=None,
approve_key=True,
install=True,
pub_key=None,
priv_key=None,
bootstrap_url=None,
force_install=False,
unconditional_install=False,
path=None,
bootstrap_delay=None,
bootstrap_args=None,
bootstrap_shell=None):
'''
Install and configure salt in a container.
config
Minion configuration options. By default, the ``master`` option is set
to the target host's master.
approve_key
Request a pre-approval of the generated minion key. Requires
that the salt-master be configured to either auto-accept all keys or
expect a signing request from the target host. Default: ``True``
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
pub_key
Explicit public key to pressed the minion with (optional).
This can be either a filepath or a string representing the key
priv_key
Explicit private key to pressed the minion with (optional).
This can be either a filepath or a string representing the key
bootstrap_delay
Delay in seconds between end of container creation and bootstrapping.
Useful when waiting for container to obtain a DHCP lease.
.. versionadded:: 2015.5.0
bootstrap_url
url, content or filepath to the salt bootstrap script
bootstrap_args
salt bootstrap script arguments
bootstrap_shell
shell to execute the script into
install
Whether to attempt a full installation of salt-minion if needed.
force_install
Force installation even if salt-minion is detected,
this is the way to run vendor bootstrap scripts even
if a salt minion is already present in the container
unconditional_install
Run the script even if the container seems seeded
CLI Examples:
.. code-block:: bash
salt 'minion' lxc.bootstrap container_name [config=config_data] \\
[approve_key=(True|False)] [install=(True|False)]
'''
wait_started(name, path=path)
if bootstrap_delay is not None:
try:
log.info('LXC %s: bootstrap_delay: %s', name, bootstrap_delay)
time.sleep(bootstrap_delay)
except TypeError:
# Bad input, but assume since a value was passed that
# a delay was desired, and sleep for 5 seconds
time.sleep(5)
c_info = info(name, path=path)
if not c_info:
return None
# default set here as we cannot set them
# in def as it can come from a chain of procedures.
if bootstrap_args:
# custom bootstrap args can be totally customized, and user could
# have inserted the placeholder for the config directory.
# For example, some salt bootstrap script do not use at all -c
if '{0}' not in bootstrap_args:
bootstrap_args += ' -c {0}'
else:
bootstrap_args = '-c {0}'
if not bootstrap_shell:
bootstrap_shell = 'sh'
orig_state = _ensure_running(name, path=path)
if not orig_state:
return orig_state
if not force_install:
needs_install = _needs_install(name, path=path)
else:
needs_install = True
seeded = retcode(name,
'test -e \'{0}\''.format(SEED_MARKER),
path=path,
chroot_fallback=True,
ignore_retcode=True) == 0
tmp = tempfile.mkdtemp()
if seeded and not unconditional_install:
ret = True
else:
ret = False
cfg_files = __salt__['seed.mkconfig'](
config, tmp=tmp, id_=name, approve_key=approve_key,
pub_key=pub_key, priv_key=priv_key)
if needs_install or force_install or unconditional_install:
if install:
rstr = __salt__['test.random_hash']()
configdir = '/var/tmp/.c_{0}'.format(rstr)
cmd = 'install -m 0700 -d {0}'.format(configdir)
if run_all(
name, cmd, path=path, python_shell=False
)['retcode'] != 0:
log.error('tmpdir %s creation failed %s', configdir, cmd)
return False
bs_ = __salt__['config.gather_bootstrap_script'](
bootstrap=bootstrap_url)
script = '/sbin/{0}_bootstrap.sh'.format(rstr)
copy_to(name, bs_, script, path=path)
result = run_all(name,
'sh -c "chmod +x {0}"'.format(script),
path=path,
python_shell=True)
copy_to(name, cfg_files['config'],
os.path.join(configdir, 'minion'),
path=path)
copy_to(name, cfg_files['privkey'],
os.path.join(configdir, 'minion.pem'),
path=path)
copy_to(name, cfg_files['pubkey'],
os.path.join(configdir, 'minion.pub'),
path=path)
bootstrap_args = bootstrap_args.format(configdir)
cmd = ('{0} {2} {1}'
.format(bootstrap_shell,
bootstrap_args.replace("'", "''"),
script))
# log ASAP the forged bootstrap command which can be wrapped
# out of the output in case of unexpected problem
log.info('Running %s in LXC container \'%s\'', cmd, name)
ret = retcode(name, cmd, output_loglevel='info',
path=path, use_vt=True) == 0
run_all(name,
'sh -c \'if [ -f "{0}" ];then rm -f "{0}";fi\''
''.format(script),
path=path,
ignore_retcode=True,
python_shell=True)
else:
ret = False
else:
minion_config = salt.config.minion_config(cfg_files['config'])
pki_dir = minion_config['pki_dir']
copy_to(name,
cfg_files['config'],
'/etc/salt/minion',
path=path)
copy_to(name,
cfg_files['privkey'],
os.path.join(pki_dir, 'minion.pem'),
path=path)
copy_to(name,
cfg_files['pubkey'],
os.path.join(pki_dir, 'minion.pub'),
path=path)
run(name,
'salt-call --local service.enable salt-minion',
path=path,
python_shell=False)
ret = True
shutil.rmtree(tmp)
if orig_state == 'stopped':
stop(name, path=path)
elif orig_state == 'frozen':
freeze(name, path=path)
# mark seeded upon successful install
if ret:
run(name,
'touch \'{0}\''.format(SEED_MARKER),
path=path,
python_shell=False)
return ret
def attachable(name, path=None):
'''
Return True if the named container can be attached to via the lxc-attach
command
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt 'minion' lxc.attachable ubuntu
'''
cachekey = 'lxc.attachable{0}{1}'.format(name, path)
try:
return __context__[cachekey]
except KeyError:
_ensure_exists(name, path=path)
# Can't use run() here because it uses attachable() and would
# endlessly recurse, resulting in a traceback
log.debug('Checking if LXC container %s is attachable', name)
cmd = 'lxc-attach'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' --clear-env -n {0} -- /usr/bin/env'.format(name)
result = __salt__['cmd.retcode'](cmd,
python_shell=False,
output_loglevel='quiet',
ignore_retcode=True) == 0
__context__[cachekey] = result
return __context__[cachekey]
def _run(name,
cmd,
output=None,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=None,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
Common logic for lxc.run functions
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
'''
orig_state = state(name, path=path)
try:
if attachable(name, path=path):
ret = __salt__['container_resource.run'](
name,
cmd,
path=path,
container_type=__virtualname__,
exec_driver=EXEC_DRIVER,
output=output,
no_start=no_start,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
ignore_retcode=ignore_retcode,
use_vt=use_vt,
keep_env=keep_env)
else:
if not chroot_fallback:
raise CommandExecutionError(
'{0} is not attachable.'.format(name))
rootfs = info(name, path=path).get('rootfs')
# Set context var to make cmd.run_chroot run cmd.run instead of
# cmd.run_all.
__context__['cmd.run_chroot.func'] = __salt__['cmd.run']
ret = __salt__['cmd.run_chroot'](rootfs,
cmd,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
ignore_retcode=ignore_retcode)
except Exception:
raise
finally:
# Make sure we honor preserve_state, even if there was an exception
new_state = state(name, path=path)
if preserve_state:
if orig_state == 'stopped' and new_state != 'stopped':
stop(name, path=path)
elif orig_state == 'frozen' and new_state != 'frozen':
freeze(name, start=True, path=path)
if output in (None, 'all'):
return ret
else:
return ret[output]
def run(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.8.0
Run :mod:`cmd.run <salt.modules.cmdmod.run>` within a container
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed in stderr if the command being run
does not exist. If no output is returned using this function, try using
:mod:`lxc.run_stderr <salt.modules.lxc.run_stderr>` or
:mod:`lxc.run_all <salt.modules.lxc.run_all>`.
name
Name of the container in which to run the command
cmd
Command to run
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console. Assumes
``output=all``.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
CLI Example:
.. code-block:: bash
salt myminion lxc.run mycontainer 'ifconfig -a'
'''
return _run(name,
cmd,
path=path,
output=None,
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def run_stdout(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.5.0
Run :mod:`cmd.run_stdout <salt.modules.cmdmod.run_stdout>` within a container
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed in stderr if the command being run
does not exist. If no output is returned using this function, try using
:mod:`lxc.run_stderr <salt.modules.lxc.run_stderr>` or
:mod:`lxc.run_all <salt.modules.lxc.run_all>`.
name
Name of the container in which to run the command
cmd
Command to run
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console
``output=all``.
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
CLI Example:
.. code-block:: bash
salt myminion lxc.run_stdout mycontainer 'ifconfig -a'
'''
return _run(name,
cmd,
path=path,
output='stdout',
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def run_stderr(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.5.0
Run :mod:`cmd.run_stderr <salt.modules.cmdmod.run_stderr>` within a container
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed if the command being run does not
exist.
name
Name of the container in which to run the command
cmd
Command to run
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console
``output=all``.
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
CLI Example:
.. code-block:: bash
salt myminion lxc.run_stderr mycontainer 'ip addr show'
'''
return _run(name,
cmd,
path=path,
output='stderr',
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def retcode(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.5.0
Run :mod:`cmd.retcode <salt.modules.cmdmod.retcode>` within a container
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed in stderr if the command being run
does not exist. If the retcode is nonzero and not what was expected,
try using :mod:`lxc.run_stderr <salt.modules.lxc.run_stderr>`
or :mod:`lxc.run_all <salt.modules.lxc.run_all>`.
name
Name of the container in which to run the command
cmd
Command to run
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console
``output=all``.
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
CLI Example:
.. code-block:: bash
salt myminion lxc.retcode mycontainer 'ip addr show'
'''
return _run(name,
cmd,
output='retcode',
path=path,
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def run_all(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.5.0
Run :mod:`cmd.run_all <salt.modules.cmdmod.run_all>` within a container
.. note::
While the command is run within the container, it is initiated from the
host. Therefore, the PID in the return dict is from the host, not from
the container.
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed in stderr if the command being run
does not exist.
name
Name of the container in which to run the command
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
cmd
Command to run
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console
``output=all``.
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
CLI Example:
.. code-block:: bash
salt myminion lxc.run_all mycontainer 'ip addr show'
'''
return _run(name,
cmd,
output='all',
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
path=path,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def _get_md5(name, path):
'''
Get the MD5 checksum of a file from a container
'''
output = run_stdout(name, 'md5sum "{0}"'.format(path),
chroot_fallback=True,
ignore_retcode=True)
try:
return output.split()[0]
except IndexError:
# Destination file does not exist or could not be accessed
return None
def copy_to(name, source, dest, overwrite=False, makedirs=False, path=None):
'''
.. versionchanged:: 2015.8.0
Function renamed from ``lxc.cp`` to ``lxc.copy_to`` for consistency
with other container types. ``lxc.cp`` will continue to work, however.
For versions 2015.2.x and earlier, use ``lxc.cp``.
Copy a file or directory from the host into a container
name
Container name
source
File to be copied to the container
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
dest
Destination on the container. Must be an absolute path.
.. versionchanged:: 2015.5.0
If the destination is a directory, the file will be copied into
that directory.
overwrite : False
Unless this option is set to ``True``, then if a file exists at the
location specified by the ``dest`` argument, an error will be raised.
.. versionadded:: 2015.8.0
makedirs : False
Create the parent directory on the container if it does not already
exist.
.. versionadded:: 2015.5.0
CLI Example:
.. code-block:: bash
salt 'minion' lxc.copy_to /tmp/foo /root/foo
salt 'minion' lxc.cp /tmp/foo /root/foo
'''
_ensure_running(name, no_start=True, path=path)
return __salt__['container_resource.copy_to'](
name,
source,
dest,
container_type=__virtualname__,
path=path,
exec_driver=EXEC_DRIVER,
overwrite=overwrite,
makedirs=makedirs)
cp = salt.utils.functools.alias_function(copy_to, 'cp')
def read_conf(conf_file, out_format='simple'):
'''
Read in an LXC configuration file. By default returns a simple, unsorted
dict, but can also return a more detailed structure including blank lines
and comments.
out_format:
set to 'simple' if you need the old and unsupported behavior.
This won't support the multiple lxc values (eg: multiple network nics)
CLI Examples:
.. code-block:: bash
salt 'minion' lxc.read_conf /etc/lxc/mycontainer.conf
salt 'minion' lxc.read_conf /etc/lxc/mycontainer.conf out_format=commented
'''
ret_commented = []
ret_simple = {}
with salt.utils.files.fopen(conf_file, 'r') as fp_:
for line in salt.utils.data.decode(fp_.readlines()):
if '=' not in line:
ret_commented.append(line)
continue
comps = line.split('=')
value = '='.join(comps[1:]).strip()
comment = None
if value.strip().startswith('#'):
vcomps = value.strip().split('#')
value = vcomps[1].strip()
comment = '#'.join(vcomps[1:]).strip()
ret_commented.append({comps[0].strip(): {
'value': value,
'comment': comment,
}})
else:
ret_commented.append({comps[0].strip(): value})
ret_simple[comps[0].strip()] = value
if out_format == 'simple':
return ret_simple
return ret_commented
def write_conf(conf_file, conf):
'''
Write out an LXC configuration file
This is normally only used internally. The format of the data structure
must match that which is returned from ``lxc.read_conf()``, with
``out_format`` set to ``commented``.
An example might look like:
.. code-block:: python
[
{'lxc.utsname': '$CONTAINER_NAME'},
'# This is a commented line\\n',
'\\n',
{'lxc.mount': '$CONTAINER_FSTAB'},
{'lxc.rootfs': {'comment': 'This is another test',
'value': 'This is another test'}},
'\\n',
{'lxc.network.type': 'veth'},
{'lxc.network.flags': 'up'},
{'lxc.network.link': 'br0'},
{'lxc.network.mac': '$CONTAINER_MACADDR'},
{'lxc.network.ipv4': '$CONTAINER_IPADDR'},
{'lxc.network.name': '$CONTAINER_DEVICENAME'},
]
CLI Example:
.. code-block:: bash
salt 'minion' lxc.write_conf /etc/lxc/mycontainer.conf \\
out_format=commented
'''
if not isinstance(conf, list):
raise SaltInvocationError('Configuration must be passed as a list')
# construct the content prior to write to the file
# to avoid half written configs
content = ''
for line in conf:
if isinstance(line, (six.text_type, six.string_types)):
content += line
elif isinstance(line, dict):
for key in list(line.keys()):
out_line = None
if isinstance(
line[key],
(six.text_type, six.string_types, six.integer_types, float)
):
out_line = ' = '.join((key, "{0}".format(line[key])))
elif isinstance(line[key], dict):
out_line = ' = '.join((key, line[key]['value']))
if 'comment' in line[key]:
out_line = ' # '.join((out_line, line[key]['comment']))
if out_line:
content += out_line
content += '\n'
with salt.utils.files.fopen(conf_file, 'w') as fp_:
fp_.write(salt.utils.stringutils.to_str(content))
return {}
def edit_conf(conf_file,
out_format='simple',
read_only=False,
lxc_config=None,
**kwargs):
'''
Edit an LXC configuration file. If a setting is already present inside the
file, its value will be replaced. If it does not exist, it will be appended
to the end of the file. Comments and blank lines will be kept in-tact if
they already exist in the file.
out_format:
Set to simple if you need backward compatibility (multiple items for a
simple key is not supported)
read_only:
return only the edited configuration without applying it
to the underlying lxc configuration file
lxc_config:
List of dict containning lxc configuration items
For network configuration, you also need to add the device it belongs
to, otherwise it will default to eth0.
Also, any change to a network parameter will result in the whole
network reconfiguration to avoid mismatchs, be aware of that !
After the file is edited, its contents will be returned. By default, it
will be returned in ``simple`` format, meaning an unordered dict (which
may not represent the actual file order). Passing in an ``out_format`` of
``commented`` will return a data structure which accurately represents the
order and content of the file.
CLI Example:
.. code-block:: bash
salt 'minion' lxc.edit_conf /etc/lxc/mycontainer.conf \\
out_format=commented lxc.network.type=veth
salt 'minion' lxc.edit_conf /etc/lxc/mycontainer.conf \\
out_format=commented \\
lxc_config="[{'lxc.network.name': 'eth0', \\
'lxc.network.ipv4': '1.2.3.4'},
{'lxc.network.name': 'eth2', \\
'lxc.network.ipv4': '1.2.3.5',\\
'lxc.network.gateway': '1.2.3.1'}]"
'''
data = []
try:
conf = read_conf(conf_file, out_format=out_format)
except Exception:
conf = []
if not lxc_config:
lxc_config = []
lxc_config = copy.deepcopy(lxc_config)
# search if we want to access net config
# in that case, we will replace all the net configuration
net_config = []
for lxc_kws in lxc_config + [kwargs]:
net_params = {}
for kwarg in [a for a in lxc_kws]:
if kwarg.startswith('__'):
continue
if kwarg.startswith('lxc.network.'):
net_params[kwarg] = lxc_kws[kwarg]
lxc_kws.pop(kwarg, None)
if net_params:
net_config.append(net_params)
nic_opts = salt.utils.odict.OrderedDict()
for params in net_config:
dev = params.get('lxc.network.name', DEFAULT_NIC)
dev_opts = nic_opts.setdefault(dev, salt.utils.odict.OrderedDict())
for param in params:
opt = param.replace('lxc.network.', '')
opt = {'hwaddr': 'mac'}.get(opt, opt)
dev_opts[opt] = params[param]
net_changes = []
if nic_opts:
net_changes = _config_list(conf, only_net=True,
**{'network_profile': DEFAULT_NIC,
'nic_opts': nic_opts})
if net_changes:
lxc_config.extend(net_changes)
for line in conf:
if not isinstance(line, dict):
data.append(line)
continue
else:
for key in list(line.keys()):
val = line[key]
if net_changes and key.startswith('lxc.network.'):
continue
found = False
for ix in range(len(lxc_config)):
kw = lxc_config[ix]
if key in kw:
found = True
data.append({key: kw[key]})
del kw[key]
if not found:
data.append({key: val})
for lxc_kws in lxc_config:
for kwarg in lxc_kws:
data.append({kwarg: lxc_kws[kwarg]})
if read_only:
return data
write_conf(conf_file, data)
return read_conf(conf_file, out_format)
def reboot(name, path=None):
'''
Reboot a container.
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Examples:
.. code-block:: bash
salt 'minion' lxc.reboot myvm
'''
ret = {'result': True,
'changes': {},
'comment': '{0} rebooted'.format(name)}
does_exist = exists(name, path=path)
if does_exist and (state(name, path=path) == 'running'):
try:
stop(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
ret['result'] = False
return ret
if does_exist and (state(name, path=path) != 'running'):
try:
start(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
ret['result'] = False
return ret
ret['changes'][name] = 'rebooted'
return ret
def reconfigure(name,
cpu=None,
cpuset=None,
cpushare=None,
memory=None,
profile=None,
network_profile=None,
nic_opts=None,
bridge=None,
gateway=None,
autostart=None,
utsname=None,
rootfs=None,
path=None,
**kwargs):
'''
Reconfigure a container.
This only applies to a few property
name
Name of the container.
utsname
utsname of the container.
.. versionadded:: 2016.3.0
rootfs
rootfs of the container.
.. versionadded:: 2016.3.0
cpu
Select a random number of cpu cores and assign it to the cpuset, if the
cpuset option is set then this option will be ignored
cpuset
Explicitly define the cpus this container will be bound to
cpushare
cgroups cpu shares.
autostart
autostart container on reboot
memory
cgroups memory limit, in MB.
(0 for nolimit, None for old default 1024MB)
gateway
the ipv4 gateway to use
the default does nothing more than lxcutils does
bridge
the bridge to use
the default does nothing more than lxcutils does
nic
Network interfaces profile (defined in config or pillar).
nic_opts
Extra options for network interfaces, will override
``{"eth0": {"mac": "aa:bb:cc:dd:ee:ff", "ipv4": "10.1.1.1", "ipv6": "2001:db8::ff00:42:8329"}}``
or
``{"eth0": {"mac": "aa:bb:cc:dd:ee:ff", "ipv4": "10.1.1.1/24", "ipv6": "2001:db8::ff00:42:8329"}}``
path
path to the container parent
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt-call -lall mc_lxc_fork.reconfigure foobar nic_opts="{'eth1': {'mac': '00:16:3e:dd:ee:44'}}" memory=4
'''
changes = {}
cpath = get_root_path(path)
path = os.path.join(cpath, name, 'config')
ret = {'name': name,
'comment': 'config for {0} up to date'.format(name),
'result': True,
'changes': changes}
profile = get_container_profile(copy.deepcopy(profile))
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, _marker)
profile_match = profile.pop(key, default)
# let kwarg overrides be the preferred choice
if kw_overrides_match is _marker:
return profile_match
return kw_overrides_match
if nic_opts is not None and not network_profile:
network_profile = DEFAULT_NIC
if autostart is not None:
autostart = select('autostart', autostart)
else:
autostart = 'keep'
if not utsname:
utsname = select('utsname', utsname)
if os.path.exists(path):
old_chunks = read_conf(path, out_format='commented')
make_kw = salt.utils.odict.OrderedDict([
('utsname', utsname),
('rootfs', rootfs),
('autostart', autostart),
('cpu', cpu),
('gateway', gateway),
('cpuset', cpuset),
('cpushare', cpushare),
('network_profile', network_profile),
('nic_opts', nic_opts),
('bridge', bridge)])
# match 0 and none as memory = 0 in lxc config is harmful
if memory:
make_kw['memory'] = memory
kw = salt.utils.odict.OrderedDict()
for key, val in six.iteritems(make_kw):
if val is not None:
kw[key] = val
new_cfg = _config_list(conf_tuples=old_chunks, **kw)
if new_cfg:
edit_conf(path, out_format='commented', lxc_config=new_cfg)
chunks = read_conf(path, out_format='commented')
if old_chunks != chunks:
ret['comment'] = '{0} lxc config updated'.format(name)
if state(name, path=path) == 'running':
cret = reboot(name, path=path)
ret['result'] = cret['result']
return ret
def apply_network_profile(name, network_profile, nic_opts=None, path=None):
'''
.. versionadded:: 2015.5.0
Apply a network profile to a container
network_profile
profile name or default values (dict)
nic_opts
values to override in defaults (dict)
indexed by nic card names
path
path to the container parent
.. versionadded:: 2015.8.0
CLI Examples:
.. code-block:: bash
salt 'minion' lxc.apply_network_profile web1 centos
salt 'minion' lxc.apply_network_profile web1 centos \\
nic_opts="{'eth0': {'mac': 'xx:xx:xx:xx:xx:xx'}}"
salt 'minion' lxc.apply_network_profile web1 \\
"{'eth0': {'mac': 'xx:xx:xx:xx:xx:yy'}}"
nic_opts="{'eth0': {'mac': 'xx:xx:xx:xx:xx:xx'}}"
The special case to disable use of ethernet nics:
.. code-block:: bash
salt 'minion' lxc.apply_network_profile web1 centos \\
"{eth0: {disable: true}}"
'''
cpath = get_root_path(path)
cfgpath = os.path.join(cpath, name, 'config')
before = []
with salt.utils.files.fopen(cfgpath, 'r') as fp_:
for line in fp_:
before.append(line)
lxcconfig = _LXCConfig(name=name, path=path)
old_net = lxcconfig._filter_data('lxc.network')
network_params = {}
for param in _network_conf(
conf_tuples=old_net,
network_profile=network_profile, nic_opts=nic_opts
):
network_params.update(param)
if network_params:
edit_conf(cfgpath, out_format='commented', **network_params)
after = []
with salt.utils.files.fopen(cfgpath, 'r') as fp_:
for line in fp_:
after.append(line)
diff = ''
for line in difflib.unified_diff(before,
after,
fromfile='before',
tofile='after'):
diff += line
return diff
def get_pid(name, path=None):
'''
Returns a container pid.
Throw an exception if the container isn't running.
CLI Example:
.. code-block:: bash
salt '*' lxc.get_pid name
'''
if name not in list_(limit='running', path=path):
raise CommandExecutionError('Container {0} is not running, can\'t determine PID'.format(name))
info = __salt__['cmd.run']('lxc-info -n {0}'.format(name)).split("\n")
pid = [line.split(':')[1].strip() for line in info if re.match(r'\s*PID', line)][0]
return pid
def add_veth(name, interface_name, bridge=None, path=None):
'''
Add a veth to a container.
Note : this function doesn't update the container config, just add the interface at runtime
name
Name of the container
interface_name
Name of the interface in the container
bridge
Name of the bridge to attach the interface to (facultative)
CLI Examples:
.. code-block:: bash
salt '*' lxc.add_veth container_name eth1 br1
salt '*' lxc.add_veth container_name eth1
'''
# Get container init PID
pid = get_pid(name, path=path)
# Generate a ramdom string for veth and ensure that is isn't present on the system
while True:
random_veth = 'veth'+''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(6))
if random_veth not in __salt__['network.interfaces']().keys():
break
# Check prerequisites
if not __salt__['file.directory_exists']('/var/run/'):
raise CommandExecutionError('Directory /var/run required for lxc.add_veth doesn\'t exists')
if not __salt__['file.file_exists']('/proc/{0}/ns/net'.format(pid)):
raise CommandExecutionError('Proc file for container {0} network namespace doesn\'t exists'.format(name))
if not __salt__['file.directory_exists']('/var/run/netns'):
__salt__['file.mkdir']('/var/run/netns')
# Ensure that the symlink is up to date (change on container restart)
if __salt__['file.is_link']('/var/run/netns/{0}'.format(name)):
__salt__['file.remove']('/var/run/netns/{0}'.format(name))
__salt__['file.symlink']('/proc/{0}/ns/net'.format(pid), '/var/run/netns/{0}'.format(name))
# Ensure that interface doesn't exists
interface_exists = 0 == __salt__['cmd.retcode']('ip netns exec {netns} ip address list {interface}'.format(
netns=name,
interface=interface_name
))
if interface_exists:
raise CommandExecutionError('Interface {interface} already exists in {container}'.format(
interface=interface_name,
container=name
))
# Create veth and bring it up
if __salt__['cmd.retcode']('ip link add name {veth} type veth peer name {veth}_c'.format(veth=random_veth)) != 0:
raise CommandExecutionError('Error while creating the veth pair {0}'.format(random_veth))
if __salt__['cmd.retcode']('ip link set dev {0} up'.format(random_veth)) != 0:
raise CommandExecutionError('Error while bringing up host-side veth {0}'.format(random_veth))
# Attach it to the container
attached = 0 == __salt__['cmd.retcode']('ip link set dev {veth}_c netns {container} name {interface_name}'.format(
veth=random_veth,
container=name,
interface_name=interface_name
))
if not attached:
raise CommandExecutionError('Error while attaching the veth {veth} to container {container}'.format(
veth=random_veth,
container=name
))
__salt__['file.remove']('/var/run/netns/{0}'.format(name))
if bridge is not None:
__salt__['bridge.addif'](bridge, random_veth)
|
saltstack/salt
|
salt/modules/lxc.py
|
_get_veths
|
python
|
def _get_veths(net_data):
'''
Parse the nic setup inside lxc conf tuples back to a dictionary indexed by
network interface
'''
if isinstance(net_data, dict):
net_data = list(net_data.items())
nics = salt.utils.odict.OrderedDict()
current_nic = salt.utils.odict.OrderedDict()
no_names = True
for item in net_data:
if item and isinstance(item, dict):
item = list(item.items())[0]
# skip LXC configuration comment lines, and play only with tuples conf
elif isinstance(item, six.string_types):
# deal with reflection of commented lxc configs
sitem = item.strip()
if sitem.startswith('#') or not sitem:
continue
elif '=' in item:
item = tuple([a.strip() for a in item.split('=', 1)])
if item[0] == 'lxc.network.type':
current_nic = salt.utils.odict.OrderedDict()
if item[0] == 'lxc.network.name':
no_names = False
nics[item[1].strip()] = current_nic
current_nic[item[0].strip()] = item[1].strip()
# if not ethernet card name has been collected, assuming we collected
# data for eth0
if no_names and current_nic:
nics[DEFAULT_NIC] = current_nic
return nics
|
Parse the nic setup inside lxc conf tuples back to a dictionary indexed by
network interface
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/lxc.py#L954-L985
| null |
# -*- coding: utf-8 -*-
'''
Control Linux Containers via Salt
:depends: lxc package for distribution
lxc >= 1.0 (even beta alpha) is required
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import datetime
import copy
import string
import textwrap
import difflib
import logging
import tempfile
import os
import pipes
import time
import shutil
import re
import random
# Import salt libs
import salt.utils.args
import salt.utils.cloud
import salt.utils.data
import salt.utils.dictupdate
import salt.utils.files
import salt.utils.functools
import salt.utils.hashutils
import salt.utils.network
import salt.utils.odict
import salt.utils.path
import salt.utils.stringutils
from salt.exceptions import CommandExecutionError, SaltInvocationError
import salt.config
from salt.utils.versions import LooseVersion as _LooseVersion
# Import 3rd-party libs
from salt.ext import six
# pylint: disable=import-error,no-name-in-module
from salt.ext.six.moves import range # pylint: disable=redefined-builtin
from salt.ext.six.moves.urllib.parse import urlparse as _urlparse
# pylint: enable=import-error,no-name-in-module
# Set up logging
log = logging.getLogger(__name__)
# Don't shadow built-in's.
__func_alias__ = {
'list_': 'list',
'ls_': 'ls'
}
__virtualname__ = 'lxc'
DEFAULT_NIC = 'eth0'
DEFAULT_BR = 'br0'
SEED_MARKER = '/lxc.initial_seed'
EXEC_DRIVER = 'lxc-attach'
DEFAULT_PATH = '/var/lib/lxc'
_marker = object()
def __virtual__():
if salt.utils.path.which('lxc-start'):
return __virtualname__
# To speed up the whole thing, we decided to not use the
# subshell way and assume things are in place for lxc
# Discussion made by @kiorky and @thatch45
# lxc-version presence is not sufficient, in lxc1.0 alpha
# (precise backports), we have it and it is sufficient
# for the module to execute.
# elif salt.utils.path.which('lxc-version'):
# passed = False
# try:
# passed = subprocess.check_output(
# 'lxc-version').split(':')[1].strip() >= '1.0'
# except Exception:
# pass
# if not passed:
# log.warning('Support for lxc < 1.0 may be incomplete.')
# return 'lxc'
# return False
#
return (False, 'The lxc execution module cannot be loaded: the lxc-start binary is not in the path.')
def get_root_path(path):
'''
Get the configured lxc root for containers
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.get_root_path
'''
if not path:
path = __opts__.get('lxc.root_path', DEFAULT_PATH)
return path
def version():
'''
Return the actual lxc client version
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.version
'''
k = 'lxc.version'
if not __context__.get(k, None):
cversion = __salt__['cmd.run_all']('lxc-info --version')
if not cversion['retcode']:
ver = _LooseVersion(cversion['stdout'])
if ver < _LooseVersion('1.0'):
raise CommandExecutionError('LXC should be at least 1.0')
__context__[k] = "{0}".format(ver)
return __context__.get(k, None)
def _clear_context():
'''
Clear any lxc variables set in __context__
'''
for var in [x for x in __context__ if x.startswith('lxc.')]:
log.trace('Clearing __context__[\'%s\']', var)
__context__.pop(var, None)
def _ip_sort(ip):
'''Ip sorting'''
idx = '001'
if ip == '127.0.0.1':
idx = '200'
if ip == '::1':
idx = '201'
elif '::' in ip:
idx = '100'
return '{0}___{1}'.format(idx, ip)
def search_lxc_bridges():
'''
Search which bridges are potentially available as LXC bridges
CLI Example:
.. code-block:: bash
salt '*' lxc.search_lxc_bridges
'''
bridges = __context__.get('lxc.bridges', None)
# either match not yet called or no bridges were found
# to handle the case where lxc was not installed on the first
# call
if not bridges:
bridges = set()
running_bridges = set()
bridges.add(DEFAULT_BR)
try:
output = __salt__['cmd.run_all']('brctl show')
for line in output['stdout'].splitlines()[1:]:
if not line.startswith(' '):
running_bridges.add(line.split()[0].strip())
except (SaltInvocationError, CommandExecutionError):
pass
for ifc, ip in six.iteritems(
__grains__.get('ip_interfaces', {})
):
if ifc in running_bridges:
bridges.add(ifc)
elif os.path.exists(
'/sys/devices/virtual/net/{0}/bridge'.format(ifc)
):
bridges.add(ifc)
bridges = list(bridges)
# if we found interfaces that have lxc in their names
# we filter them as being the potential lxc bridges
# we also try to default on br0 on other cases
def sort_bridges(a):
pref = 'z'
if 'lxc' in a:
pref = 'a'
elif 'br0' == a:
pref = 'c'
return '{0}_{1}'.format(pref, a)
bridges.sort(key=sort_bridges)
__context__['lxc.bridges'] = bridges
return bridges
def search_lxc_bridge():
'''
Search the first bridge which is potentially available as LXC bridge
CLI Example:
.. code-block:: bash
salt '*' lxc.search_lxc_bridge
'''
return search_lxc_bridges()[0]
def _get_salt_config(config, **kwargs):
if not config:
config = kwargs.get('minion', {})
if not config:
config = {}
config.setdefault('master',
kwargs.get('master',
__opts__.get('master',
__opts__['id'])))
config.setdefault(
'master_port',
kwargs.get('master_port',
__opts__.get('master_port',
__opts__.get('ret_port',
__opts__.get('4506')))))
if not config['master']:
config = {}
return config
def cloud_init_interface(name, vm_=None, **kwargs):
'''
Interface between salt.cloud.lxc driver and lxc.init
``vm_`` is a mapping of vm opts in the salt.cloud format
as documented for the lxc driver.
This can be used either:
- from the salt cloud driver
- because you find the argument to give easier here
than using directly lxc.init
.. warning::
BE REALLY CAREFUL CHANGING DEFAULTS !!!
IT'S A RETRO COMPATIBLE INTERFACE WITH
THE SALT CLOUD DRIVER (ask kiorky).
name
name of the lxc container to create
pub_key
public key to preseed the minion with.
Can be the keycontent or a filepath
priv_key
private key to preseed the minion with.
Can be the keycontent or a filepath
path
path to the container parent directory (default: /var/lib/lxc)
.. versionadded:: 2015.8.0
profile
:ref:`profile <tutorial-lxc-profiles-container>` selection
network_profile
:ref:`network profile <tutorial-lxc-profiles-network>` selection
nic_opts
per interface settings compatibles with
network profile (ipv4/ipv6/link/gateway/mac/netmask)
eg::
- {'eth0': {'mac': '00:16:3e:01:29:40',
'gateway': None, (default)
'link': 'br0', (default)
'gateway': None, (default)
'netmask': '', (default)
'ip': '22.1.4.25'}}
unconditional_install
given to lxc.bootstrap (see relative doc)
force_install
given to lxc.bootstrap (see relative doc)
config
any extra argument for the salt minion config
dnsservers
list of DNS servers to set inside the container
dns_via_dhcp
do not set the dns servers, let them be set by the dhcp.
autostart
autostart the container at boot time
password
administrative password for the container
bootstrap_delay
delay before launching bootstrap script at Container init
.. warning::
Legacy but still supported options:
from_container
which container we use as a template
when running lxc.clone
image
which template do we use when we
are using lxc.create. This is the default
mode unless you specify something in from_container
backing
which backing store to use.
Values can be: overlayfs, dir(default), lvm, zfs, brtfs
fstype
When using a blockdevice level backing store,
which filesystem to use on
size
When using a blockdevice level backing store,
which size for the filesystem to use on
snapshot
Use snapshot when cloning the container source
vgname
if using LVM: vgname
lvname
if using LVM: lvname
thinpool:
if using LVM: thinpool
ip
ip for the primary nic
mac
mac address for the primary nic
netmask
netmask for the primary nic (24)
= ``vm_.get('netmask', '24')``
bridge
bridge for the primary nic (lxcbr0)
gateway
network gateway for the container
additional_ips
additional ips which will be wired on the main bridge (br0)
which is connected to internet.
Be aware that you may use manual virtual mac addresses
providen by you provider (online, ovh, etc).
This is a list of mappings {ip: '', mac: '', netmask:''}
Set gateway to None and an interface with a gateway
to escape from another interface that eth0.
eg::
- {'mac': '00:16:3e:01:29:40',
'gateway': None, (default)
'link': 'br0', (default)
'netmask': '', (default)
'ip': '22.1.4.25'}
users
administrative users for the container
default: [root] and [root, ubuntu] on ubuntu
default_nic
name of the first interface, you should
really not override this
CLI Example:
.. code-block:: bash
salt '*' lxc.cloud_init_interface foo
'''
if vm_ is None:
vm_ = {}
vm_ = copy.deepcopy(vm_)
vm_ = salt.utils.dictupdate.update(vm_, kwargs)
profile_data = copy.deepcopy(
vm_.get('lxc_profile',
vm_.get('profile', {})))
if not isinstance(profile_data, (dict, six.string_types)):
profile_data = {}
profile = get_container_profile(profile_data)
def _cloud_get(k, default=None):
return vm_.get(k, profile.get(k, default))
if name is None:
name = vm_['name']
# if we are on ubuntu, default to ubuntu
default_template = ''
if __grains__.get('os', '') in ['Ubuntu']:
default_template = 'ubuntu'
image = _cloud_get('image')
if not image:
_cloud_get('template', default_template)
backing = _cloud_get('backing', 'dir')
if image:
profile['template'] = image
vgname = _cloud_get('vgname', None)
if vgname:
profile['vgname'] = vgname
if backing:
profile['backing'] = backing
snapshot = _cloud_get('snapshot', False)
autostart = bool(_cloud_get('autostart', True))
dnsservers = _cloud_get('dnsservers', [])
dns_via_dhcp = _cloud_get('dns_via_dhcp', True)
password = _cloud_get('password', 's3cr3t')
password_encrypted = _cloud_get('password_encrypted', False)
fstype = _cloud_get('fstype', None)
lvname = _cloud_get('lvname', None)
thinpool = _cloud_get('thinpool', None)
pub_key = _cloud_get('pub_key', None)
priv_key = _cloud_get('priv_key', None)
size = _cloud_get('size', '20G')
script = _cloud_get('script', None)
script_args = _cloud_get('script_args', None)
users = _cloud_get('users', None)
if users is None:
users = []
ssh_username = _cloud_get('ssh_username', None)
if ssh_username and (ssh_username not in users):
users.append(ssh_username)
network_profile = _cloud_get('network_profile', None)
nic_opts = kwargs.get('nic_opts', None)
netmask = _cloud_get('netmask', '24')
path = _cloud_get('path', None)
bridge = _cloud_get('bridge', None)
gateway = _cloud_get('gateway', None)
unconditional_install = _cloud_get('unconditional_install', False)
force_install = _cloud_get('force_install', True)
config = _get_salt_config(_cloud_get('config', {}), **vm_)
default_nic = _cloud_get('default_nic', DEFAULT_NIC)
# do the interface with lxc.init mainly via nic_opts
# to avoid extra and confusing extra use cases.
if not isinstance(nic_opts, dict):
nic_opts = salt.utils.odict.OrderedDict()
# have a reference to the default nic
eth0 = nic_opts.setdefault(default_nic,
salt.utils.odict.OrderedDict())
# lxc config is based of ifc order, be sure to use odicts.
if not isinstance(nic_opts, salt.utils.odict.OrderedDict):
bnic_opts = salt.utils.odict.OrderedDict()
bnic_opts.update(nic_opts)
nic_opts = bnic_opts
gw = None
# legacy salt.cloud scheme for network interfaces settings support
bridge = _cloud_get('bridge', None)
ip = _cloud_get('ip', None)
mac = _cloud_get('mac', None)
if ip:
fullip = ip
if netmask:
fullip += '/{0}'.format(netmask)
eth0['ipv4'] = fullip
if mac is not None:
eth0['mac'] = mac
for ix, iopts in enumerate(_cloud_get("additional_ips", [])):
ifh = "eth{0}".format(ix+1)
ethx = nic_opts.setdefault(ifh, {})
if gw is None:
gw = iopts.get('gateway', ethx.get('gateway', None))
if gw:
# only one and only one default gateway is allowed !
eth0.pop('gateway', None)
gateway = None
# even if the gateway if on default "eth0" nic
# and we popped it will work
# as we reinject or set it here.
ethx['gateway'] = gw
elink = iopts.get('link', ethx.get('link', None))
if elink:
ethx['link'] = elink
# allow dhcp
aip = iopts.get('ipv4', iopts.get('ip', None))
if aip:
ethx['ipv4'] = aip
nm = iopts.get('netmask', '')
if nm:
ethx['ipv4'] += '/{0}'.format(nm)
for i in ('mac', 'hwaddr'):
if i in iopts:
ethx['mac'] = iopts[i]
break
if 'mac' not in ethx:
ethx['mac'] = salt.utils.network.gen_mac()
# last round checking for unique gateway and such
gw = None
for ethx in [a for a in nic_opts]:
ndata = nic_opts[ethx]
if gw:
ndata.pop('gateway', None)
if 'gateway' in ndata:
gw = ndata['gateway']
gateway = None
# only use a default bridge / gateway if we configured them
# via the legacy salt cloud configuration style.
# On other cases, we should rely on settings provided by the new
# salt lxc network profile style configuration which can
# be also be overridden or a per interface basis via the nic_opts dict.
if bridge:
eth0['link'] = bridge
if gateway:
eth0['gateway'] = gateway
#
lxc_init_interface = {}
lxc_init_interface['name'] = name
lxc_init_interface['config'] = config
lxc_init_interface['memory'] = _cloud_get('memory', 0) # nolimit
lxc_init_interface['pub_key'] = pub_key
lxc_init_interface['priv_key'] = priv_key
lxc_init_interface['nic_opts'] = nic_opts
for clone_from in ['clone_from', 'clone', 'from_container']:
# clone_from should default to None if not available
lxc_init_interface['clone_from'] = _cloud_get(clone_from, None)
if lxc_init_interface['clone_from'] is not None:
break
lxc_init_interface['profile'] = profile
lxc_init_interface['snapshot'] = snapshot
lxc_init_interface['dnsservers'] = dnsservers
lxc_init_interface['fstype'] = fstype
lxc_init_interface['path'] = path
lxc_init_interface['vgname'] = vgname
lxc_init_interface['size'] = size
lxc_init_interface['lvname'] = lvname
lxc_init_interface['thinpool'] = thinpool
lxc_init_interface['force_install'] = force_install
lxc_init_interface['unconditional_install'] = (
unconditional_install
)
lxc_init_interface['bootstrap_url'] = script
lxc_init_interface['bootstrap_args'] = script_args
lxc_init_interface['bootstrap_shell'] = _cloud_get('bootstrap_shell', 'sh')
lxc_init_interface['bootstrap_delay'] = _cloud_get('bootstrap_delay', None)
lxc_init_interface['autostart'] = autostart
lxc_init_interface['users'] = users
lxc_init_interface['password'] = password
lxc_init_interface['password_encrypted'] = password_encrypted
# be sure not to let objects goes inside the return
# as this return will be msgpacked for use in the runner !
lxc_init_interface['network_profile'] = network_profile
for i in ['cpu', 'cpuset', 'cpushare']:
if _cloud_get(i, None):
try:
lxc_init_interface[i] = vm_[i]
except KeyError:
lxc_init_interface[i] = profile[i]
return lxc_init_interface
def _get_profile(key, name, **kwargs):
if isinstance(name, dict):
profilename = name.pop('name', None)
return _get_profile(key, profilename, **name)
if name is None:
profile_match = {}
else:
profile_match = \
__salt__['config.get'](
'lxc.{1}:{0}'.format(name, key),
default=None,
merge='recurse'
)
if profile_match is None:
# No matching profile, make the profile an empty dict so that
# overrides can be applied below.
profile_match = {}
if not isinstance(profile_match, dict):
raise CommandExecutionError('lxc.{0} must be a dictionary'.format(key))
# Overlay the kwargs to override matched profile data
overrides = salt.utils.args.clean_kwargs(**copy.deepcopy(kwargs))
profile_match = salt.utils.dictupdate.update(
copy.deepcopy(profile_match),
overrides
)
return profile_match
def get_container_profile(name=None, **kwargs):
'''
.. versionadded:: 2015.5.0
Gather a pre-configured set of container configuration parameters. If no
arguments are passed, an empty profile is returned.
Profiles can be defined in the minion or master config files, or in pillar
or grains, and are loaded using :mod:`config.get
<salt.modules.config.get>`. The key under which LXC profiles must be
configured is ``lxc.container_profile.profile_name``. An example container
profile would be as follows:
.. code-block:: yaml
lxc.container_profile:
ubuntu:
template: ubuntu
backing: lvm
vgname: lxc
size: 1G
Parameters set in a profile can be overridden by passing additional
container creation arguments (such as the ones passed to :mod:`lxc.create
<salt.modules.lxc.create>`) to this function.
A profile can be defined either as the name of the profile, or a dictionary
of variable names and values. See the :ref:`LXC Tutorial
<tutorial-lxc-profiles>` for more information on how to use LXC profiles.
CLI Example:
.. code-block:: bash
salt-call lxc.get_container_profile centos
salt-call lxc.get_container_profile ubuntu template=ubuntu backing=overlayfs
'''
profile = _get_profile('container_profile', name, **kwargs)
return profile
def get_network_profile(name=None, **kwargs):
'''
.. versionadded:: 2015.5.0
Gather a pre-configured set of network configuration parameters. If no
arguments are passed, the following default profile is returned:
.. code-block:: python
{'eth0': {'link': 'br0', 'type': 'veth', 'flags': 'up'}}
Profiles can be defined in the minion or master config files, or in pillar
or grains, and are loaded using :mod:`config.get
<salt.modules.config.get>`. The key under which LXC profiles must be
configured is ``lxc.network_profile``. An example network profile would be
as follows:
.. code-block:: yaml
lxc.network_profile.centos:
eth0:
link: br0
type: veth
flags: up
To disable networking entirely:
.. code-block:: yaml
lxc.network_profile.centos:
eth0:
disable: true
Parameters set in a profile can be overridden by passing additional
arguments to this function.
A profile can be passed either as the name of the profile, or a
dictionary of variable names and values. See the :ref:`LXC Tutorial
<tutorial-lxc-profiles>` for more information on how to use network
profiles.
.. warning::
The ``ipv4``, ``ipv6``, ``gateway``, and ``link`` (bridge) settings in
network profiles will only work if the container doesn't redefine the
network configuration (for example in
``/etc/sysconfig/network-scripts/ifcfg-<interface_name>`` on
RHEL/CentOS, or ``/etc/network/interfaces`` on Debian/Ubuntu/etc.)
CLI Example:
.. code-block:: bash
salt-call lxc.get_network_profile default
'''
profile = _get_profile('network_profile', name, **kwargs)
return profile
def _rand_cpu_str(cpu):
'''
Return a random subset of cpus for the cpuset config
'''
cpu = int(cpu)
avail = __salt__['status.nproc']()
if cpu < avail:
return '0-{0}'.format(avail)
to_set = set()
while len(to_set) < cpu:
choice = random.randint(0, avail - 1)
if choice not in to_set:
to_set.add(six.text_type(choice))
return ','.join(sorted(to_set))
def _network_conf(conf_tuples=None, **kwargs):
'''
Network configuration defaults
network_profile
as for containers, we can either call this function
either with a network_profile dict or network profile name
in the kwargs
nic_opts
overrides or extra nics in the form {nic_name: {set: tings}
'''
nic = kwargs.get('network_profile', None)
ret = []
nic_opts = kwargs.get('nic_opts', {})
if nic_opts is None:
# coming from elsewhere
nic_opts = {}
if not conf_tuples:
conf_tuples = []
old = _get_veths(conf_tuples)
if not old:
old = {}
# if we have a profile name, get the profile and load the network settings
# this will obviously by default look for a profile called "eth0"
# or by what is defined in nic_opts
# and complete each nic settings by sane defaults
if nic and isinstance(nic, (six.string_types, dict)):
nicp = get_network_profile(nic)
else:
nicp = {}
if DEFAULT_NIC not in nicp:
nicp[DEFAULT_NIC] = {}
kwargs = copy.deepcopy(kwargs)
gateway = kwargs.pop('gateway', None)
bridge = kwargs.get('bridge', None)
if nic_opts:
for dev, args in six.iteritems(nic_opts):
ethx = nicp.setdefault(dev, {})
try:
ethx = salt.utils.dictupdate.update(ethx, args)
except AttributeError:
raise SaltInvocationError('Invalid nic_opts configuration')
ifs = [a for a in nicp]
ifs += [a for a in old if a not in nicp]
ifs.sort()
gateway_set = False
for dev in ifs:
args = nicp.get(dev, {})
opts = nic_opts.get(dev, {}) if nic_opts else {}
old_if = old.get(dev, {})
disable = opts.get('disable', args.get('disable', False))
if disable:
continue
mac = opts.get('mac',
opts.get('hwaddr',
args.get('mac',
args.get('hwaddr', ''))))
type_ = opts.get('type', args.get('type', ''))
flags = opts.get('flags', args.get('flags', ''))
link = opts.get('link', args.get('link', ''))
ipv4 = opts.get('ipv4', args.get('ipv4', ''))
ipv6 = opts.get('ipv6', args.get('ipv6', ''))
infos = salt.utils.odict.OrderedDict([
('lxc.network.type', {
'test': not type_,
'value': type_,
'old': old_if.get('lxc.network.type'),
'default': 'veth'}),
('lxc.network.name', {
'test': False,
'value': dev,
'old': dev,
'default': dev}),
('lxc.network.flags', {
'test': not flags,
'value': flags,
'old': old_if.get('lxc.network.flags'),
'default': 'up'}),
('lxc.network.link', {
'test': not link,
'value': link,
'old': old_if.get('lxc.network.link'),
'default': search_lxc_bridge()}),
('lxc.network.hwaddr', {
'test': not mac,
'value': mac,
'old': old_if.get('lxc.network.hwaddr'),
'default': salt.utils.network.gen_mac()}),
('lxc.network.ipv4', {
'test': not ipv4,
'value': ipv4,
'old': old_if.get('lxc.network.ipv4', ''),
'default': None}),
('lxc.network.ipv6', {
'test': not ipv6,
'value': ipv6,
'old': old_if.get('lxc.network.ipv6', ''),
'default': None})])
# for each parameter, if not explicitly set, the
# config value present in the LXC configuration should
# take precedence over the profile configuration
for info in list(infos.keys()):
bundle = infos[info]
if bundle['test']:
if bundle['old']:
bundle['value'] = bundle['old']
elif bundle['default']:
bundle['value'] = bundle['default']
for info, data in six.iteritems(infos):
if data['value']:
ret.append({info: data['value']})
for key, val in six.iteritems(args):
if key == 'link' and bridge:
val = bridge
val = opts.get(key, val)
if key in [
'type', 'flags', 'name',
'gateway', 'mac', 'link', 'ipv4', 'ipv6'
]:
continue
ret.append({'lxc.network.{0}'.format(key): val})
# gateway (in automode) must be appended following network conf !
if not gateway:
gateway = args.get('gateway', None)
if gateway is not None and not gateway_set:
ret.append({'lxc.network.ipv4.gateway': gateway})
# only one network gateway ;)
gateway_set = True
# normally, this won't happen
# set the gateway if specified even if we did
# not managed the network underlying
if gateway is not None and not gateway_set:
ret.append({'lxc.network.ipv4.gateway': gateway})
# only one network gateway ;)
gateway_set = True
new = _get_veths(ret)
# verify that we did not loose the mac settings
for iface in [a for a in new]:
ndata = new[iface]
nmac = ndata.get('lxc.network.hwaddr', '')
ntype = ndata.get('lxc.network.type', '')
omac, otype = '', ''
if iface in old:
odata = old[iface]
omac = odata.get('lxc.network.hwaddr', '')
otype = odata.get('lxc.network.type', '')
# default for network type is setted here
# attention not to change the network type
# without a good and explicit reason to.
if otype and not ntype:
ntype = otype
if not ntype:
ntype = 'veth'
new[iface]['lxc.network.type'] = ntype
if omac and not nmac:
new[iface]['lxc.network.hwaddr'] = omac
ret = []
for val in six.itervalues(new):
for row in val:
ret.append(salt.utils.odict.OrderedDict([(row, val[row])]))
# on old versions of lxc, still support the gateway auto mode
# if we didn't explicitly say no to
# (lxc.network.ipv4.gateway: auto)
if _LooseVersion(version()) <= _LooseVersion('1.0.7') and \
True not in ['lxc.network.ipv4.gateway' in a for a in ret] and \
True in ['lxc.network.ipv4' in a for a in ret]:
ret.append({'lxc.network.ipv4.gateway': 'auto'})
return ret
def _get_lxc_default_data(**kwargs):
kwargs = copy.deepcopy(kwargs)
ret = {}
for k in ['utsname', 'rootfs']:
val = kwargs.get(k, None)
if val is not None:
ret['lxc.{0}'.format(k)] = val
autostart = kwargs.get('autostart')
# autostart can have made in kwargs, but with the None
# value which is invalid, we need an explicit boolean
# autostart = on is the default.
if autostart is None:
autostart = True
# we will set the regular lxc marker to restart container at
# machine (re)boot only if we did not explicitly ask
# not to touch to the autostart settings via
# autostart == 'keep'
if autostart != 'keep':
if autostart:
ret['lxc.start.auto'] = '1'
else:
ret['lxc.start.auto'] = '0'
memory = kwargs.get('memory')
if memory is not None:
# converting the config value from MB to bytes
ret['lxc.cgroup.memory.limit_in_bytes'] = memory * 1024 * 1024
cpuset = kwargs.get('cpuset')
if cpuset:
ret['lxc.cgroup.cpuset.cpus'] = cpuset
cpushare = kwargs.get('cpushare')
cpu = kwargs.get('cpu')
if cpushare:
ret['lxc.cgroup.cpu.shares'] = cpushare
if cpu and not cpuset:
ret['lxc.cgroup.cpuset.cpus'] = _rand_cpu_str(cpu)
return ret
def _config_list(conf_tuples=None, only_net=False, **kwargs):
'''
Return a list of dicts from the salt level configurations
conf_tuples
_LXCConfig compatible list of entries which can contain
- string line
- tuple (lxc config param,value)
- dict of one entry: {lxc config param: value)
only_net
by default we add to the tuples a reflection of both
the real config if avalaible and a certain amount of
default values like the cpu parameters, the memory
and etc.
On the other hand, we also no matter the case reflect
the network configuration computed from the actual config if
available and given values.
if no_default_loads is set, we will only
reflect the network configuration back to the conf tuples
list
'''
# explicit cast
only_net = bool(only_net)
if not conf_tuples:
conf_tuples = []
kwargs = copy.deepcopy(kwargs)
ret = []
if not only_net:
default_data = _get_lxc_default_data(**kwargs)
for k, val in six.iteritems(default_data):
ret.append({k: val})
net_datas = _network_conf(conf_tuples=conf_tuples, **kwargs)
ret.extend(net_datas)
return ret
class _LXCConfig(object):
'''
LXC configuration data
'''
pattern = re.compile(r'^(\S+)(\s*)(=)(\s*)(.*)')
non_interpretable_pattern = re.compile(r'^((#.*)|(\s*))$')
def __init__(self, **kwargs):
kwargs = copy.deepcopy(kwargs)
self.name = kwargs.pop('name', None)
path = get_root_path(kwargs.get('path', None))
self.data = []
if self.name:
self.path = os.path.join(path, self.name, 'config')
if os.path.isfile(self.path):
with salt.utils.files.fopen(self.path) as fhr:
for line in salt.utils.data.decode(fhr.readlines()):
match = self.pattern.findall((line.strip()))
if match:
self.data.append((match[0][0], match[0][-1]))
match = self.non_interpretable_pattern.findall(
(line.strip()))
if match:
self.data.append(('', match[0][0]))
else:
self.path = None
def _replace(key, val):
if val:
self._filter_data(key)
self.data.append((key, val))
default_data = _get_lxc_default_data(**kwargs)
for key, val in six.iteritems(default_data):
_replace(key, val)
old_net = self._filter_data('lxc.network')
net_datas = _network_conf(conf_tuples=old_net, **kwargs)
if net_datas:
for row in net_datas:
self.data.extend(list(row.items()))
# be sure to reset harmful settings
for idx in ['lxc.cgroup.memory.limit_in_bytes']:
if not default_data.get(idx):
self._filter_data(idx)
def as_string(self):
chunks = ('{0[0]}{1}{0[1]}'.format(item, (' = ' if item[0] else '')) for item in self.data)
return '\n'.join(chunks) + '\n'
def write(self):
if self.path:
content = self.as_string()
# 2 step rendering to be sure not to open/wipe the config
# before as_string succeeds.
with salt.utils.files.fopen(self.path, 'w') as fic:
fic.write(salt.utils.stringutils.to_str(content))
fic.flush()
def tempfile(self):
# this might look like the function name is shadowing the
# module, but it's not since the method belongs to the class
ntf = tempfile.NamedTemporaryFile()
ntf.write(self.as_string())
ntf.flush()
return ntf
def _filter_data(self, pattern):
'''
Removes parameters which match the pattern from the config data
'''
removed = []
filtered = []
for param in self.data:
if not param[0].startswith(pattern):
filtered.append(param)
else:
removed.append(param)
self.data = filtered
return removed
def _get_base(**kwargs):
'''
If the needed base does not exist, then create it, if it does exist
create nothing and return the name of the base lxc container so
it can be cloned.
'''
profile = get_container_profile(copy.deepcopy(kwargs.get('profile')))
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, _marker)
profile_match = profile.pop(key, default)
# let kwarg overrides be the preferred choice
if kw_overrides_match is _marker:
return profile_match
return kw_overrides_match
template = select('template')
image = select('image')
vgname = select('vgname')
path = kwargs.get('path', None)
# remove the above three variables from kwargs, if they exist, to avoid
# duplicates if create() is invoked below.
for param in ('path', 'image', 'vgname', 'template'):
kwargs.pop(param, None)
if image:
proto = _urlparse(image).scheme
img_tar = __salt__['cp.cache_file'](image)
img_name = os.path.basename(img_tar)
hash_ = salt.utils.hashutils.get_hash(
img_tar,
__salt__['config.get']('hash_type'))
name = '__base_{0}_{1}_{2}'.format(proto, img_name, hash_)
if not exists(name, path=path):
create(name, template=template, image=image,
path=path, vgname=vgname, **kwargs)
if vgname:
rootfs = os.path.join('/dev', vgname, name)
edit_conf(info(name, path=path)['config'],
out_format='commented', **{'lxc.rootfs': rootfs})
return name
elif template:
name = '__base_{0}'.format(template)
if not exists(name, path=path):
create(name, template=template, image=image, path=path,
vgname=vgname, **kwargs)
if vgname:
rootfs = os.path.join('/dev', vgname, name)
edit_conf(info(name, path=path)['config'],
out_format='commented', **{'lxc.rootfs': rootfs})
return name
return ''
def init(name,
config=None,
cpuset=None,
cpushare=None,
memory=None,
profile=None,
network_profile=None,
nic_opts=None,
cpu=None,
autostart=True,
password=None,
password_encrypted=None,
users=None,
dnsservers=None,
searchdomains=None,
bridge=None,
gateway=None,
pub_key=None,
priv_key=None,
force_install=False,
unconditional_install=False,
bootstrap_delay=None,
bootstrap_args=None,
bootstrap_shell=None,
bootstrap_url=None,
**kwargs):
'''
Initialize a new container.
This is a partial idempotent function as if it is already provisioned, we
will reset a bit the lxc configuration file but much of the hard work will
be escaped as markers will prevent re-execution of harmful tasks.
name
Name of the container
image
A tar archive to use as the rootfs for the container. Conflicts with
the ``template`` argument.
cpus
Select a random number of cpu cores and assign it to the cpuset, if the
cpuset option is set then this option will be ignored
cpuset
Explicitly define the cpus this container will be bound to
cpushare
cgroups cpu shares
autostart
autostart container on reboot
memory
cgroups memory limit, in MB
.. versionchanged:: 2015.5.0
If no value is passed, no limit is set. In earlier Salt versions,
not passing this value causes a 1024MB memory limit to be set, and
it was necessary to pass ``memory=0`` to set no limit.
gateway
the ipv4 gateway to use
the default does nothing more than lxcutils does
bridge
the bridge to use
the default does nothing more than lxcutils does
network_profile
Network profile to use for the container
.. versionadded:: 2015.5.0
nic_opts
Extra options for network interfaces, will override
``{"eth0": {"hwaddr": "aa:bb:cc:dd:ee:ff", "ipv4": "10.1.1.1", "ipv6": "2001:db8::ff00:42:8329"}}``
or
``{"eth0": {"hwaddr": "aa:bb:cc:dd:ee:ff", "ipv4": "10.1.1.1/24", "ipv6": "2001:db8::ff00:42:8329"}}``
users
Users for which the password defined in the ``password`` param should
be set. Can be passed as a comma separated list or a python list.
Defaults to just the ``root`` user.
password
Set the initial password for the users defined in the ``users``
parameter
password_encrypted : False
Set to ``True`` to denote a password hash instead of a plaintext
password
.. versionadded:: 2015.5.0
profile
A LXC profile (defined in config or pillar).
This can be either a real profile mapping or a string
to retrieve it in configuration
start
Start the newly-created container
dnsservers
list of dns servers to set in the container, default [] (no setting)
seed
Seed the container with the minion config. Default: ``True``
install
If salt-minion is not already installed, install it. Default: ``True``
config
Optional config parameters. By default, the id is set to
the name of the container.
master
salt master (default to minion's master)
master_port
salt master port (default to minion's master port)
pub_key
Explicit public key to preseed the minion with (optional).
This can be either a filepath or a string representing the key
priv_key
Explicit private key to preseed the minion with (optional).
This can be either a filepath or a string representing the key
approve_key
If explicit preseeding is not used;
Attempt to request key approval from the master. Default: ``True``
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
clone_from
Original from which to use a clone operation to create the container.
Default: ``None``
bootstrap_delay
Delay in seconds between end of container creation and bootstrapping.
Useful when waiting for container to obtain a DHCP lease.
.. versionadded:: 2015.5.0
bootstrap_url
See lxc.bootstrap
bootstrap_shell
See lxc.bootstrap
bootstrap_args
See lxc.bootstrap
force_install
Force installation even if salt-minion is detected,
this is the way to run vendor bootstrap scripts even
if a salt minion is already present in the container
unconditional_install
Run the script even if the container seems seeded
CLI Example:
.. code-block:: bash
salt 'minion' lxc.init name [cpuset=cgroups_cpuset] \\
[cpushare=cgroups_cpushare] [memory=cgroups_memory] \\
[nic=nic_profile] [profile=lxc_profile] \\
[nic_opts=nic_opts] [start=(True|False)] \\
[seed=(True|False)] [install=(True|False)] \\
[config=minion_config] [approve_key=(True|False) \\
[clone_from=original] [autostart=True] \\
[priv_key=/path_or_content] [pub_key=/path_or_content] \\
[bridge=lxcbr0] [gateway=10.0.3.1] \\
[dnsservers[dns1,dns2]] \\
[users=[foo]] [password='secret'] \\
[password_encrypted=(True|False)]
'''
ret = {'name': name,
'changes': {}}
profile = get_container_profile(copy.deepcopy(profile))
if not network_profile:
network_profile = profile.get('network_profile')
if not network_profile:
network_profile = DEFAULT_NIC
# Changes is a pointer to changes_dict['init']. This method is used so that
# we can have a list of changes as they are made, providing an ordered list
# of things that were changed.
changes_dict = {'init': []}
changes = changes_dict.get('init')
if users is None:
users = []
dusers = ['root']
for user in dusers:
if user not in users:
users.append(user)
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, _marker)
profile_match = profile.pop(key, default)
# let kwarg overrides be the preferred choice
if kw_overrides_match is _marker:
return profile_match
return kw_overrides_match
path = select('path')
bpath = get_root_path(path)
state_pre = state(name, path=path)
tvg = select('vgname')
vgname = tvg if tvg else __salt__['config.get']('lxc.vgname')
start_ = select('start', True)
autostart = select('autostart', autostart)
seed = select('seed', True)
install = select('install', True)
seed_cmd = select('seed_cmd')
salt_config = _get_salt_config(config, **kwargs)
approve_key = select('approve_key', True)
clone_from = select('clone_from')
# If using a volume group then set up to make snapshot cow clones
if vgname and not clone_from:
try:
kwargs['vgname'] = vgname
clone_from = _get_base(profile=profile, **kwargs)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = exc.strerror
if changes:
ret['changes'] = changes_dict
return ret
if not kwargs.get('snapshot') is False:
kwargs['snapshot'] = True
does_exist = exists(name, path=path)
to_reboot = False
remove_seed_marker = False
if does_exist:
pass
elif clone_from:
remove_seed_marker = True
try:
clone(name, clone_from, profile=profile, **kwargs)
changes.append({'create': 'Container cloned'})
except (SaltInvocationError, CommandExecutionError) as exc:
if 'already exists' in exc.strerror:
changes.append({'create': 'Container already exists'})
else:
ret['result'] = False
ret['comment'] = exc.strerror
if changes:
ret['changes'] = changes_dict
return ret
cfg = _LXCConfig(name=name, network_profile=network_profile,
nic_opts=nic_opts, bridge=bridge, path=path,
gateway=gateway, autostart=autostart,
cpuset=cpuset, cpushare=cpushare, memory=memory)
old_chunks = read_conf(cfg.path, out_format='commented')
cfg.write()
chunks = read_conf(cfg.path, out_format='commented')
if old_chunks != chunks:
to_reboot = True
else:
remove_seed_marker = True
cfg = _LXCConfig(network_profile=network_profile,
nic_opts=nic_opts, cpuset=cpuset, path=path,
bridge=bridge, gateway=gateway,
autostart=autostart,
cpushare=cpushare, memory=memory)
with cfg.tempfile() as cfile:
try:
create(name, config=cfile.name, profile=profile, **kwargs)
changes.append({'create': 'Container created'})
except (SaltInvocationError, CommandExecutionError) as exc:
if 'already exists' in exc.strerror:
changes.append({'create': 'Container already exists'})
else:
ret['comment'] = exc.strerror
if changes:
ret['changes'] = changes_dict
return ret
cpath = os.path.join(bpath, name, 'config')
old_chunks = []
if os.path.exists(cpath):
old_chunks = read_conf(cpath, out_format='commented')
new_cfg = _config_list(conf_tuples=old_chunks,
cpu=cpu,
network_profile=network_profile,
nic_opts=nic_opts, bridge=bridge,
cpuset=cpuset, cpushare=cpushare,
memory=memory)
if new_cfg:
edit_conf(cpath, out_format='commented', lxc_config=new_cfg)
chunks = read_conf(cpath, out_format='commented')
if old_chunks != chunks:
to_reboot = True
# last time to be sure any of our property is correctly applied
cfg = _LXCConfig(name=name, network_profile=network_profile,
nic_opts=nic_opts, bridge=bridge, path=path,
gateway=gateway, autostart=autostart,
cpuset=cpuset, cpushare=cpushare, memory=memory)
old_chunks = []
if os.path.exists(cfg.path):
old_chunks = read_conf(cfg.path, out_format='commented')
cfg.write()
chunks = read_conf(cfg.path, out_format='commented')
if old_chunks != chunks:
changes.append({'config': 'Container configuration updated'})
to_reboot = True
if to_reboot:
try:
stop(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
if changes:
ret['changes'] = changes_dict
return ret
if not does_exist or (does_exist and state(name, path=path) != 'running'):
try:
start(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
if changes:
ret['changes'] = changes_dict
return ret
if remove_seed_marker:
run(name,
'rm -f \'{0}\''.format(SEED_MARKER),
path=path,
chroot_fallback=False,
python_shell=False)
# set the default user/password, only the first time
if ret.get('result', True) and password:
gid = '/.lxc.initial_pass'
gids = [gid,
'/lxc.initial_pass',
'/.lxc.{0}.initial_pass'.format(name)]
if not any(retcode(name,
'test -e "{0}"'.format(x),
chroot_fallback=True,
path=path,
ignore_retcode=True) == 0
for x in gids):
# think to touch the default user generated by default templates
# which has a really unsecure passwords...
# root is defined as a member earlier in the code
for default_user in ['ubuntu']:
if (
default_user not in users and
retcode(name,
'id {0}'.format(default_user),
python_shell=False,
path=path,
chroot_fallback=True,
ignore_retcode=True) == 0
):
users.append(default_user)
for user in users:
try:
cret = set_password(name,
users=[user],
path=path,
password=password,
encrypted=password_encrypted)
except (SaltInvocationError, CommandExecutionError) as exc:
msg = '{0}: Failed to set password'.format(
user) + exc.strerror
# only hardfail in unrecoverable situation:
# root cannot be setted up
if user == 'root':
ret['comment'] = msg
ret['result'] = False
else:
log.debug(msg)
if ret.get('result', True):
changes.append({'password': 'Password(s) updated'})
if retcode(name,
('sh -c \'touch "{0}"; test -e "{0}"\''
.format(gid)),
path=path,
chroot_fallback=True,
ignore_retcode=True) != 0:
ret['comment'] = 'Failed to set password marker'
changes[-1]['password'] += '. ' + ret['comment'] + '.'
ret['result'] = False
# set dns servers if any, only the first time
if ret.get('result', True) and dnsservers:
# retro compatibility, test also old markers
gid = '/.lxc.initial_dns'
gids = [gid,
'/lxc.initial_dns',
'/lxc.{0}.initial_dns'.format(name)]
if not any(retcode(name,
'test -e "{0}"'.format(x),
chroot_fallback=True,
path=path,
ignore_retcode=True) == 0
for x in gids):
try:
set_dns(name,
path=path,
dnsservers=dnsservers,
searchdomains=searchdomains)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Failed to set DNS: ' + exc.strerror
ret['result'] = False
else:
changes.append({'dns': 'DNS updated'})
if retcode(name,
('sh -c \'touch "{0}"; test -e "{0}"\''
.format(gid)),
chroot_fallback=True,
path=path,
ignore_retcode=True) != 0:
ret['comment'] = 'Failed to set DNS marker'
changes[-1]['dns'] += '. ' + ret['comment'] + '.'
ret['result'] = False
# retro compatibility, test also old markers
if remove_seed_marker:
run(name,
'rm -f \'{0}\''.format(SEED_MARKER),
path=path,
python_shell=False)
gid = '/.lxc.initial_seed'
gids = [gid, '/lxc.initial_seed']
if (
any(retcode(name,
'test -e {0}'.format(x),
path=path,
chroot_fallback=True,
ignore_retcode=True) == 0
for x in gids) or not ret.get('result', True)
):
pass
elif seed or seed_cmd:
if seed:
try:
result = bootstrap(
name, config=salt_config, path=path,
approve_key=approve_key,
pub_key=pub_key, priv_key=priv_key,
install=install,
force_install=force_install,
unconditional_install=unconditional_install,
bootstrap_delay=bootstrap_delay,
bootstrap_url=bootstrap_url,
bootstrap_shell=bootstrap_shell,
bootstrap_args=bootstrap_args)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Bootstrap failed: ' + exc.strerror
ret['result'] = False
else:
if not result:
ret['comment'] = ('Bootstrap failed, see minion log for '
'more information')
ret['result'] = False
else:
changes.append(
{'bootstrap': 'Container successfully bootstrapped'}
)
elif seed_cmd:
try:
result = __salt__[seed_cmd](info(name, path=path)['rootfs'],
name,
salt_config)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = ('Bootstrap via seed_cmd \'{0}\' failed: {1}'
.format(seed_cmd, exc.strerror))
ret['result'] = False
else:
if not result:
ret['comment'] = ('Bootstrap via seed_cmd \'{0}\' failed, '
'see minion log for more information '
.format(seed_cmd))
ret['result'] = False
else:
changes.append(
{'bootstrap': 'Container successfully bootstrapped '
'using seed_cmd \'{0}\''
.format(seed_cmd)}
)
if ret.get('result', True) and not start_:
try:
stop(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
ret['result'] = False
state_post = state(name, path=path)
if state_pre != state_post:
changes.append({'state': {'old': state_pre, 'new': state_post}})
if ret.get('result', True):
ret['comment'] = ('Container \'{0}\' successfully initialized'
.format(name))
ret['result'] = True
if changes:
ret['changes'] = changes_dict
return ret
def cloud_init(name, vm_=None, **kwargs):
'''
Thin wrapper to lxc.init to be used from the saltcloud lxc driver
name
Name of the container
may be None and then guessed from saltcloud mapping
`vm_`
saltcloud mapping defaults for the vm
CLI Example:
.. code-block:: bash
salt '*' lxc.cloud_init foo
'''
init_interface = cloud_init_interface(name, vm_, **kwargs)
name = init_interface.pop('name', name)
return init(name, **init_interface)
def images(dist=None):
'''
.. versionadded:: 2015.5.0
List the available images for LXC's ``download`` template.
dist : None
Filter results to a single Linux distribution
CLI Examples:
.. code-block:: bash
salt myminion lxc.images
salt myminion lxc.images dist=centos
'''
out = __salt__['cmd.run_stdout'](
'lxc-create -n __imgcheck -t download -- --list',
ignore_retcode=True
)
if 'DIST' not in out:
raise CommandExecutionError(
'Unable to run the \'download\' template script. Is it installed?'
)
ret = {}
passed_header = False
for line in out.splitlines():
try:
distro, release, arch, variant, build_time = line.split()
except ValueError:
continue
if not passed_header:
if distro == 'DIST':
passed_header = True
continue
dist_list = ret.setdefault(distro, [])
dist_list.append({
'release': release,
'arch': arch,
'variant': variant,
'build_time': build_time,
})
if dist is not None:
return dict([(dist, ret.get(dist, []))])
return ret
def templates():
'''
.. versionadded:: 2015.5.0
List the available LXC template scripts installed on the minion
CLI Examples:
.. code-block:: bash
salt myminion lxc.templates
'''
try:
template_scripts = os.listdir('/usr/share/lxc/templates')
except OSError:
return []
else:
return [x[4:] for x in template_scripts if x.startswith('lxc-')]
def _after_ignition_network_profile(cmd,
ret,
name,
network_profile,
path,
nic_opts):
_clear_context()
if ret['retcode'] == 0 and exists(name, path=path):
if network_profile:
network_changes = apply_network_profile(name,
network_profile,
path=path,
nic_opts=nic_opts)
if network_changes:
log.info(
'Network changes from applying network profile \'%s\' '
'to newly-created container \'%s\':\n%s',
network_profile, name, network_changes
)
c_state = state(name, path=path)
return {'result': True,
'state': {'old': None, 'new': c_state}}
else:
if exists(name, path=path):
# destroy the container if it was partially created
cmd = 'lxc-destroy'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0}'.format(name)
__salt__['cmd.retcode'](cmd, python_shell=False)
raise CommandExecutionError(
'Container could not be created with cmd \'{0}\': {1}'
.format(cmd, ret['stderr'])
)
def create(name,
config=None,
profile=None,
network_profile=None,
nic_opts=None,
**kwargs):
'''
Create a new container.
name
Name of the container
config
The config file to use for the container. Defaults to system-wide
config (usually in /etc/lxc/lxc.conf).
profile
Profile to use in container creation (see
:mod:`lxc.get_container_profile
<salt.modules.lxc.get_container_profile>`). Values in a profile will be
overridden by the **Container Creation Arguments** listed below.
network_profile
Network profile to use for container
.. versionadded:: 2015.5.0
**Container Creation Arguments**
template
The template to use. For example, ``ubuntu`` or ``fedora``.
For a full list of available templates, check out
the :mod:`lxc.templates <salt.modules.lxc.templates>` function.
Conflicts with the ``image`` argument.
.. note::
The ``download`` template requires the following three parameters
to be defined in ``options``:
* **dist** - The name of the distribution
* **release** - Release name/version
* **arch** - Architecture of the container
The available images can be listed using the :mod:`lxc.images
<salt.modules.lxc.images>` function.
options
Template-specific options to pass to the lxc-create command. These
correspond to the long options (ones beginning with two dashes) that
the template script accepts. For example:
.. code-block:: bash
options='{"dist": "centos", "release": "6", "arch": "amd64"}'
For available template options, refer to the lxc template scripts
which are ususally located under ``/usr/share/lxc/templates``,
or run ``lxc-create -t <template> -h``.
image
A tar archive to use as the rootfs for the container. Conflicts with
the ``template`` argument.
backing
The type of storage to use. Set to ``lvm`` to use an LVM group.
Defaults to filesystem within /var/lib/lxc.
fstype
Filesystem type to use on LVM logical volume
size : 1G
Size of the volume to create. Only applicable if ``backing=lvm``.
vgname : lxc
Name of the LVM volume group in which to create the volume for this
container. Only applicable if ``backing=lvm``.
lvname
Name of the LVM logical volume in which to create the volume for this
container. Only applicable if ``backing=lvm``.
thinpool
Name of a pool volume that will be used for thin-provisioning this
container. Only applicable if ``backing=lvm``.
nic_opts
give extra opts overriding network profile values
path
parent path for the container creation (default: /var/lib/lxc)
zfsroot
Name of the ZFS root in which to create the volume for this container.
Only applicable if ``backing=zfs``. (default: tank/lxc)
.. versionadded:: 2015.8.0
'''
# Required params for 'download' template
download_template_deps = ('dist', 'release', 'arch')
cmd = 'lxc-create -n {0}'.format(name)
profile = get_container_profile(copy.deepcopy(profile))
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, None)
profile_match = profile.pop(key, default)
# Return the profile match if the the kwarg match was None, as the
# lxc.present state will pass these kwargs set to None by default.
if kw_overrides_match is None:
return profile_match
return kw_overrides_match
path = select('path')
if exists(name, path=path):
raise CommandExecutionError(
'Container \'{0}\' already exists'.format(name)
)
tvg = select('vgname')
vgname = tvg if tvg else __salt__['config.get']('lxc.vgname')
# The 'template' and 'image' params conflict
template = select('template')
image = select('image')
if template and image:
raise SaltInvocationError(
'Only one of \'template\' and \'image\' is permitted'
)
elif not any((template, image, profile)):
raise SaltInvocationError(
'At least one of \'template\', \'image\', and \'profile\' is '
'required'
)
options = select('options') or {}
backing = select('backing')
if vgname and not backing:
backing = 'lvm'
lvname = select('lvname')
thinpool = select('thinpool')
fstype = select('fstype')
size = select('size', '1G')
zfsroot = select('zfsroot')
if backing in ('dir', 'overlayfs', 'btrfs', 'zfs'):
fstype = None
size = None
# some backends won't support some parameters
if backing in ('aufs', 'dir', 'overlayfs', 'btrfs'):
lvname = vgname = thinpool = None
if image:
img_tar = __salt__['cp.cache_file'](image)
template = os.path.join(
os.path.dirname(salt.__file__),
'templates',
'lxc',
'salt_tarball')
options['imgtar'] = img_tar
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
if not os.path.exists(path):
os.makedirs(path)
if config:
cmd += ' -f {0}'.format(config)
if template:
cmd += ' -t {0}'.format(template)
if backing:
backing = backing.lower()
cmd += ' -B {0}'.format(backing)
if backing in ('zfs',):
if zfsroot:
cmd += ' --zfsroot {0}'.format(zfsroot)
if backing in ('lvm',):
if lvname:
cmd += ' --lvname {0}'.format(lvname)
if vgname:
cmd += ' --vgname {0}'.format(vgname)
if thinpool:
cmd += ' --thinpool {0}'.format(thinpool)
if backing not in ('dir', 'overlayfs'):
if fstype:
cmd += ' --fstype {0}'.format(fstype)
if size:
cmd += ' --fssize {0}'.format(size)
if options:
if template == 'download':
missing_deps = [x for x in download_template_deps
if x not in options]
if missing_deps:
raise SaltInvocationError(
'Missing params in \'options\' dict: {0}'
.format(', '.join(missing_deps))
)
cmd += ' --'
for key, val in six.iteritems(options):
cmd += ' --{0} {1}'.format(key, val)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
# please do not merge extra conflicting stuff
# inside those two line (ret =, return)
return _after_ignition_network_profile(cmd,
ret,
name,
network_profile,
path,
nic_opts)
def clone(name,
orig,
profile=None,
network_profile=None,
nic_opts=None,
**kwargs):
'''
Create a new container as a clone of another container
name
Name of the container
orig
Name of the original container to be cloned
profile
Profile to use in container cloning (see
:mod:`lxc.get_container_profile
<salt.modules.lxc.get_container_profile>`). Values in a profile will be
overridden by the **Container Cloning Arguments** listed below.
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
**Container Cloning Arguments**
snapshot
Use Copy On Write snapshots (LVM)
size : 1G
Size of the volume to create. Only applicable if ``backing=lvm``.
backing
The type of storage to use. Set to ``lvm`` to use an LVM group.
Defaults to filesystem within /var/lib/lxc.
network_profile
Network profile to use for container
.. versionadded:: 2015.8.0
nic_opts
give extra opts overriding network profile values
.. versionadded:: 2015.8.0
CLI Examples:
.. code-block:: bash
salt '*' lxc.clone myclone orig=orig_container
salt '*' lxc.clone myclone orig=orig_container snapshot=True
'''
profile = get_container_profile(copy.deepcopy(profile))
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, None)
profile_match = profile.pop(key, default)
# let kwarg overrides be the preferred choice
if kw_overrides_match is None:
return profile_match
return kw_overrides_match
path = select('path')
if exists(name, path=path):
raise CommandExecutionError(
'Container \'{0}\' already exists'.format(name)
)
_ensure_exists(orig, path=path)
if state(orig, path=path) != 'stopped':
raise CommandExecutionError(
'Container \'{0}\' must be stopped to be cloned'.format(orig)
)
backing = select('backing')
snapshot = select('snapshot')
if backing in ('dir',):
snapshot = False
if not snapshot:
snapshot = ''
else:
snapshot = '-s'
size = select('size', '1G')
if backing in ('dir', 'overlayfs', 'btrfs'):
size = None
# LXC commands and options changed in 2.0 - CF issue #34086 for details
if _LooseVersion(version()) >= _LooseVersion('2.0'):
# https://linuxcontainers.org/lxc/manpages//man1/lxc-copy.1.html
cmd = 'lxc-copy'
cmd += ' {0} -n {1} -N {2}'.format(snapshot, orig, name)
else:
# https://linuxcontainers.org/lxc/manpages//man1/lxc-clone.1.html
cmd = 'lxc-clone'
cmd += ' {0} -o {1} -n {2}'.format(snapshot, orig, name)
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
if not os.path.exists(path):
os.makedirs(path)
if backing:
backing = backing.lower()
cmd += ' -B {0}'.format(backing)
if backing not in ('dir', 'overlayfs'):
if size:
cmd += ' -L {0}'.format(size)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
# please do not merge extra conflicting stuff
# inside those two line (ret =, return)
return _after_ignition_network_profile(cmd,
ret,
name,
network_profile,
path,
nic_opts)
def ls_(active=None, cache=True, path=None):
'''
Return a list of the containers available on the minion
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
active
If ``True``, return only active (i.e. running) containers
.. versionadded:: 2015.5.0
CLI Example:
.. code-block:: bash
salt '*' lxc.ls
salt '*' lxc.ls active=True
'''
contextvar = 'lxc.ls{0}'.format(path)
if active:
contextvar += '.active'
if cache and (contextvar in __context__):
return __context__[contextvar]
else:
ret = []
cmd = 'lxc-ls'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
if active:
cmd += ' --active'
output = __salt__['cmd.run_stdout'](cmd, python_shell=False)
for line in output.splitlines():
ret.extend(line.split())
__context__[contextvar] = ret
return ret
def list_(extra=False, limit=None, path=None):
'''
List containers classified by state
extra
Also get per-container specific info. This will change the return data.
Instead of returning a list of containers, a dictionary of containers
and each container's output from :mod:`lxc.info
<salt.modules.lxc.info>`.
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
limit
Return output matching a specific state (**frozen**, **running**, or
**stopped**).
.. versionadded:: 2015.5.0
CLI Examples:
.. code-block:: bash
salt '*' lxc.list
salt '*' lxc.list extra=True
salt '*' lxc.list limit=running
'''
ctnrs = ls_(path=path)
if extra:
stopped = {}
frozen = {}
running = {}
else:
stopped = []
frozen = []
running = []
ret = {'running': running,
'stopped': stopped,
'frozen': frozen}
for container in ctnrs:
cmd = 'lxc-info'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0}'.format(container)
c_info = __salt__['cmd.run'](
cmd,
python_shell=False,
output_loglevel='debug'
)
c_state = None
for line in c_info.splitlines():
stat = line.split(':')
if stat[0] in ('State', 'state'):
c_state = stat[1].strip()
break
if not c_state or (limit is not None and c_state.lower() != limit):
continue
if extra:
infos = info(container, path=path)
method = 'update'
value = {container: infos}
else:
method = 'append'
value = container
if c_state == 'STOPPED':
getattr(stopped, method)(value)
continue
if c_state == 'FROZEN':
getattr(frozen, method)(value)
continue
if c_state == 'RUNNING':
getattr(running, method)(value)
continue
if limit is not None:
return ret.get(limit, {} if extra else [])
return ret
def _change_state(cmd,
name,
expected,
stdin=_marker,
stdout=_marker,
stderr=_marker,
with_communicate=_marker,
use_vt=_marker,
path=None):
pre = state(name, path=path)
if pre == expected:
return {'result': True,
'state': {'old': expected, 'new': expected},
'comment': 'Container \'{0}\' already {1}'
.format(name, expected)}
if cmd == 'lxc-destroy':
# Kill the container first
scmd = 'lxc-stop'
if path:
scmd += ' -P {0}'.format(pipes.quote(path))
scmd += ' -k -n {0}'.format(name)
__salt__['cmd.run'](scmd,
python_shell=False)
if path and ' -P ' not in cmd:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0}'.format(name)
# certain lxc commands need to be taken with care (lxc-start)
# as te command itself mess with double forks; we must not
# communicate with it, but just wait for the exit status
pkwargs = {'python_shell': False,
'redirect_stderr': True,
'with_communicate': with_communicate,
'use_vt': use_vt,
'stdin': stdin,
'stdout': stdout}
for i in [a for a in pkwargs]:
val = pkwargs[i]
if val is _marker:
pkwargs.pop(i, None)
_cmdout = __salt__['cmd.run_all'](cmd, **pkwargs)
if _cmdout['retcode'] != 0:
raise CommandExecutionError(
'Error changing state for container \'{0}\' using command '
'\'{1}\': {2}'.format(name, cmd, _cmdout['stdout'])
)
if expected is not None:
# some commands do not wait, so we will
rcmd = 'lxc-wait'
if path:
rcmd += ' -P {0}'.format(pipes.quote(path))
rcmd += ' -n {0} -s {1}'.format(name, expected.upper())
__salt__['cmd.run'](rcmd, python_shell=False, timeout=30)
_clear_context()
post = state(name, path=path)
ret = {'result': post == expected,
'state': {'old': pre, 'new': post}}
return ret
def _ensure_exists(name, path=None):
'''
Raise an exception if the container does not exist
'''
if not exists(name, path=path):
raise CommandExecutionError(
'Container \'{0}\' does not exist'.format(name)
)
def _ensure_running(name, no_start=False, path=None):
'''
If the container is not currently running, start it. This function returns
the state that the container was in before changing
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
'''
_ensure_exists(name, path=path)
pre = state(name, path=path)
if pre == 'running':
# This will be a no-op but running the function will give us a pretty
# return dict.
return start(name, path=path)
elif pre == 'stopped':
if no_start:
raise CommandExecutionError(
'Container \'{0}\' is not running'.format(name)
)
return start(name, path=path)
elif pre == 'frozen':
if no_start:
raise CommandExecutionError(
'Container \'{0}\' is not running'.format(name)
)
return unfreeze(name, path=path)
def restart(name, path=None, lxc_config=None, force=False):
'''
.. versionadded:: 2015.5.0
Restart the named container. If the container was not running, the
container will merely be started.
name
The name of the container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
lxc_config
path to a lxc config file
config file will be guessed from container name otherwise
.. versionadded:: 2015.8.0
force : False
If ``True``, the container will be force-stopped instead of gracefully
shut down
CLI Example:
.. code-block:: bash
salt myminion lxc.restart name
'''
_ensure_exists(name, path=path)
orig_state = state(name, path=path)
if orig_state != 'stopped':
stop(name, kill=force, path=path)
ret = start(name, path=path, lxc_config=lxc_config)
ret['state']['old'] = orig_state
if orig_state != 'stopped':
ret['restarted'] = True
return ret
def start(name, **kwargs):
'''
Start the named container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
lxc_config
path to a lxc config file
config file will be guessed from container name otherwise
.. versionadded:: 2015.8.0
use_vt
run the command through VT
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.start name
'''
path = kwargs.get('path', None)
cpath = get_root_path(path)
lxc_config = kwargs.get('lxc_config', None)
cmd = 'lxc-start'
if not lxc_config:
lxc_config = os.path.join(cpath, name, 'config')
# we try to start, even without config, if global opts are there
if os.path.exists(lxc_config):
cmd += ' -f {0}'.format(pipes.quote(lxc_config))
cmd += ' -d'
_ensure_exists(name, path=path)
if state(name, path=path) == 'frozen':
raise CommandExecutionError(
'Container \'{0}\' is frozen, use lxc.unfreeze'.format(name)
)
# lxc-start daemonize itself violently, we must not communicate with it
use_vt = kwargs.get('use_vt', None)
with_communicate = kwargs.get('with_communicate', False)
return _change_state(cmd, name, 'running',
stdout=None,
stderr=None,
stdin=None,
with_communicate=with_communicate,
path=path,
use_vt=use_vt)
def stop(name, kill=False, path=None, use_vt=None):
'''
Stop the named container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
kill: False
Do not wait for the container to stop, kill all tasks in the container.
Older LXC versions will stop containers like this irrespective of this
argument.
.. versionchanged:: 2015.5.0
Default value changed to ``False``
use_vt
run the command through VT
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.stop name
'''
_ensure_exists(name, path=path)
orig_state = state(name, path=path)
if orig_state == 'frozen' and not kill:
# Gracefully stopping a frozen container is slower than unfreezing and
# then stopping it (at least in my testing), so if we're not
# force-stopping the container, unfreeze it first.
unfreeze(name, path=path)
cmd = 'lxc-stop'
if kill:
cmd += ' -k'
ret = _change_state(cmd, name, 'stopped', use_vt=use_vt, path=path)
ret['state']['old'] = orig_state
return ret
def freeze(name, **kwargs):
'''
Freeze the named container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
start : False
If ``True`` and the container is stopped, the container will be started
before attempting to freeze.
.. versionadded:: 2015.5.0
use_vt
run the command through VT
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.freeze name
'''
use_vt = kwargs.get('use_vt', None)
path = kwargs.get('path', None)
_ensure_exists(name, path=path)
orig_state = state(name, path=path)
start_ = kwargs.get('start', False)
if orig_state == 'stopped':
if not start_:
raise CommandExecutionError(
'Container \'{0}\' is stopped'.format(name)
)
start(name, path=path)
cmd = 'lxc-freeze'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
ret = _change_state(cmd, name, 'frozen', use_vt=use_vt, path=path)
if orig_state == 'stopped' and start_:
ret['state']['old'] = orig_state
ret['started'] = True
ret['state']['new'] = state(name, path=path)
return ret
def unfreeze(name, path=None, use_vt=None):
'''
Unfreeze the named container.
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
use_vt
run the command through VT
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.unfreeze name
'''
_ensure_exists(name, path=path)
if state(name, path=path) == 'stopped':
raise CommandExecutionError(
'Container \'{0}\' is stopped'.format(name)
)
cmd = 'lxc-unfreeze'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
return _change_state(cmd, name, 'running', path=path, use_vt=use_vt)
def destroy(name, stop=False, path=None):
'''
Destroy the named container.
.. warning::
Destroys all data associated with the container.
path
path to the container parent directory (default: /var/lib/lxc)
.. versionadded:: 2015.8.0
stop : False
If ``True``, the container will be destroyed even if it is
running/frozen.
.. versionchanged:: 2015.5.0
Default value changed to ``False``. This more closely matches the
behavior of ``lxc-destroy(1)``, and also makes it less likely that
an accidental command will destroy a running container that was
being used for important things.
CLI Examples:
.. code-block:: bash
salt '*' lxc.destroy foo
salt '*' lxc.destroy foo stop=True
'''
_ensure_exists(name, path=path)
if not stop and state(name, path=path) != 'stopped':
raise CommandExecutionError(
'Container \'{0}\' is not stopped'.format(name)
)
return _change_state('lxc-destroy', name, None, path=path)
# Compatibility between LXC and nspawn
remove = salt.utils.functools.alias_function(destroy, 'remove')
def exists(name, path=None):
'''
Returns whether the named container exists.
path
path to the container parent directory (default: /var/lib/lxc)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.exists name
'''
_exists = name in ls_(path=path)
# container may be just created but we did cached earlier the
# lxc-ls results
if not _exists:
_exists = name in ls_(cache=False, path=path)
return _exists
def state(name, path=None):
'''
Returns the state of a container.
path
path to the container parent directory (default: /var/lib/lxc)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.state name
'''
# Don't use _ensure_exists() here, it will mess with _change_state()
cachekey = 'lxc.state.{0}{1}'.format(name, path)
try:
return __context__[cachekey]
except KeyError:
if not exists(name, path=path):
__context__[cachekey] = None
else:
cmd = 'lxc-info'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0}'.format(name)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
if ret['retcode'] != 0:
_clear_context()
raise CommandExecutionError(
'Unable to get state of container \'{0}\''.format(name)
)
c_infos = ret['stdout'].splitlines()
c_state = None
for c_info in c_infos:
stat = c_info.split(':')
if stat[0].lower() == 'state':
c_state = stat[1].strip().lower()
break
__context__[cachekey] = c_state
return __context__[cachekey]
def get_parameter(name, parameter, path=None):
'''
Returns the value of a cgroup parameter for a container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.get_parameter container_name memory.limit_in_bytes
'''
_ensure_exists(name, path=path)
cmd = 'lxc-cgroup'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0} {1}'.format(name, parameter)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
if ret['retcode'] != 0:
raise CommandExecutionError(
'Unable to retrieve value for \'{0}\''.format(parameter)
)
return ret['stdout'].strip()
def set_parameter(name, parameter, value, path=None):
'''
Set the value of a cgroup parameter for a container.
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.set_parameter name parameter value
'''
if not exists(name, path=path):
return None
cmd = 'lxc-cgroup'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0} {1} {2}'.format(name, parameter, value)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
if ret['retcode'] != 0:
return False
else:
return True
def info(name, path=None):
'''
Returns information about a container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.info name
'''
cachekey = 'lxc.info.{0}{1}'.format(name, path)
try:
return __context__[cachekey]
except KeyError:
_ensure_exists(name, path=path)
cpath = get_root_path(path)
try:
conf_file = os.path.join(cpath, name, 'config')
except AttributeError:
conf_file = os.path.join(cpath, six.text_type(name), 'config')
if not os.path.isfile(conf_file):
raise CommandExecutionError(
'LXC config file {0} does not exist'.format(conf_file)
)
ret = {}
config = []
with salt.utils.files.fopen(conf_file) as fp_:
for line in fp_:
line = salt.utils.stringutils.to_unicode(line)
comps = [x.strip() for x in
line.split('#', 1)[0].strip().split('=', 1)]
if len(comps) == 2:
config.append(tuple(comps))
ifaces = []
current = None
for key, val in config:
if key == 'lxc.network.type':
current = {'type': val}
ifaces.append(current)
elif not current:
continue
elif key.startswith('lxc.network.'):
current[key.replace('lxc.network.', '', 1)] = val
if ifaces:
ret['nics'] = ifaces
ret['rootfs'] = next(
(x[1] for x in config if x[0] == 'lxc.rootfs'),
None
)
ret['state'] = state(name, path=path)
ret['ips'] = []
ret['public_ips'] = []
ret['private_ips'] = []
ret['public_ipv4_ips'] = []
ret['public_ipv6_ips'] = []
ret['private_ipv4_ips'] = []
ret['private_ipv6_ips'] = []
ret['ipv4_ips'] = []
ret['ipv6_ips'] = []
ret['size'] = None
ret['config'] = conf_file
if ret['state'] == 'running':
try:
limit = int(get_parameter(name, 'memory.limit_in_bytes'))
except (CommandExecutionError, TypeError, ValueError):
limit = 0
try:
usage = int(get_parameter(name, 'memory.usage_in_bytes'))
except (CommandExecutionError, TypeError, ValueError):
usage = 0
free = limit - usage
ret['memory_limit'] = limit
ret['memory_free'] = free
size = run_stdout(name, 'df /', path=path, python_shell=False)
# The size is the 2nd column of the last line
ret['size'] = size.splitlines()[-1].split()[1]
# First try iproute2
ip_cmd = run_all(
name, 'ip link show', path=path, python_shell=False)
if ip_cmd['retcode'] == 0:
ip_data = ip_cmd['stdout']
ip_cmd = run_all(
name, 'ip addr show', path=path, python_shell=False)
ip_data += '\n' + ip_cmd['stdout']
ip_data = salt.utils.network._interfaces_ip(ip_data)
else:
# That didn't work, try ifconfig
ip_cmd = run_all(
name, 'ifconfig', path=path, python_shell=False)
if ip_cmd['retcode'] == 0:
ip_data = \
salt.utils.network._interfaces_ifconfig(
ip_cmd['stdout'])
else:
# Neither was successful, give up
log.warning(
'Unable to run ip or ifconfig in container \'%s\'', name
)
ip_data = {}
ret['ipv4_ips'] = salt.utils.network.ip_addrs(
include_loopback=True,
interface_data=ip_data
)
ret['ipv6_ips'] = salt.utils.network.ip_addrs6(
include_loopback=True,
interface_data=ip_data
)
ret['ips'] = ret['ipv4_ips'] + ret['ipv6_ips']
for address in ret['ipv4_ips']:
if address == '127.0.0.1':
ret['private_ips'].append(address)
ret['private_ipv4_ips'].append(address)
elif salt.utils.cloud.is_public_ip(address):
ret['public_ips'].append(address)
ret['public_ipv4_ips'].append(address)
else:
ret['private_ips'].append(address)
ret['private_ipv4_ips'].append(address)
for address in ret['ipv6_ips']:
if address == '::1' or address.startswith('fe80'):
ret['private_ips'].append(address)
ret['private_ipv6_ips'].append(address)
else:
ret['public_ips'].append(address)
ret['public_ipv6_ips'].append(address)
for key in [x for x in ret if x == 'ips' or x.endswith('ips')]:
ret[key].sort(key=_ip_sort)
__context__[cachekey] = ret
return __context__[cachekey]
def set_password(name, users, password, encrypted=True, path=None):
'''
.. versionchanged:: 2015.5.0
Function renamed from ``set_pass`` to ``set_password``. Additionally,
this function now supports (and defaults to using) a password hash
instead of a plaintext password.
Set the password of one or more system users inside containers
users
Comma-separated list (or python list) of users to change password
password
Password to set for the specified user(s)
encrypted : True
If true, ``password`` must be a password hash. Set to ``False`` to set
a plaintext password (not recommended).
.. versionadded:: 2015.5.0
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.set_pass container-name root '$6$uJ2uAyLU$KoI67t8As/0fXtJOPcHKGXmUpcoYUcVR2K6x93walnShTCQvjRwq25yIkiCBOqgbfdKQSFnAo28/ek6716vEV1'
salt '*' lxc.set_pass container-name root foo encrypted=False
'''
def _bad_user_input():
raise SaltInvocationError('Invalid input for \'users\' parameter')
if not isinstance(users, list):
try:
users = users.split(',')
except AttributeError:
_bad_user_input()
if not users:
_bad_user_input()
failed_users = []
for user in users:
result = retcode(name,
'chpasswd{0}'.format(' -e' if encrypted else ''),
stdin=':'.join((user, password)),
python_shell=False,
path=path,
chroot_fallback=True,
output_loglevel='quiet')
if result != 0:
failed_users.append(user)
if failed_users:
raise CommandExecutionError(
'Password change failed for the following user(s): {0}'
.format(', '.join(failed_users))
)
return True
set_pass = salt.utils.functools.alias_function(set_password, 'set_pass')
def update_lxc_conf(name, lxc_conf, lxc_conf_unset, path=None):
'''
Edit LXC configuration options
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.update_lxc_conf ubuntu \\
lxc_conf="[{'network.ipv4.ip':'10.0.3.5'}]" \\
lxc_conf_unset="['lxc.utsname']"
'''
_ensure_exists(name, path=path)
cpath = get_root_path(path)
lxc_conf_p = os.path.join(cpath, name, 'config')
if not os.path.exists(lxc_conf_p):
raise SaltInvocationError(
'Configuration file {0} does not exist'.format(lxc_conf_p)
)
changes = {'edited': [], 'added': [], 'removed': []}
ret = {'changes': changes, 'result': True, 'comment': ''}
# do not use salt.utils.files.fopen !
with salt.utils.files.fopen(lxc_conf_p, 'r') as fic:
filtered_lxc_conf = []
for row in lxc_conf:
if not row:
continue
for conf in row:
filtered_lxc_conf.append((conf.strip(),
row[conf].strip()))
ret['comment'] = 'lxc.conf is up to date'
lines = []
orig_config = salt.utils.stringutils.to_unicode(fic.read())
for line in orig_config.splitlines():
if line.startswith('#') or not line.strip():
lines.append([line, ''])
else:
line = line.split('=')
index = line.pop(0)
val = (index.strip(), '='.join(line).strip())
if val not in lines:
lines.append(val)
for key, item in filtered_lxc_conf:
matched = False
for idx, line in enumerate(lines[:]):
if line[0] == key:
matched = True
lines[idx] = (key, item)
if '='.join(line[1:]).strip() != item.strip():
changes['edited'].append(
({line[0]: line[1:]}, {key: item}))
break
if not matched:
if (key, item) not in lines:
lines.append((key, item))
changes['added'].append({key: item})
dest_lxc_conf = []
# filter unset
if lxc_conf_unset:
for line in lines:
for opt in lxc_conf_unset:
if (
not line[0].startswith(opt) and
line not in dest_lxc_conf
):
dest_lxc_conf.append(line)
else:
changes['removed'].append(opt)
else:
dest_lxc_conf = lines
conf = ''
for key, val in dest_lxc_conf:
if not val:
conf += '{0}\n'.format(key)
else:
conf += '{0} = {1}\n'.format(key.strip(), val.strip())
conf_changed = conf != orig_config
chrono = datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S')
if conf_changed:
# DO NOT USE salt.utils.files.fopen here, i got (kiorky)
# problems with lxc configs which were wiped !
with salt.utils.files.fopen('{0}.{1}'.format(lxc_conf_p, chrono), 'w') as wfic:
wfic.write(salt.utils.stringutils.to_str(conf))
with salt.utils.files.fopen(lxc_conf_p, 'w') as wfic:
wfic.write(salt.utils.stringutils.to_str(conf))
ret['comment'] = 'Updated'
ret['result'] = True
if not any(changes[x] for x in changes):
# Ensure an empty changes dict if nothing was modified
ret['changes'] = {}
return ret
def set_dns(name, dnsservers=None, searchdomains=None, path=None):
'''
.. versionchanged:: 2015.5.0
The ``dnsservers`` and ``searchdomains`` parameters can now be passed
as a comma-separated list.
Update /etc/resolv.confo
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.set_dns ubuntu "['8.8.8.8', '4.4.4.4']"
'''
if dnsservers is None:
dnsservers = ['8.8.8.8', '4.4.4.4']
elif not isinstance(dnsservers, list):
try:
dnsservers = dnsservers.split(',')
except AttributeError:
raise SaltInvocationError(
'Invalid input for \'dnsservers\' parameter'
)
if searchdomains is None:
searchdomains = []
elif not isinstance(searchdomains, list):
try:
searchdomains = searchdomains.split(',')
except AttributeError:
raise SaltInvocationError(
'Invalid input for \'searchdomains\' parameter'
)
dns = ['nameserver {0}'.format(x) for x in dnsservers]
dns.extend(['search {0}'.format(x) for x in searchdomains])
dns = '\n'.join(dns) + '\n'
# we may be using resolvconf in the container
# We need to handle that case with care:
# - we create the resolv.conf runtime directory (the
# linked directory) as anyway it will be shadowed when the real
# runned tmpfs mountpoint will be mounted.
# ( /etc/resolv.conf -> ../run/resolvconf/resolv.conf)
# Indeed, it can save us in any other case (running, eg, in a
# bare chroot when repairing or preparing the container for
# operation.
# - We also teach resolvconf to use the aforementioned dns.
# - We finally also set /etc/resolv.conf in all cases
rstr = __salt__['test.random_hash']()
# no tmp here, apparmor won't let us execute !
script = '/sbin/{0}_dns.sh'.format(rstr)
DNS_SCRIPT = "\n".join([
# 'set -x',
'#!/usr/bin/env bash',
'if [ -h /etc/resolv.conf ];then',
' if [ "x$(readlink /etc/resolv.conf)"'
' = "x../run/resolvconf/resolv.conf" ];then',
' if [ ! -d /run/resolvconf/ ];then',
' mkdir -p /run/resolvconf',
' fi',
' cat > /etc/resolvconf/resolv.conf.d/head <<EOF',
dns,
'EOF',
'',
' fi',
'fi',
'cat > /etc/resolv.conf <<EOF',
dns,
'EOF',
''])
result = run_all(
name, 'tee {0}'.format(script), path=path,
stdin=DNS_SCRIPT, python_shell=True)
if result['retcode'] == 0:
result = run_all(
name, 'sh -c "chmod +x {0};{0}"'.format(script),
path=path, python_shell=True)
# blindly delete the setter file
run_all(name,
'sh -c \'if [ -f "{0}" ];then rm -f "{0}";fi\''.format(script),
path=path, python_shell=True)
if result['retcode'] != 0:
error = ('Unable to write to /etc/resolv.conf in container \'{0}\''
.format(name))
if result['stderr']:
error += ': {0}'.format(result['stderr'])
raise CommandExecutionError(error)
return True
def running_systemd(name, cache=True, path=None):
'''
Determine if systemD is running
path
path to the container parent
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.running_systemd ubuntu
'''
k = 'lxc.systemd.test.{0}{1}'.format(name, path)
ret = __context__.get(k, None)
if ret is None or not cache:
rstr = __salt__['test.random_hash']()
# no tmp here, apparmor won't let us execute !
script = '/sbin/{0}_testsystemd.sh'.format(rstr)
# ubuntu already had since trusty some bits of systemd but was
# still using upstart ...
# we need to be a bit more careful that just testing that systemd
# is present
_script = textwrap.dedent(
'''\
#!/usr/bin/env bash
set -x
if ! command -v systemctl 1>/dev/null 2>/dev/null;then exit 2;fi
for i in \\
/run/systemd/journal/dev-log\\
/run/systemd/journal/flushed\\
/run/systemd/journal/kernel-seqnum\\
/run/systemd/journal/socket\\
/run/systemd/journal/stdout\\
/var/run/systemd/journal/dev-log\\
/var/run/systemd/journal/flushed\\
/var/run/systemd/journal/kernel-seqnum\\
/var/run/systemd/journal/socket\\
/var/run/systemd/journal/stdout\\
;do\\
if test -e ${i};then exit 0;fi
done
if test -d /var/systemd/system;then exit 0;fi
exit 2
''')
result = run_all(
name, 'tee {0}'.format(script), path=path,
stdin=_script, python_shell=True)
if result['retcode'] == 0:
result = run_all(name,
'sh -c "chmod +x {0};{0}"'''.format(script),
path=path,
python_shell=True)
else:
raise CommandExecutionError(
'lxc {0} failed to copy initd tester'.format(name))
run_all(name,
'sh -c \'if [ -f "{0}" ];then rm -f "{0}";fi\''
''.format(script),
path=path,
ignore_retcode=True,
python_shell=True)
if result['retcode'] != 0:
error = ('Unable to determine if the container \'{0}\''
' was running systemd, assmuming it is not.'
''.format(name))
if result['stderr']:
error += ': {0}'.format(result['stderr'])
# only cache result if we got a known exit code
if result['retcode'] in (0, 2):
__context__[k] = ret = not result['retcode']
return ret
def systemd_running_state(name, path=None):
'''
Get the operational state of a systemd based container
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.systemd_running_state ubuntu
'''
try:
ret = run_all(name,
'systemctl is-system-running',
path=path,
ignore_retcode=True)['stdout']
except CommandExecutionError:
ret = ''
return ret
def test_sd_started_state(name, path=None):
'''
Test if a systemd container is fully started
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.test_sd_started_state ubuntu
'''
qstate = systemd_running_state(name, path=path)
if qstate in ('initializing', 'starting'):
return False
elif qstate == '':
return None
else:
return True
def test_bare_started_state(name, path=None):
'''
Test if a non systemd container is fully started
For now, it consists only to test if the container is attachable
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.test_bare_started_state ubuntu
'''
try:
ret = run_all(
name, 'ls', path=path, ignore_retcode=True
)['retcode'] == 0
except (CommandExecutionError,):
ret = None
return ret
def wait_started(name, path=None, timeout=300):
'''
Check that the system has fully inited
This is actually very important for systemD based containers
see https://github.com/saltstack/salt/issues/23847
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.wait_started ubuntu
'''
if not exists(name, path=path):
raise CommandExecutionError(
'Container {0} does does exists'.format(name))
if not state(name, path=path) == 'running':
raise CommandExecutionError(
'Container {0} is not running'.format(name))
ret = False
if running_systemd(name, path=path):
test_started = test_sd_started_state
logger = log.error
else:
test_started = test_bare_started_state
logger = log.debug
now = time.time()
expire = now + timeout
now = time.time()
started = test_started(name, path=path)
while time.time() < expire and not started:
time.sleep(0.3)
started = test_started(name, path=path)
if started is None:
logger(
'Assuming %s is started, although we failed to detect that'
' is fully started correctly', name)
ret = True
else:
ret = started
return ret
def _needs_install(name, path=None):
ret = 0
has_minion = retcode(name,
'which salt-minion',
path=path,
ignore_retcode=True)
# we assume that installing is when no minion is running
# but testing the executable presence is not enougth for custom
# installs where the bootstrap can do much more than installing
# the bare salt binaries.
if has_minion:
processes = run_stdout(name, "ps aux", path=path)
if 'salt-minion' not in processes:
ret = 1
else:
retcode(name, 'salt-call --local service.stop salt-minion')
else:
ret = 1
return ret
def bootstrap(name,
config=None,
approve_key=True,
install=True,
pub_key=None,
priv_key=None,
bootstrap_url=None,
force_install=False,
unconditional_install=False,
path=None,
bootstrap_delay=None,
bootstrap_args=None,
bootstrap_shell=None):
'''
Install and configure salt in a container.
config
Minion configuration options. By default, the ``master`` option is set
to the target host's master.
approve_key
Request a pre-approval of the generated minion key. Requires
that the salt-master be configured to either auto-accept all keys or
expect a signing request from the target host. Default: ``True``
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
pub_key
Explicit public key to pressed the minion with (optional).
This can be either a filepath or a string representing the key
priv_key
Explicit private key to pressed the minion with (optional).
This can be either a filepath or a string representing the key
bootstrap_delay
Delay in seconds between end of container creation and bootstrapping.
Useful when waiting for container to obtain a DHCP lease.
.. versionadded:: 2015.5.0
bootstrap_url
url, content or filepath to the salt bootstrap script
bootstrap_args
salt bootstrap script arguments
bootstrap_shell
shell to execute the script into
install
Whether to attempt a full installation of salt-minion if needed.
force_install
Force installation even if salt-minion is detected,
this is the way to run vendor bootstrap scripts even
if a salt minion is already present in the container
unconditional_install
Run the script even if the container seems seeded
CLI Examples:
.. code-block:: bash
salt 'minion' lxc.bootstrap container_name [config=config_data] \\
[approve_key=(True|False)] [install=(True|False)]
'''
wait_started(name, path=path)
if bootstrap_delay is not None:
try:
log.info('LXC %s: bootstrap_delay: %s', name, bootstrap_delay)
time.sleep(bootstrap_delay)
except TypeError:
# Bad input, but assume since a value was passed that
# a delay was desired, and sleep for 5 seconds
time.sleep(5)
c_info = info(name, path=path)
if not c_info:
return None
# default set here as we cannot set them
# in def as it can come from a chain of procedures.
if bootstrap_args:
# custom bootstrap args can be totally customized, and user could
# have inserted the placeholder for the config directory.
# For example, some salt bootstrap script do not use at all -c
if '{0}' not in bootstrap_args:
bootstrap_args += ' -c {0}'
else:
bootstrap_args = '-c {0}'
if not bootstrap_shell:
bootstrap_shell = 'sh'
orig_state = _ensure_running(name, path=path)
if not orig_state:
return orig_state
if not force_install:
needs_install = _needs_install(name, path=path)
else:
needs_install = True
seeded = retcode(name,
'test -e \'{0}\''.format(SEED_MARKER),
path=path,
chroot_fallback=True,
ignore_retcode=True) == 0
tmp = tempfile.mkdtemp()
if seeded and not unconditional_install:
ret = True
else:
ret = False
cfg_files = __salt__['seed.mkconfig'](
config, tmp=tmp, id_=name, approve_key=approve_key,
pub_key=pub_key, priv_key=priv_key)
if needs_install or force_install or unconditional_install:
if install:
rstr = __salt__['test.random_hash']()
configdir = '/var/tmp/.c_{0}'.format(rstr)
cmd = 'install -m 0700 -d {0}'.format(configdir)
if run_all(
name, cmd, path=path, python_shell=False
)['retcode'] != 0:
log.error('tmpdir %s creation failed %s', configdir, cmd)
return False
bs_ = __salt__['config.gather_bootstrap_script'](
bootstrap=bootstrap_url)
script = '/sbin/{0}_bootstrap.sh'.format(rstr)
copy_to(name, bs_, script, path=path)
result = run_all(name,
'sh -c "chmod +x {0}"'.format(script),
path=path,
python_shell=True)
copy_to(name, cfg_files['config'],
os.path.join(configdir, 'minion'),
path=path)
copy_to(name, cfg_files['privkey'],
os.path.join(configdir, 'minion.pem'),
path=path)
copy_to(name, cfg_files['pubkey'],
os.path.join(configdir, 'minion.pub'),
path=path)
bootstrap_args = bootstrap_args.format(configdir)
cmd = ('{0} {2} {1}'
.format(bootstrap_shell,
bootstrap_args.replace("'", "''"),
script))
# log ASAP the forged bootstrap command which can be wrapped
# out of the output in case of unexpected problem
log.info('Running %s in LXC container \'%s\'', cmd, name)
ret = retcode(name, cmd, output_loglevel='info',
path=path, use_vt=True) == 0
run_all(name,
'sh -c \'if [ -f "{0}" ];then rm -f "{0}";fi\''
''.format(script),
path=path,
ignore_retcode=True,
python_shell=True)
else:
ret = False
else:
minion_config = salt.config.minion_config(cfg_files['config'])
pki_dir = minion_config['pki_dir']
copy_to(name,
cfg_files['config'],
'/etc/salt/minion',
path=path)
copy_to(name,
cfg_files['privkey'],
os.path.join(pki_dir, 'minion.pem'),
path=path)
copy_to(name,
cfg_files['pubkey'],
os.path.join(pki_dir, 'minion.pub'),
path=path)
run(name,
'salt-call --local service.enable salt-minion',
path=path,
python_shell=False)
ret = True
shutil.rmtree(tmp)
if orig_state == 'stopped':
stop(name, path=path)
elif orig_state == 'frozen':
freeze(name, path=path)
# mark seeded upon successful install
if ret:
run(name,
'touch \'{0}\''.format(SEED_MARKER),
path=path,
python_shell=False)
return ret
def attachable(name, path=None):
'''
Return True if the named container can be attached to via the lxc-attach
command
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt 'minion' lxc.attachable ubuntu
'''
cachekey = 'lxc.attachable{0}{1}'.format(name, path)
try:
return __context__[cachekey]
except KeyError:
_ensure_exists(name, path=path)
# Can't use run() here because it uses attachable() and would
# endlessly recurse, resulting in a traceback
log.debug('Checking if LXC container %s is attachable', name)
cmd = 'lxc-attach'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' --clear-env -n {0} -- /usr/bin/env'.format(name)
result = __salt__['cmd.retcode'](cmd,
python_shell=False,
output_loglevel='quiet',
ignore_retcode=True) == 0
__context__[cachekey] = result
return __context__[cachekey]
def _run(name,
cmd,
output=None,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=None,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
Common logic for lxc.run functions
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
'''
orig_state = state(name, path=path)
try:
if attachable(name, path=path):
ret = __salt__['container_resource.run'](
name,
cmd,
path=path,
container_type=__virtualname__,
exec_driver=EXEC_DRIVER,
output=output,
no_start=no_start,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
ignore_retcode=ignore_retcode,
use_vt=use_vt,
keep_env=keep_env)
else:
if not chroot_fallback:
raise CommandExecutionError(
'{0} is not attachable.'.format(name))
rootfs = info(name, path=path).get('rootfs')
# Set context var to make cmd.run_chroot run cmd.run instead of
# cmd.run_all.
__context__['cmd.run_chroot.func'] = __salt__['cmd.run']
ret = __salt__['cmd.run_chroot'](rootfs,
cmd,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
ignore_retcode=ignore_retcode)
except Exception:
raise
finally:
# Make sure we honor preserve_state, even if there was an exception
new_state = state(name, path=path)
if preserve_state:
if orig_state == 'stopped' and new_state != 'stopped':
stop(name, path=path)
elif orig_state == 'frozen' and new_state != 'frozen':
freeze(name, start=True, path=path)
if output in (None, 'all'):
return ret
else:
return ret[output]
def run(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.8.0
Run :mod:`cmd.run <salt.modules.cmdmod.run>` within a container
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed in stderr if the command being run
does not exist. If no output is returned using this function, try using
:mod:`lxc.run_stderr <salt.modules.lxc.run_stderr>` or
:mod:`lxc.run_all <salt.modules.lxc.run_all>`.
name
Name of the container in which to run the command
cmd
Command to run
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console. Assumes
``output=all``.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
CLI Example:
.. code-block:: bash
salt myminion lxc.run mycontainer 'ifconfig -a'
'''
return _run(name,
cmd,
path=path,
output=None,
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def run_stdout(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.5.0
Run :mod:`cmd.run_stdout <salt.modules.cmdmod.run_stdout>` within a container
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed in stderr if the command being run
does not exist. If no output is returned using this function, try using
:mod:`lxc.run_stderr <salt.modules.lxc.run_stderr>` or
:mod:`lxc.run_all <salt.modules.lxc.run_all>`.
name
Name of the container in which to run the command
cmd
Command to run
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console
``output=all``.
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
CLI Example:
.. code-block:: bash
salt myminion lxc.run_stdout mycontainer 'ifconfig -a'
'''
return _run(name,
cmd,
path=path,
output='stdout',
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def run_stderr(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.5.0
Run :mod:`cmd.run_stderr <salt.modules.cmdmod.run_stderr>` within a container
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed if the command being run does not
exist.
name
Name of the container in which to run the command
cmd
Command to run
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console
``output=all``.
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
CLI Example:
.. code-block:: bash
salt myminion lxc.run_stderr mycontainer 'ip addr show'
'''
return _run(name,
cmd,
path=path,
output='stderr',
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def retcode(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.5.0
Run :mod:`cmd.retcode <salt.modules.cmdmod.retcode>` within a container
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed in stderr if the command being run
does not exist. If the retcode is nonzero and not what was expected,
try using :mod:`lxc.run_stderr <salt.modules.lxc.run_stderr>`
or :mod:`lxc.run_all <salt.modules.lxc.run_all>`.
name
Name of the container in which to run the command
cmd
Command to run
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console
``output=all``.
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
CLI Example:
.. code-block:: bash
salt myminion lxc.retcode mycontainer 'ip addr show'
'''
return _run(name,
cmd,
output='retcode',
path=path,
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def run_all(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.5.0
Run :mod:`cmd.run_all <salt.modules.cmdmod.run_all>` within a container
.. note::
While the command is run within the container, it is initiated from the
host. Therefore, the PID in the return dict is from the host, not from
the container.
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed in stderr if the command being run
does not exist.
name
Name of the container in which to run the command
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
cmd
Command to run
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console
``output=all``.
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
CLI Example:
.. code-block:: bash
salt myminion lxc.run_all mycontainer 'ip addr show'
'''
return _run(name,
cmd,
output='all',
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
path=path,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def _get_md5(name, path):
'''
Get the MD5 checksum of a file from a container
'''
output = run_stdout(name, 'md5sum "{0}"'.format(path),
chroot_fallback=True,
ignore_retcode=True)
try:
return output.split()[0]
except IndexError:
# Destination file does not exist or could not be accessed
return None
def copy_to(name, source, dest, overwrite=False, makedirs=False, path=None):
'''
.. versionchanged:: 2015.8.0
Function renamed from ``lxc.cp`` to ``lxc.copy_to`` for consistency
with other container types. ``lxc.cp`` will continue to work, however.
For versions 2015.2.x and earlier, use ``lxc.cp``.
Copy a file or directory from the host into a container
name
Container name
source
File to be copied to the container
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
dest
Destination on the container. Must be an absolute path.
.. versionchanged:: 2015.5.0
If the destination is a directory, the file will be copied into
that directory.
overwrite : False
Unless this option is set to ``True``, then if a file exists at the
location specified by the ``dest`` argument, an error will be raised.
.. versionadded:: 2015.8.0
makedirs : False
Create the parent directory on the container if it does not already
exist.
.. versionadded:: 2015.5.0
CLI Example:
.. code-block:: bash
salt 'minion' lxc.copy_to /tmp/foo /root/foo
salt 'minion' lxc.cp /tmp/foo /root/foo
'''
_ensure_running(name, no_start=True, path=path)
return __salt__['container_resource.copy_to'](
name,
source,
dest,
container_type=__virtualname__,
path=path,
exec_driver=EXEC_DRIVER,
overwrite=overwrite,
makedirs=makedirs)
cp = salt.utils.functools.alias_function(copy_to, 'cp')
def read_conf(conf_file, out_format='simple'):
'''
Read in an LXC configuration file. By default returns a simple, unsorted
dict, but can also return a more detailed structure including blank lines
and comments.
out_format:
set to 'simple' if you need the old and unsupported behavior.
This won't support the multiple lxc values (eg: multiple network nics)
CLI Examples:
.. code-block:: bash
salt 'minion' lxc.read_conf /etc/lxc/mycontainer.conf
salt 'minion' lxc.read_conf /etc/lxc/mycontainer.conf out_format=commented
'''
ret_commented = []
ret_simple = {}
with salt.utils.files.fopen(conf_file, 'r') as fp_:
for line in salt.utils.data.decode(fp_.readlines()):
if '=' not in line:
ret_commented.append(line)
continue
comps = line.split('=')
value = '='.join(comps[1:]).strip()
comment = None
if value.strip().startswith('#'):
vcomps = value.strip().split('#')
value = vcomps[1].strip()
comment = '#'.join(vcomps[1:]).strip()
ret_commented.append({comps[0].strip(): {
'value': value,
'comment': comment,
}})
else:
ret_commented.append({comps[0].strip(): value})
ret_simple[comps[0].strip()] = value
if out_format == 'simple':
return ret_simple
return ret_commented
def write_conf(conf_file, conf):
'''
Write out an LXC configuration file
This is normally only used internally. The format of the data structure
must match that which is returned from ``lxc.read_conf()``, with
``out_format`` set to ``commented``.
An example might look like:
.. code-block:: python
[
{'lxc.utsname': '$CONTAINER_NAME'},
'# This is a commented line\\n',
'\\n',
{'lxc.mount': '$CONTAINER_FSTAB'},
{'lxc.rootfs': {'comment': 'This is another test',
'value': 'This is another test'}},
'\\n',
{'lxc.network.type': 'veth'},
{'lxc.network.flags': 'up'},
{'lxc.network.link': 'br0'},
{'lxc.network.mac': '$CONTAINER_MACADDR'},
{'lxc.network.ipv4': '$CONTAINER_IPADDR'},
{'lxc.network.name': '$CONTAINER_DEVICENAME'},
]
CLI Example:
.. code-block:: bash
salt 'minion' lxc.write_conf /etc/lxc/mycontainer.conf \\
out_format=commented
'''
if not isinstance(conf, list):
raise SaltInvocationError('Configuration must be passed as a list')
# construct the content prior to write to the file
# to avoid half written configs
content = ''
for line in conf:
if isinstance(line, (six.text_type, six.string_types)):
content += line
elif isinstance(line, dict):
for key in list(line.keys()):
out_line = None
if isinstance(
line[key],
(six.text_type, six.string_types, six.integer_types, float)
):
out_line = ' = '.join((key, "{0}".format(line[key])))
elif isinstance(line[key], dict):
out_line = ' = '.join((key, line[key]['value']))
if 'comment' in line[key]:
out_line = ' # '.join((out_line, line[key]['comment']))
if out_line:
content += out_line
content += '\n'
with salt.utils.files.fopen(conf_file, 'w') as fp_:
fp_.write(salt.utils.stringutils.to_str(content))
return {}
def edit_conf(conf_file,
out_format='simple',
read_only=False,
lxc_config=None,
**kwargs):
'''
Edit an LXC configuration file. If a setting is already present inside the
file, its value will be replaced. If it does not exist, it will be appended
to the end of the file. Comments and blank lines will be kept in-tact if
they already exist in the file.
out_format:
Set to simple if you need backward compatibility (multiple items for a
simple key is not supported)
read_only:
return only the edited configuration without applying it
to the underlying lxc configuration file
lxc_config:
List of dict containning lxc configuration items
For network configuration, you also need to add the device it belongs
to, otherwise it will default to eth0.
Also, any change to a network parameter will result in the whole
network reconfiguration to avoid mismatchs, be aware of that !
After the file is edited, its contents will be returned. By default, it
will be returned in ``simple`` format, meaning an unordered dict (which
may not represent the actual file order). Passing in an ``out_format`` of
``commented`` will return a data structure which accurately represents the
order and content of the file.
CLI Example:
.. code-block:: bash
salt 'minion' lxc.edit_conf /etc/lxc/mycontainer.conf \\
out_format=commented lxc.network.type=veth
salt 'minion' lxc.edit_conf /etc/lxc/mycontainer.conf \\
out_format=commented \\
lxc_config="[{'lxc.network.name': 'eth0', \\
'lxc.network.ipv4': '1.2.3.4'},
{'lxc.network.name': 'eth2', \\
'lxc.network.ipv4': '1.2.3.5',\\
'lxc.network.gateway': '1.2.3.1'}]"
'''
data = []
try:
conf = read_conf(conf_file, out_format=out_format)
except Exception:
conf = []
if not lxc_config:
lxc_config = []
lxc_config = copy.deepcopy(lxc_config)
# search if we want to access net config
# in that case, we will replace all the net configuration
net_config = []
for lxc_kws in lxc_config + [kwargs]:
net_params = {}
for kwarg in [a for a in lxc_kws]:
if kwarg.startswith('__'):
continue
if kwarg.startswith('lxc.network.'):
net_params[kwarg] = lxc_kws[kwarg]
lxc_kws.pop(kwarg, None)
if net_params:
net_config.append(net_params)
nic_opts = salt.utils.odict.OrderedDict()
for params in net_config:
dev = params.get('lxc.network.name', DEFAULT_NIC)
dev_opts = nic_opts.setdefault(dev, salt.utils.odict.OrderedDict())
for param in params:
opt = param.replace('lxc.network.', '')
opt = {'hwaddr': 'mac'}.get(opt, opt)
dev_opts[opt] = params[param]
net_changes = []
if nic_opts:
net_changes = _config_list(conf, only_net=True,
**{'network_profile': DEFAULT_NIC,
'nic_opts': nic_opts})
if net_changes:
lxc_config.extend(net_changes)
for line in conf:
if not isinstance(line, dict):
data.append(line)
continue
else:
for key in list(line.keys()):
val = line[key]
if net_changes and key.startswith('lxc.network.'):
continue
found = False
for ix in range(len(lxc_config)):
kw = lxc_config[ix]
if key in kw:
found = True
data.append({key: kw[key]})
del kw[key]
if not found:
data.append({key: val})
for lxc_kws in lxc_config:
for kwarg in lxc_kws:
data.append({kwarg: lxc_kws[kwarg]})
if read_only:
return data
write_conf(conf_file, data)
return read_conf(conf_file, out_format)
def reboot(name, path=None):
'''
Reboot a container.
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Examples:
.. code-block:: bash
salt 'minion' lxc.reboot myvm
'''
ret = {'result': True,
'changes': {},
'comment': '{0} rebooted'.format(name)}
does_exist = exists(name, path=path)
if does_exist and (state(name, path=path) == 'running'):
try:
stop(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
ret['result'] = False
return ret
if does_exist and (state(name, path=path) != 'running'):
try:
start(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
ret['result'] = False
return ret
ret['changes'][name] = 'rebooted'
return ret
def reconfigure(name,
cpu=None,
cpuset=None,
cpushare=None,
memory=None,
profile=None,
network_profile=None,
nic_opts=None,
bridge=None,
gateway=None,
autostart=None,
utsname=None,
rootfs=None,
path=None,
**kwargs):
'''
Reconfigure a container.
This only applies to a few property
name
Name of the container.
utsname
utsname of the container.
.. versionadded:: 2016.3.0
rootfs
rootfs of the container.
.. versionadded:: 2016.3.0
cpu
Select a random number of cpu cores and assign it to the cpuset, if the
cpuset option is set then this option will be ignored
cpuset
Explicitly define the cpus this container will be bound to
cpushare
cgroups cpu shares.
autostart
autostart container on reboot
memory
cgroups memory limit, in MB.
(0 for nolimit, None for old default 1024MB)
gateway
the ipv4 gateway to use
the default does nothing more than lxcutils does
bridge
the bridge to use
the default does nothing more than lxcutils does
nic
Network interfaces profile (defined in config or pillar).
nic_opts
Extra options for network interfaces, will override
``{"eth0": {"mac": "aa:bb:cc:dd:ee:ff", "ipv4": "10.1.1.1", "ipv6": "2001:db8::ff00:42:8329"}}``
or
``{"eth0": {"mac": "aa:bb:cc:dd:ee:ff", "ipv4": "10.1.1.1/24", "ipv6": "2001:db8::ff00:42:8329"}}``
path
path to the container parent
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt-call -lall mc_lxc_fork.reconfigure foobar nic_opts="{'eth1': {'mac': '00:16:3e:dd:ee:44'}}" memory=4
'''
changes = {}
cpath = get_root_path(path)
path = os.path.join(cpath, name, 'config')
ret = {'name': name,
'comment': 'config for {0} up to date'.format(name),
'result': True,
'changes': changes}
profile = get_container_profile(copy.deepcopy(profile))
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, _marker)
profile_match = profile.pop(key, default)
# let kwarg overrides be the preferred choice
if kw_overrides_match is _marker:
return profile_match
return kw_overrides_match
if nic_opts is not None and not network_profile:
network_profile = DEFAULT_NIC
if autostart is not None:
autostart = select('autostart', autostart)
else:
autostart = 'keep'
if not utsname:
utsname = select('utsname', utsname)
if os.path.exists(path):
old_chunks = read_conf(path, out_format='commented')
make_kw = salt.utils.odict.OrderedDict([
('utsname', utsname),
('rootfs', rootfs),
('autostart', autostart),
('cpu', cpu),
('gateway', gateway),
('cpuset', cpuset),
('cpushare', cpushare),
('network_profile', network_profile),
('nic_opts', nic_opts),
('bridge', bridge)])
# match 0 and none as memory = 0 in lxc config is harmful
if memory:
make_kw['memory'] = memory
kw = salt.utils.odict.OrderedDict()
for key, val in six.iteritems(make_kw):
if val is not None:
kw[key] = val
new_cfg = _config_list(conf_tuples=old_chunks, **kw)
if new_cfg:
edit_conf(path, out_format='commented', lxc_config=new_cfg)
chunks = read_conf(path, out_format='commented')
if old_chunks != chunks:
ret['comment'] = '{0} lxc config updated'.format(name)
if state(name, path=path) == 'running':
cret = reboot(name, path=path)
ret['result'] = cret['result']
return ret
def apply_network_profile(name, network_profile, nic_opts=None, path=None):
'''
.. versionadded:: 2015.5.0
Apply a network profile to a container
network_profile
profile name or default values (dict)
nic_opts
values to override in defaults (dict)
indexed by nic card names
path
path to the container parent
.. versionadded:: 2015.8.0
CLI Examples:
.. code-block:: bash
salt 'minion' lxc.apply_network_profile web1 centos
salt 'minion' lxc.apply_network_profile web1 centos \\
nic_opts="{'eth0': {'mac': 'xx:xx:xx:xx:xx:xx'}}"
salt 'minion' lxc.apply_network_profile web1 \\
"{'eth0': {'mac': 'xx:xx:xx:xx:xx:yy'}}"
nic_opts="{'eth0': {'mac': 'xx:xx:xx:xx:xx:xx'}}"
The special case to disable use of ethernet nics:
.. code-block:: bash
salt 'minion' lxc.apply_network_profile web1 centos \\
"{eth0: {disable: true}}"
'''
cpath = get_root_path(path)
cfgpath = os.path.join(cpath, name, 'config')
before = []
with salt.utils.files.fopen(cfgpath, 'r') as fp_:
for line in fp_:
before.append(line)
lxcconfig = _LXCConfig(name=name, path=path)
old_net = lxcconfig._filter_data('lxc.network')
network_params = {}
for param in _network_conf(
conf_tuples=old_net,
network_profile=network_profile, nic_opts=nic_opts
):
network_params.update(param)
if network_params:
edit_conf(cfgpath, out_format='commented', **network_params)
after = []
with salt.utils.files.fopen(cfgpath, 'r') as fp_:
for line in fp_:
after.append(line)
diff = ''
for line in difflib.unified_diff(before,
after,
fromfile='before',
tofile='after'):
diff += line
return diff
def get_pid(name, path=None):
'''
Returns a container pid.
Throw an exception if the container isn't running.
CLI Example:
.. code-block:: bash
salt '*' lxc.get_pid name
'''
if name not in list_(limit='running', path=path):
raise CommandExecutionError('Container {0} is not running, can\'t determine PID'.format(name))
info = __salt__['cmd.run']('lxc-info -n {0}'.format(name)).split("\n")
pid = [line.split(':')[1].strip() for line in info if re.match(r'\s*PID', line)][0]
return pid
def add_veth(name, interface_name, bridge=None, path=None):
'''
Add a veth to a container.
Note : this function doesn't update the container config, just add the interface at runtime
name
Name of the container
interface_name
Name of the interface in the container
bridge
Name of the bridge to attach the interface to (facultative)
CLI Examples:
.. code-block:: bash
salt '*' lxc.add_veth container_name eth1 br1
salt '*' lxc.add_veth container_name eth1
'''
# Get container init PID
pid = get_pid(name, path=path)
# Generate a ramdom string for veth and ensure that is isn't present on the system
while True:
random_veth = 'veth'+''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(6))
if random_veth not in __salt__['network.interfaces']().keys():
break
# Check prerequisites
if not __salt__['file.directory_exists']('/var/run/'):
raise CommandExecutionError('Directory /var/run required for lxc.add_veth doesn\'t exists')
if not __salt__['file.file_exists']('/proc/{0}/ns/net'.format(pid)):
raise CommandExecutionError('Proc file for container {0} network namespace doesn\'t exists'.format(name))
if not __salt__['file.directory_exists']('/var/run/netns'):
__salt__['file.mkdir']('/var/run/netns')
# Ensure that the symlink is up to date (change on container restart)
if __salt__['file.is_link']('/var/run/netns/{0}'.format(name)):
__salt__['file.remove']('/var/run/netns/{0}'.format(name))
__salt__['file.symlink']('/proc/{0}/ns/net'.format(pid), '/var/run/netns/{0}'.format(name))
# Ensure that interface doesn't exists
interface_exists = 0 == __salt__['cmd.retcode']('ip netns exec {netns} ip address list {interface}'.format(
netns=name,
interface=interface_name
))
if interface_exists:
raise CommandExecutionError('Interface {interface} already exists in {container}'.format(
interface=interface_name,
container=name
))
# Create veth and bring it up
if __salt__['cmd.retcode']('ip link add name {veth} type veth peer name {veth}_c'.format(veth=random_veth)) != 0:
raise CommandExecutionError('Error while creating the veth pair {0}'.format(random_veth))
if __salt__['cmd.retcode']('ip link set dev {0} up'.format(random_veth)) != 0:
raise CommandExecutionError('Error while bringing up host-side veth {0}'.format(random_veth))
# Attach it to the container
attached = 0 == __salt__['cmd.retcode']('ip link set dev {veth}_c netns {container} name {interface_name}'.format(
veth=random_veth,
container=name,
interface_name=interface_name
))
if not attached:
raise CommandExecutionError('Error while attaching the veth {veth} to container {container}'.format(
veth=random_veth,
container=name
))
__salt__['file.remove']('/var/run/netns/{0}'.format(name))
if bridge is not None:
__salt__['bridge.addif'](bridge, random_veth)
|
saltstack/salt
|
salt/modules/lxc.py
|
_get_base
|
python
|
def _get_base(**kwargs):
'''
If the needed base does not exist, then create it, if it does exist
create nothing and return the name of the base lxc container so
it can be cloned.
'''
profile = get_container_profile(copy.deepcopy(kwargs.get('profile')))
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, _marker)
profile_match = profile.pop(key, default)
# let kwarg overrides be the preferred choice
if kw_overrides_match is _marker:
return profile_match
return kw_overrides_match
template = select('template')
image = select('image')
vgname = select('vgname')
path = kwargs.get('path', None)
# remove the above three variables from kwargs, if they exist, to avoid
# duplicates if create() is invoked below.
for param in ('path', 'image', 'vgname', 'template'):
kwargs.pop(param, None)
if image:
proto = _urlparse(image).scheme
img_tar = __salt__['cp.cache_file'](image)
img_name = os.path.basename(img_tar)
hash_ = salt.utils.hashutils.get_hash(
img_tar,
__salt__['config.get']('hash_type'))
name = '__base_{0}_{1}_{2}'.format(proto, img_name, hash_)
if not exists(name, path=path):
create(name, template=template, image=image,
path=path, vgname=vgname, **kwargs)
if vgname:
rootfs = os.path.join('/dev', vgname, name)
edit_conf(info(name, path=path)['config'],
out_format='commented', **{'lxc.rootfs': rootfs})
return name
elif template:
name = '__base_{0}'.format(template)
if not exists(name, path=path):
create(name, template=template, image=image, path=path,
vgname=vgname, **kwargs)
if vgname:
rootfs = os.path.join('/dev', vgname, name)
edit_conf(info(name, path=path)['config'],
out_format='commented', **{'lxc.rootfs': rootfs})
return name
return ''
|
If the needed base does not exist, then create it, if it does exist
create nothing and return the name of the base lxc container so
it can be cloned.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/lxc.py#L1070-L1122
| null |
# -*- coding: utf-8 -*-
'''
Control Linux Containers via Salt
:depends: lxc package for distribution
lxc >= 1.0 (even beta alpha) is required
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import datetime
import copy
import string
import textwrap
import difflib
import logging
import tempfile
import os
import pipes
import time
import shutil
import re
import random
# Import salt libs
import salt.utils.args
import salt.utils.cloud
import salt.utils.data
import salt.utils.dictupdate
import salt.utils.files
import salt.utils.functools
import salt.utils.hashutils
import salt.utils.network
import salt.utils.odict
import salt.utils.path
import salt.utils.stringutils
from salt.exceptions import CommandExecutionError, SaltInvocationError
import salt.config
from salt.utils.versions import LooseVersion as _LooseVersion
# Import 3rd-party libs
from salt.ext import six
# pylint: disable=import-error,no-name-in-module
from salt.ext.six.moves import range # pylint: disable=redefined-builtin
from salt.ext.six.moves.urllib.parse import urlparse as _urlparse
# pylint: enable=import-error,no-name-in-module
# Set up logging
log = logging.getLogger(__name__)
# Don't shadow built-in's.
__func_alias__ = {
'list_': 'list',
'ls_': 'ls'
}
__virtualname__ = 'lxc'
DEFAULT_NIC = 'eth0'
DEFAULT_BR = 'br0'
SEED_MARKER = '/lxc.initial_seed'
EXEC_DRIVER = 'lxc-attach'
DEFAULT_PATH = '/var/lib/lxc'
_marker = object()
def __virtual__():
if salt.utils.path.which('lxc-start'):
return __virtualname__
# To speed up the whole thing, we decided to not use the
# subshell way and assume things are in place for lxc
# Discussion made by @kiorky and @thatch45
# lxc-version presence is not sufficient, in lxc1.0 alpha
# (precise backports), we have it and it is sufficient
# for the module to execute.
# elif salt.utils.path.which('lxc-version'):
# passed = False
# try:
# passed = subprocess.check_output(
# 'lxc-version').split(':')[1].strip() >= '1.0'
# except Exception:
# pass
# if not passed:
# log.warning('Support for lxc < 1.0 may be incomplete.')
# return 'lxc'
# return False
#
return (False, 'The lxc execution module cannot be loaded: the lxc-start binary is not in the path.')
def get_root_path(path):
'''
Get the configured lxc root for containers
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.get_root_path
'''
if not path:
path = __opts__.get('lxc.root_path', DEFAULT_PATH)
return path
def version():
'''
Return the actual lxc client version
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.version
'''
k = 'lxc.version'
if not __context__.get(k, None):
cversion = __salt__['cmd.run_all']('lxc-info --version')
if not cversion['retcode']:
ver = _LooseVersion(cversion['stdout'])
if ver < _LooseVersion('1.0'):
raise CommandExecutionError('LXC should be at least 1.0')
__context__[k] = "{0}".format(ver)
return __context__.get(k, None)
def _clear_context():
'''
Clear any lxc variables set in __context__
'''
for var in [x for x in __context__ if x.startswith('lxc.')]:
log.trace('Clearing __context__[\'%s\']', var)
__context__.pop(var, None)
def _ip_sort(ip):
'''Ip sorting'''
idx = '001'
if ip == '127.0.0.1':
idx = '200'
if ip == '::1':
idx = '201'
elif '::' in ip:
idx = '100'
return '{0}___{1}'.format(idx, ip)
def search_lxc_bridges():
'''
Search which bridges are potentially available as LXC bridges
CLI Example:
.. code-block:: bash
salt '*' lxc.search_lxc_bridges
'''
bridges = __context__.get('lxc.bridges', None)
# either match not yet called or no bridges were found
# to handle the case where lxc was not installed on the first
# call
if not bridges:
bridges = set()
running_bridges = set()
bridges.add(DEFAULT_BR)
try:
output = __salt__['cmd.run_all']('brctl show')
for line in output['stdout'].splitlines()[1:]:
if not line.startswith(' '):
running_bridges.add(line.split()[0].strip())
except (SaltInvocationError, CommandExecutionError):
pass
for ifc, ip in six.iteritems(
__grains__.get('ip_interfaces', {})
):
if ifc in running_bridges:
bridges.add(ifc)
elif os.path.exists(
'/sys/devices/virtual/net/{0}/bridge'.format(ifc)
):
bridges.add(ifc)
bridges = list(bridges)
# if we found interfaces that have lxc in their names
# we filter them as being the potential lxc bridges
# we also try to default on br0 on other cases
def sort_bridges(a):
pref = 'z'
if 'lxc' in a:
pref = 'a'
elif 'br0' == a:
pref = 'c'
return '{0}_{1}'.format(pref, a)
bridges.sort(key=sort_bridges)
__context__['lxc.bridges'] = bridges
return bridges
def search_lxc_bridge():
'''
Search the first bridge which is potentially available as LXC bridge
CLI Example:
.. code-block:: bash
salt '*' lxc.search_lxc_bridge
'''
return search_lxc_bridges()[0]
def _get_salt_config(config, **kwargs):
if not config:
config = kwargs.get('minion', {})
if not config:
config = {}
config.setdefault('master',
kwargs.get('master',
__opts__.get('master',
__opts__['id'])))
config.setdefault(
'master_port',
kwargs.get('master_port',
__opts__.get('master_port',
__opts__.get('ret_port',
__opts__.get('4506')))))
if not config['master']:
config = {}
return config
def cloud_init_interface(name, vm_=None, **kwargs):
'''
Interface between salt.cloud.lxc driver and lxc.init
``vm_`` is a mapping of vm opts in the salt.cloud format
as documented for the lxc driver.
This can be used either:
- from the salt cloud driver
- because you find the argument to give easier here
than using directly lxc.init
.. warning::
BE REALLY CAREFUL CHANGING DEFAULTS !!!
IT'S A RETRO COMPATIBLE INTERFACE WITH
THE SALT CLOUD DRIVER (ask kiorky).
name
name of the lxc container to create
pub_key
public key to preseed the minion with.
Can be the keycontent or a filepath
priv_key
private key to preseed the minion with.
Can be the keycontent or a filepath
path
path to the container parent directory (default: /var/lib/lxc)
.. versionadded:: 2015.8.0
profile
:ref:`profile <tutorial-lxc-profiles-container>` selection
network_profile
:ref:`network profile <tutorial-lxc-profiles-network>` selection
nic_opts
per interface settings compatibles with
network profile (ipv4/ipv6/link/gateway/mac/netmask)
eg::
- {'eth0': {'mac': '00:16:3e:01:29:40',
'gateway': None, (default)
'link': 'br0', (default)
'gateway': None, (default)
'netmask': '', (default)
'ip': '22.1.4.25'}}
unconditional_install
given to lxc.bootstrap (see relative doc)
force_install
given to lxc.bootstrap (see relative doc)
config
any extra argument for the salt minion config
dnsservers
list of DNS servers to set inside the container
dns_via_dhcp
do not set the dns servers, let them be set by the dhcp.
autostart
autostart the container at boot time
password
administrative password for the container
bootstrap_delay
delay before launching bootstrap script at Container init
.. warning::
Legacy but still supported options:
from_container
which container we use as a template
when running lxc.clone
image
which template do we use when we
are using lxc.create. This is the default
mode unless you specify something in from_container
backing
which backing store to use.
Values can be: overlayfs, dir(default), lvm, zfs, brtfs
fstype
When using a blockdevice level backing store,
which filesystem to use on
size
When using a blockdevice level backing store,
which size for the filesystem to use on
snapshot
Use snapshot when cloning the container source
vgname
if using LVM: vgname
lvname
if using LVM: lvname
thinpool:
if using LVM: thinpool
ip
ip for the primary nic
mac
mac address for the primary nic
netmask
netmask for the primary nic (24)
= ``vm_.get('netmask', '24')``
bridge
bridge for the primary nic (lxcbr0)
gateway
network gateway for the container
additional_ips
additional ips which will be wired on the main bridge (br0)
which is connected to internet.
Be aware that you may use manual virtual mac addresses
providen by you provider (online, ovh, etc).
This is a list of mappings {ip: '', mac: '', netmask:''}
Set gateway to None and an interface with a gateway
to escape from another interface that eth0.
eg::
- {'mac': '00:16:3e:01:29:40',
'gateway': None, (default)
'link': 'br0', (default)
'netmask': '', (default)
'ip': '22.1.4.25'}
users
administrative users for the container
default: [root] and [root, ubuntu] on ubuntu
default_nic
name of the first interface, you should
really not override this
CLI Example:
.. code-block:: bash
salt '*' lxc.cloud_init_interface foo
'''
if vm_ is None:
vm_ = {}
vm_ = copy.deepcopy(vm_)
vm_ = salt.utils.dictupdate.update(vm_, kwargs)
profile_data = copy.deepcopy(
vm_.get('lxc_profile',
vm_.get('profile', {})))
if not isinstance(profile_data, (dict, six.string_types)):
profile_data = {}
profile = get_container_profile(profile_data)
def _cloud_get(k, default=None):
return vm_.get(k, profile.get(k, default))
if name is None:
name = vm_['name']
# if we are on ubuntu, default to ubuntu
default_template = ''
if __grains__.get('os', '') in ['Ubuntu']:
default_template = 'ubuntu'
image = _cloud_get('image')
if not image:
_cloud_get('template', default_template)
backing = _cloud_get('backing', 'dir')
if image:
profile['template'] = image
vgname = _cloud_get('vgname', None)
if vgname:
profile['vgname'] = vgname
if backing:
profile['backing'] = backing
snapshot = _cloud_get('snapshot', False)
autostart = bool(_cloud_get('autostart', True))
dnsservers = _cloud_get('dnsservers', [])
dns_via_dhcp = _cloud_get('dns_via_dhcp', True)
password = _cloud_get('password', 's3cr3t')
password_encrypted = _cloud_get('password_encrypted', False)
fstype = _cloud_get('fstype', None)
lvname = _cloud_get('lvname', None)
thinpool = _cloud_get('thinpool', None)
pub_key = _cloud_get('pub_key', None)
priv_key = _cloud_get('priv_key', None)
size = _cloud_get('size', '20G')
script = _cloud_get('script', None)
script_args = _cloud_get('script_args', None)
users = _cloud_get('users', None)
if users is None:
users = []
ssh_username = _cloud_get('ssh_username', None)
if ssh_username and (ssh_username not in users):
users.append(ssh_username)
network_profile = _cloud_get('network_profile', None)
nic_opts = kwargs.get('nic_opts', None)
netmask = _cloud_get('netmask', '24')
path = _cloud_get('path', None)
bridge = _cloud_get('bridge', None)
gateway = _cloud_get('gateway', None)
unconditional_install = _cloud_get('unconditional_install', False)
force_install = _cloud_get('force_install', True)
config = _get_salt_config(_cloud_get('config', {}), **vm_)
default_nic = _cloud_get('default_nic', DEFAULT_NIC)
# do the interface with lxc.init mainly via nic_opts
# to avoid extra and confusing extra use cases.
if not isinstance(nic_opts, dict):
nic_opts = salt.utils.odict.OrderedDict()
# have a reference to the default nic
eth0 = nic_opts.setdefault(default_nic,
salt.utils.odict.OrderedDict())
# lxc config is based of ifc order, be sure to use odicts.
if not isinstance(nic_opts, salt.utils.odict.OrderedDict):
bnic_opts = salt.utils.odict.OrderedDict()
bnic_opts.update(nic_opts)
nic_opts = bnic_opts
gw = None
# legacy salt.cloud scheme for network interfaces settings support
bridge = _cloud_get('bridge', None)
ip = _cloud_get('ip', None)
mac = _cloud_get('mac', None)
if ip:
fullip = ip
if netmask:
fullip += '/{0}'.format(netmask)
eth0['ipv4'] = fullip
if mac is not None:
eth0['mac'] = mac
for ix, iopts in enumerate(_cloud_get("additional_ips", [])):
ifh = "eth{0}".format(ix+1)
ethx = nic_opts.setdefault(ifh, {})
if gw is None:
gw = iopts.get('gateway', ethx.get('gateway', None))
if gw:
# only one and only one default gateway is allowed !
eth0.pop('gateway', None)
gateway = None
# even if the gateway if on default "eth0" nic
# and we popped it will work
# as we reinject or set it here.
ethx['gateway'] = gw
elink = iopts.get('link', ethx.get('link', None))
if elink:
ethx['link'] = elink
# allow dhcp
aip = iopts.get('ipv4', iopts.get('ip', None))
if aip:
ethx['ipv4'] = aip
nm = iopts.get('netmask', '')
if nm:
ethx['ipv4'] += '/{0}'.format(nm)
for i in ('mac', 'hwaddr'):
if i in iopts:
ethx['mac'] = iopts[i]
break
if 'mac' not in ethx:
ethx['mac'] = salt.utils.network.gen_mac()
# last round checking for unique gateway and such
gw = None
for ethx in [a for a in nic_opts]:
ndata = nic_opts[ethx]
if gw:
ndata.pop('gateway', None)
if 'gateway' in ndata:
gw = ndata['gateway']
gateway = None
# only use a default bridge / gateway if we configured them
# via the legacy salt cloud configuration style.
# On other cases, we should rely on settings provided by the new
# salt lxc network profile style configuration which can
# be also be overridden or a per interface basis via the nic_opts dict.
if bridge:
eth0['link'] = bridge
if gateway:
eth0['gateway'] = gateway
#
lxc_init_interface = {}
lxc_init_interface['name'] = name
lxc_init_interface['config'] = config
lxc_init_interface['memory'] = _cloud_get('memory', 0) # nolimit
lxc_init_interface['pub_key'] = pub_key
lxc_init_interface['priv_key'] = priv_key
lxc_init_interface['nic_opts'] = nic_opts
for clone_from in ['clone_from', 'clone', 'from_container']:
# clone_from should default to None if not available
lxc_init_interface['clone_from'] = _cloud_get(clone_from, None)
if lxc_init_interface['clone_from'] is not None:
break
lxc_init_interface['profile'] = profile
lxc_init_interface['snapshot'] = snapshot
lxc_init_interface['dnsservers'] = dnsservers
lxc_init_interface['fstype'] = fstype
lxc_init_interface['path'] = path
lxc_init_interface['vgname'] = vgname
lxc_init_interface['size'] = size
lxc_init_interface['lvname'] = lvname
lxc_init_interface['thinpool'] = thinpool
lxc_init_interface['force_install'] = force_install
lxc_init_interface['unconditional_install'] = (
unconditional_install
)
lxc_init_interface['bootstrap_url'] = script
lxc_init_interface['bootstrap_args'] = script_args
lxc_init_interface['bootstrap_shell'] = _cloud_get('bootstrap_shell', 'sh')
lxc_init_interface['bootstrap_delay'] = _cloud_get('bootstrap_delay', None)
lxc_init_interface['autostart'] = autostart
lxc_init_interface['users'] = users
lxc_init_interface['password'] = password
lxc_init_interface['password_encrypted'] = password_encrypted
# be sure not to let objects goes inside the return
# as this return will be msgpacked for use in the runner !
lxc_init_interface['network_profile'] = network_profile
for i in ['cpu', 'cpuset', 'cpushare']:
if _cloud_get(i, None):
try:
lxc_init_interface[i] = vm_[i]
except KeyError:
lxc_init_interface[i] = profile[i]
return lxc_init_interface
def _get_profile(key, name, **kwargs):
if isinstance(name, dict):
profilename = name.pop('name', None)
return _get_profile(key, profilename, **name)
if name is None:
profile_match = {}
else:
profile_match = \
__salt__['config.get'](
'lxc.{1}:{0}'.format(name, key),
default=None,
merge='recurse'
)
if profile_match is None:
# No matching profile, make the profile an empty dict so that
# overrides can be applied below.
profile_match = {}
if not isinstance(profile_match, dict):
raise CommandExecutionError('lxc.{0} must be a dictionary'.format(key))
# Overlay the kwargs to override matched profile data
overrides = salt.utils.args.clean_kwargs(**copy.deepcopy(kwargs))
profile_match = salt.utils.dictupdate.update(
copy.deepcopy(profile_match),
overrides
)
return profile_match
def get_container_profile(name=None, **kwargs):
'''
.. versionadded:: 2015.5.0
Gather a pre-configured set of container configuration parameters. If no
arguments are passed, an empty profile is returned.
Profiles can be defined in the minion or master config files, or in pillar
or grains, and are loaded using :mod:`config.get
<salt.modules.config.get>`. The key under which LXC profiles must be
configured is ``lxc.container_profile.profile_name``. An example container
profile would be as follows:
.. code-block:: yaml
lxc.container_profile:
ubuntu:
template: ubuntu
backing: lvm
vgname: lxc
size: 1G
Parameters set in a profile can be overridden by passing additional
container creation arguments (such as the ones passed to :mod:`lxc.create
<salt.modules.lxc.create>`) to this function.
A profile can be defined either as the name of the profile, or a dictionary
of variable names and values. See the :ref:`LXC Tutorial
<tutorial-lxc-profiles>` for more information on how to use LXC profiles.
CLI Example:
.. code-block:: bash
salt-call lxc.get_container_profile centos
salt-call lxc.get_container_profile ubuntu template=ubuntu backing=overlayfs
'''
profile = _get_profile('container_profile', name, **kwargs)
return profile
def get_network_profile(name=None, **kwargs):
'''
.. versionadded:: 2015.5.0
Gather a pre-configured set of network configuration parameters. If no
arguments are passed, the following default profile is returned:
.. code-block:: python
{'eth0': {'link': 'br0', 'type': 'veth', 'flags': 'up'}}
Profiles can be defined in the minion or master config files, or in pillar
or grains, and are loaded using :mod:`config.get
<salt.modules.config.get>`. The key under which LXC profiles must be
configured is ``lxc.network_profile``. An example network profile would be
as follows:
.. code-block:: yaml
lxc.network_profile.centos:
eth0:
link: br0
type: veth
flags: up
To disable networking entirely:
.. code-block:: yaml
lxc.network_profile.centos:
eth0:
disable: true
Parameters set in a profile can be overridden by passing additional
arguments to this function.
A profile can be passed either as the name of the profile, or a
dictionary of variable names and values. See the :ref:`LXC Tutorial
<tutorial-lxc-profiles>` for more information on how to use network
profiles.
.. warning::
The ``ipv4``, ``ipv6``, ``gateway``, and ``link`` (bridge) settings in
network profiles will only work if the container doesn't redefine the
network configuration (for example in
``/etc/sysconfig/network-scripts/ifcfg-<interface_name>`` on
RHEL/CentOS, or ``/etc/network/interfaces`` on Debian/Ubuntu/etc.)
CLI Example:
.. code-block:: bash
salt-call lxc.get_network_profile default
'''
profile = _get_profile('network_profile', name, **kwargs)
return profile
def _rand_cpu_str(cpu):
'''
Return a random subset of cpus for the cpuset config
'''
cpu = int(cpu)
avail = __salt__['status.nproc']()
if cpu < avail:
return '0-{0}'.format(avail)
to_set = set()
while len(to_set) < cpu:
choice = random.randint(0, avail - 1)
if choice not in to_set:
to_set.add(six.text_type(choice))
return ','.join(sorted(to_set))
def _network_conf(conf_tuples=None, **kwargs):
'''
Network configuration defaults
network_profile
as for containers, we can either call this function
either with a network_profile dict or network profile name
in the kwargs
nic_opts
overrides or extra nics in the form {nic_name: {set: tings}
'''
nic = kwargs.get('network_profile', None)
ret = []
nic_opts = kwargs.get('nic_opts', {})
if nic_opts is None:
# coming from elsewhere
nic_opts = {}
if not conf_tuples:
conf_tuples = []
old = _get_veths(conf_tuples)
if not old:
old = {}
# if we have a profile name, get the profile and load the network settings
# this will obviously by default look for a profile called "eth0"
# or by what is defined in nic_opts
# and complete each nic settings by sane defaults
if nic and isinstance(nic, (six.string_types, dict)):
nicp = get_network_profile(nic)
else:
nicp = {}
if DEFAULT_NIC not in nicp:
nicp[DEFAULT_NIC] = {}
kwargs = copy.deepcopy(kwargs)
gateway = kwargs.pop('gateway', None)
bridge = kwargs.get('bridge', None)
if nic_opts:
for dev, args in six.iteritems(nic_opts):
ethx = nicp.setdefault(dev, {})
try:
ethx = salt.utils.dictupdate.update(ethx, args)
except AttributeError:
raise SaltInvocationError('Invalid nic_opts configuration')
ifs = [a for a in nicp]
ifs += [a for a in old if a not in nicp]
ifs.sort()
gateway_set = False
for dev in ifs:
args = nicp.get(dev, {})
opts = nic_opts.get(dev, {}) if nic_opts else {}
old_if = old.get(dev, {})
disable = opts.get('disable', args.get('disable', False))
if disable:
continue
mac = opts.get('mac',
opts.get('hwaddr',
args.get('mac',
args.get('hwaddr', ''))))
type_ = opts.get('type', args.get('type', ''))
flags = opts.get('flags', args.get('flags', ''))
link = opts.get('link', args.get('link', ''))
ipv4 = opts.get('ipv4', args.get('ipv4', ''))
ipv6 = opts.get('ipv6', args.get('ipv6', ''))
infos = salt.utils.odict.OrderedDict([
('lxc.network.type', {
'test': not type_,
'value': type_,
'old': old_if.get('lxc.network.type'),
'default': 'veth'}),
('lxc.network.name', {
'test': False,
'value': dev,
'old': dev,
'default': dev}),
('lxc.network.flags', {
'test': not flags,
'value': flags,
'old': old_if.get('lxc.network.flags'),
'default': 'up'}),
('lxc.network.link', {
'test': not link,
'value': link,
'old': old_if.get('lxc.network.link'),
'default': search_lxc_bridge()}),
('lxc.network.hwaddr', {
'test': not mac,
'value': mac,
'old': old_if.get('lxc.network.hwaddr'),
'default': salt.utils.network.gen_mac()}),
('lxc.network.ipv4', {
'test': not ipv4,
'value': ipv4,
'old': old_if.get('lxc.network.ipv4', ''),
'default': None}),
('lxc.network.ipv6', {
'test': not ipv6,
'value': ipv6,
'old': old_if.get('lxc.network.ipv6', ''),
'default': None})])
# for each parameter, if not explicitly set, the
# config value present in the LXC configuration should
# take precedence over the profile configuration
for info in list(infos.keys()):
bundle = infos[info]
if bundle['test']:
if bundle['old']:
bundle['value'] = bundle['old']
elif bundle['default']:
bundle['value'] = bundle['default']
for info, data in six.iteritems(infos):
if data['value']:
ret.append({info: data['value']})
for key, val in six.iteritems(args):
if key == 'link' and bridge:
val = bridge
val = opts.get(key, val)
if key in [
'type', 'flags', 'name',
'gateway', 'mac', 'link', 'ipv4', 'ipv6'
]:
continue
ret.append({'lxc.network.{0}'.format(key): val})
# gateway (in automode) must be appended following network conf !
if not gateway:
gateway = args.get('gateway', None)
if gateway is not None and not gateway_set:
ret.append({'lxc.network.ipv4.gateway': gateway})
# only one network gateway ;)
gateway_set = True
# normally, this won't happen
# set the gateway if specified even if we did
# not managed the network underlying
if gateway is not None and not gateway_set:
ret.append({'lxc.network.ipv4.gateway': gateway})
# only one network gateway ;)
gateway_set = True
new = _get_veths(ret)
# verify that we did not loose the mac settings
for iface in [a for a in new]:
ndata = new[iface]
nmac = ndata.get('lxc.network.hwaddr', '')
ntype = ndata.get('lxc.network.type', '')
omac, otype = '', ''
if iface in old:
odata = old[iface]
omac = odata.get('lxc.network.hwaddr', '')
otype = odata.get('lxc.network.type', '')
# default for network type is setted here
# attention not to change the network type
# without a good and explicit reason to.
if otype and not ntype:
ntype = otype
if not ntype:
ntype = 'veth'
new[iface]['lxc.network.type'] = ntype
if omac and not nmac:
new[iface]['lxc.network.hwaddr'] = omac
ret = []
for val in six.itervalues(new):
for row in val:
ret.append(salt.utils.odict.OrderedDict([(row, val[row])]))
# on old versions of lxc, still support the gateway auto mode
# if we didn't explicitly say no to
# (lxc.network.ipv4.gateway: auto)
if _LooseVersion(version()) <= _LooseVersion('1.0.7') and \
True not in ['lxc.network.ipv4.gateway' in a for a in ret] and \
True in ['lxc.network.ipv4' in a for a in ret]:
ret.append({'lxc.network.ipv4.gateway': 'auto'})
return ret
def _get_lxc_default_data(**kwargs):
kwargs = copy.deepcopy(kwargs)
ret = {}
for k in ['utsname', 'rootfs']:
val = kwargs.get(k, None)
if val is not None:
ret['lxc.{0}'.format(k)] = val
autostart = kwargs.get('autostart')
# autostart can have made in kwargs, but with the None
# value which is invalid, we need an explicit boolean
# autostart = on is the default.
if autostart is None:
autostart = True
# we will set the regular lxc marker to restart container at
# machine (re)boot only if we did not explicitly ask
# not to touch to the autostart settings via
# autostart == 'keep'
if autostart != 'keep':
if autostart:
ret['lxc.start.auto'] = '1'
else:
ret['lxc.start.auto'] = '0'
memory = kwargs.get('memory')
if memory is not None:
# converting the config value from MB to bytes
ret['lxc.cgroup.memory.limit_in_bytes'] = memory * 1024 * 1024
cpuset = kwargs.get('cpuset')
if cpuset:
ret['lxc.cgroup.cpuset.cpus'] = cpuset
cpushare = kwargs.get('cpushare')
cpu = kwargs.get('cpu')
if cpushare:
ret['lxc.cgroup.cpu.shares'] = cpushare
if cpu and not cpuset:
ret['lxc.cgroup.cpuset.cpus'] = _rand_cpu_str(cpu)
return ret
def _config_list(conf_tuples=None, only_net=False, **kwargs):
'''
Return a list of dicts from the salt level configurations
conf_tuples
_LXCConfig compatible list of entries which can contain
- string line
- tuple (lxc config param,value)
- dict of one entry: {lxc config param: value)
only_net
by default we add to the tuples a reflection of both
the real config if avalaible and a certain amount of
default values like the cpu parameters, the memory
and etc.
On the other hand, we also no matter the case reflect
the network configuration computed from the actual config if
available and given values.
if no_default_loads is set, we will only
reflect the network configuration back to the conf tuples
list
'''
# explicit cast
only_net = bool(only_net)
if not conf_tuples:
conf_tuples = []
kwargs = copy.deepcopy(kwargs)
ret = []
if not only_net:
default_data = _get_lxc_default_data(**kwargs)
for k, val in six.iteritems(default_data):
ret.append({k: val})
net_datas = _network_conf(conf_tuples=conf_tuples, **kwargs)
ret.extend(net_datas)
return ret
def _get_veths(net_data):
'''
Parse the nic setup inside lxc conf tuples back to a dictionary indexed by
network interface
'''
if isinstance(net_data, dict):
net_data = list(net_data.items())
nics = salt.utils.odict.OrderedDict()
current_nic = salt.utils.odict.OrderedDict()
no_names = True
for item in net_data:
if item and isinstance(item, dict):
item = list(item.items())[0]
# skip LXC configuration comment lines, and play only with tuples conf
elif isinstance(item, six.string_types):
# deal with reflection of commented lxc configs
sitem = item.strip()
if sitem.startswith('#') or not sitem:
continue
elif '=' in item:
item = tuple([a.strip() for a in item.split('=', 1)])
if item[0] == 'lxc.network.type':
current_nic = salt.utils.odict.OrderedDict()
if item[0] == 'lxc.network.name':
no_names = False
nics[item[1].strip()] = current_nic
current_nic[item[0].strip()] = item[1].strip()
# if not ethernet card name has been collected, assuming we collected
# data for eth0
if no_names and current_nic:
nics[DEFAULT_NIC] = current_nic
return nics
class _LXCConfig(object):
'''
LXC configuration data
'''
pattern = re.compile(r'^(\S+)(\s*)(=)(\s*)(.*)')
non_interpretable_pattern = re.compile(r'^((#.*)|(\s*))$')
def __init__(self, **kwargs):
kwargs = copy.deepcopy(kwargs)
self.name = kwargs.pop('name', None)
path = get_root_path(kwargs.get('path', None))
self.data = []
if self.name:
self.path = os.path.join(path, self.name, 'config')
if os.path.isfile(self.path):
with salt.utils.files.fopen(self.path) as fhr:
for line in salt.utils.data.decode(fhr.readlines()):
match = self.pattern.findall((line.strip()))
if match:
self.data.append((match[0][0], match[0][-1]))
match = self.non_interpretable_pattern.findall(
(line.strip()))
if match:
self.data.append(('', match[0][0]))
else:
self.path = None
def _replace(key, val):
if val:
self._filter_data(key)
self.data.append((key, val))
default_data = _get_lxc_default_data(**kwargs)
for key, val in six.iteritems(default_data):
_replace(key, val)
old_net = self._filter_data('lxc.network')
net_datas = _network_conf(conf_tuples=old_net, **kwargs)
if net_datas:
for row in net_datas:
self.data.extend(list(row.items()))
# be sure to reset harmful settings
for idx in ['lxc.cgroup.memory.limit_in_bytes']:
if not default_data.get(idx):
self._filter_data(idx)
def as_string(self):
chunks = ('{0[0]}{1}{0[1]}'.format(item, (' = ' if item[0] else '')) for item in self.data)
return '\n'.join(chunks) + '\n'
def write(self):
if self.path:
content = self.as_string()
# 2 step rendering to be sure not to open/wipe the config
# before as_string succeeds.
with salt.utils.files.fopen(self.path, 'w') as fic:
fic.write(salt.utils.stringutils.to_str(content))
fic.flush()
def tempfile(self):
# this might look like the function name is shadowing the
# module, but it's not since the method belongs to the class
ntf = tempfile.NamedTemporaryFile()
ntf.write(self.as_string())
ntf.flush()
return ntf
def _filter_data(self, pattern):
'''
Removes parameters which match the pattern from the config data
'''
removed = []
filtered = []
for param in self.data:
if not param[0].startswith(pattern):
filtered.append(param)
else:
removed.append(param)
self.data = filtered
return removed
def init(name,
config=None,
cpuset=None,
cpushare=None,
memory=None,
profile=None,
network_profile=None,
nic_opts=None,
cpu=None,
autostart=True,
password=None,
password_encrypted=None,
users=None,
dnsservers=None,
searchdomains=None,
bridge=None,
gateway=None,
pub_key=None,
priv_key=None,
force_install=False,
unconditional_install=False,
bootstrap_delay=None,
bootstrap_args=None,
bootstrap_shell=None,
bootstrap_url=None,
**kwargs):
'''
Initialize a new container.
This is a partial idempotent function as if it is already provisioned, we
will reset a bit the lxc configuration file but much of the hard work will
be escaped as markers will prevent re-execution of harmful tasks.
name
Name of the container
image
A tar archive to use as the rootfs for the container. Conflicts with
the ``template`` argument.
cpus
Select a random number of cpu cores and assign it to the cpuset, if the
cpuset option is set then this option will be ignored
cpuset
Explicitly define the cpus this container will be bound to
cpushare
cgroups cpu shares
autostart
autostart container on reboot
memory
cgroups memory limit, in MB
.. versionchanged:: 2015.5.0
If no value is passed, no limit is set. In earlier Salt versions,
not passing this value causes a 1024MB memory limit to be set, and
it was necessary to pass ``memory=0`` to set no limit.
gateway
the ipv4 gateway to use
the default does nothing more than lxcutils does
bridge
the bridge to use
the default does nothing more than lxcutils does
network_profile
Network profile to use for the container
.. versionadded:: 2015.5.0
nic_opts
Extra options for network interfaces, will override
``{"eth0": {"hwaddr": "aa:bb:cc:dd:ee:ff", "ipv4": "10.1.1.1", "ipv6": "2001:db8::ff00:42:8329"}}``
or
``{"eth0": {"hwaddr": "aa:bb:cc:dd:ee:ff", "ipv4": "10.1.1.1/24", "ipv6": "2001:db8::ff00:42:8329"}}``
users
Users for which the password defined in the ``password`` param should
be set. Can be passed as a comma separated list or a python list.
Defaults to just the ``root`` user.
password
Set the initial password for the users defined in the ``users``
parameter
password_encrypted : False
Set to ``True`` to denote a password hash instead of a plaintext
password
.. versionadded:: 2015.5.0
profile
A LXC profile (defined in config or pillar).
This can be either a real profile mapping or a string
to retrieve it in configuration
start
Start the newly-created container
dnsservers
list of dns servers to set in the container, default [] (no setting)
seed
Seed the container with the minion config. Default: ``True``
install
If salt-minion is not already installed, install it. Default: ``True``
config
Optional config parameters. By default, the id is set to
the name of the container.
master
salt master (default to minion's master)
master_port
salt master port (default to minion's master port)
pub_key
Explicit public key to preseed the minion with (optional).
This can be either a filepath or a string representing the key
priv_key
Explicit private key to preseed the minion with (optional).
This can be either a filepath or a string representing the key
approve_key
If explicit preseeding is not used;
Attempt to request key approval from the master. Default: ``True``
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
clone_from
Original from which to use a clone operation to create the container.
Default: ``None``
bootstrap_delay
Delay in seconds between end of container creation and bootstrapping.
Useful when waiting for container to obtain a DHCP lease.
.. versionadded:: 2015.5.0
bootstrap_url
See lxc.bootstrap
bootstrap_shell
See lxc.bootstrap
bootstrap_args
See lxc.bootstrap
force_install
Force installation even if salt-minion is detected,
this is the way to run vendor bootstrap scripts even
if a salt minion is already present in the container
unconditional_install
Run the script even if the container seems seeded
CLI Example:
.. code-block:: bash
salt 'minion' lxc.init name [cpuset=cgroups_cpuset] \\
[cpushare=cgroups_cpushare] [memory=cgroups_memory] \\
[nic=nic_profile] [profile=lxc_profile] \\
[nic_opts=nic_opts] [start=(True|False)] \\
[seed=(True|False)] [install=(True|False)] \\
[config=minion_config] [approve_key=(True|False) \\
[clone_from=original] [autostart=True] \\
[priv_key=/path_or_content] [pub_key=/path_or_content] \\
[bridge=lxcbr0] [gateway=10.0.3.1] \\
[dnsservers[dns1,dns2]] \\
[users=[foo]] [password='secret'] \\
[password_encrypted=(True|False)]
'''
ret = {'name': name,
'changes': {}}
profile = get_container_profile(copy.deepcopy(profile))
if not network_profile:
network_profile = profile.get('network_profile')
if not network_profile:
network_profile = DEFAULT_NIC
# Changes is a pointer to changes_dict['init']. This method is used so that
# we can have a list of changes as they are made, providing an ordered list
# of things that were changed.
changes_dict = {'init': []}
changes = changes_dict.get('init')
if users is None:
users = []
dusers = ['root']
for user in dusers:
if user not in users:
users.append(user)
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, _marker)
profile_match = profile.pop(key, default)
# let kwarg overrides be the preferred choice
if kw_overrides_match is _marker:
return profile_match
return kw_overrides_match
path = select('path')
bpath = get_root_path(path)
state_pre = state(name, path=path)
tvg = select('vgname')
vgname = tvg if tvg else __salt__['config.get']('lxc.vgname')
start_ = select('start', True)
autostart = select('autostart', autostart)
seed = select('seed', True)
install = select('install', True)
seed_cmd = select('seed_cmd')
salt_config = _get_salt_config(config, **kwargs)
approve_key = select('approve_key', True)
clone_from = select('clone_from')
# If using a volume group then set up to make snapshot cow clones
if vgname and not clone_from:
try:
kwargs['vgname'] = vgname
clone_from = _get_base(profile=profile, **kwargs)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = exc.strerror
if changes:
ret['changes'] = changes_dict
return ret
if not kwargs.get('snapshot') is False:
kwargs['snapshot'] = True
does_exist = exists(name, path=path)
to_reboot = False
remove_seed_marker = False
if does_exist:
pass
elif clone_from:
remove_seed_marker = True
try:
clone(name, clone_from, profile=profile, **kwargs)
changes.append({'create': 'Container cloned'})
except (SaltInvocationError, CommandExecutionError) as exc:
if 'already exists' in exc.strerror:
changes.append({'create': 'Container already exists'})
else:
ret['result'] = False
ret['comment'] = exc.strerror
if changes:
ret['changes'] = changes_dict
return ret
cfg = _LXCConfig(name=name, network_profile=network_profile,
nic_opts=nic_opts, bridge=bridge, path=path,
gateway=gateway, autostart=autostart,
cpuset=cpuset, cpushare=cpushare, memory=memory)
old_chunks = read_conf(cfg.path, out_format='commented')
cfg.write()
chunks = read_conf(cfg.path, out_format='commented')
if old_chunks != chunks:
to_reboot = True
else:
remove_seed_marker = True
cfg = _LXCConfig(network_profile=network_profile,
nic_opts=nic_opts, cpuset=cpuset, path=path,
bridge=bridge, gateway=gateway,
autostart=autostart,
cpushare=cpushare, memory=memory)
with cfg.tempfile() as cfile:
try:
create(name, config=cfile.name, profile=profile, **kwargs)
changes.append({'create': 'Container created'})
except (SaltInvocationError, CommandExecutionError) as exc:
if 'already exists' in exc.strerror:
changes.append({'create': 'Container already exists'})
else:
ret['comment'] = exc.strerror
if changes:
ret['changes'] = changes_dict
return ret
cpath = os.path.join(bpath, name, 'config')
old_chunks = []
if os.path.exists(cpath):
old_chunks = read_conf(cpath, out_format='commented')
new_cfg = _config_list(conf_tuples=old_chunks,
cpu=cpu,
network_profile=network_profile,
nic_opts=nic_opts, bridge=bridge,
cpuset=cpuset, cpushare=cpushare,
memory=memory)
if new_cfg:
edit_conf(cpath, out_format='commented', lxc_config=new_cfg)
chunks = read_conf(cpath, out_format='commented')
if old_chunks != chunks:
to_reboot = True
# last time to be sure any of our property is correctly applied
cfg = _LXCConfig(name=name, network_profile=network_profile,
nic_opts=nic_opts, bridge=bridge, path=path,
gateway=gateway, autostart=autostart,
cpuset=cpuset, cpushare=cpushare, memory=memory)
old_chunks = []
if os.path.exists(cfg.path):
old_chunks = read_conf(cfg.path, out_format='commented')
cfg.write()
chunks = read_conf(cfg.path, out_format='commented')
if old_chunks != chunks:
changes.append({'config': 'Container configuration updated'})
to_reboot = True
if to_reboot:
try:
stop(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
if changes:
ret['changes'] = changes_dict
return ret
if not does_exist or (does_exist and state(name, path=path) != 'running'):
try:
start(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
if changes:
ret['changes'] = changes_dict
return ret
if remove_seed_marker:
run(name,
'rm -f \'{0}\''.format(SEED_MARKER),
path=path,
chroot_fallback=False,
python_shell=False)
# set the default user/password, only the first time
if ret.get('result', True) and password:
gid = '/.lxc.initial_pass'
gids = [gid,
'/lxc.initial_pass',
'/.lxc.{0}.initial_pass'.format(name)]
if not any(retcode(name,
'test -e "{0}"'.format(x),
chroot_fallback=True,
path=path,
ignore_retcode=True) == 0
for x in gids):
# think to touch the default user generated by default templates
# which has a really unsecure passwords...
# root is defined as a member earlier in the code
for default_user in ['ubuntu']:
if (
default_user not in users and
retcode(name,
'id {0}'.format(default_user),
python_shell=False,
path=path,
chroot_fallback=True,
ignore_retcode=True) == 0
):
users.append(default_user)
for user in users:
try:
cret = set_password(name,
users=[user],
path=path,
password=password,
encrypted=password_encrypted)
except (SaltInvocationError, CommandExecutionError) as exc:
msg = '{0}: Failed to set password'.format(
user) + exc.strerror
# only hardfail in unrecoverable situation:
# root cannot be setted up
if user == 'root':
ret['comment'] = msg
ret['result'] = False
else:
log.debug(msg)
if ret.get('result', True):
changes.append({'password': 'Password(s) updated'})
if retcode(name,
('sh -c \'touch "{0}"; test -e "{0}"\''
.format(gid)),
path=path,
chroot_fallback=True,
ignore_retcode=True) != 0:
ret['comment'] = 'Failed to set password marker'
changes[-1]['password'] += '. ' + ret['comment'] + '.'
ret['result'] = False
# set dns servers if any, only the first time
if ret.get('result', True) and dnsservers:
# retro compatibility, test also old markers
gid = '/.lxc.initial_dns'
gids = [gid,
'/lxc.initial_dns',
'/lxc.{0}.initial_dns'.format(name)]
if not any(retcode(name,
'test -e "{0}"'.format(x),
chroot_fallback=True,
path=path,
ignore_retcode=True) == 0
for x in gids):
try:
set_dns(name,
path=path,
dnsservers=dnsservers,
searchdomains=searchdomains)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Failed to set DNS: ' + exc.strerror
ret['result'] = False
else:
changes.append({'dns': 'DNS updated'})
if retcode(name,
('sh -c \'touch "{0}"; test -e "{0}"\''
.format(gid)),
chroot_fallback=True,
path=path,
ignore_retcode=True) != 0:
ret['comment'] = 'Failed to set DNS marker'
changes[-1]['dns'] += '. ' + ret['comment'] + '.'
ret['result'] = False
# retro compatibility, test also old markers
if remove_seed_marker:
run(name,
'rm -f \'{0}\''.format(SEED_MARKER),
path=path,
python_shell=False)
gid = '/.lxc.initial_seed'
gids = [gid, '/lxc.initial_seed']
if (
any(retcode(name,
'test -e {0}'.format(x),
path=path,
chroot_fallback=True,
ignore_retcode=True) == 0
for x in gids) or not ret.get('result', True)
):
pass
elif seed or seed_cmd:
if seed:
try:
result = bootstrap(
name, config=salt_config, path=path,
approve_key=approve_key,
pub_key=pub_key, priv_key=priv_key,
install=install,
force_install=force_install,
unconditional_install=unconditional_install,
bootstrap_delay=bootstrap_delay,
bootstrap_url=bootstrap_url,
bootstrap_shell=bootstrap_shell,
bootstrap_args=bootstrap_args)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Bootstrap failed: ' + exc.strerror
ret['result'] = False
else:
if not result:
ret['comment'] = ('Bootstrap failed, see minion log for '
'more information')
ret['result'] = False
else:
changes.append(
{'bootstrap': 'Container successfully bootstrapped'}
)
elif seed_cmd:
try:
result = __salt__[seed_cmd](info(name, path=path)['rootfs'],
name,
salt_config)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = ('Bootstrap via seed_cmd \'{0}\' failed: {1}'
.format(seed_cmd, exc.strerror))
ret['result'] = False
else:
if not result:
ret['comment'] = ('Bootstrap via seed_cmd \'{0}\' failed, '
'see minion log for more information '
.format(seed_cmd))
ret['result'] = False
else:
changes.append(
{'bootstrap': 'Container successfully bootstrapped '
'using seed_cmd \'{0}\''
.format(seed_cmd)}
)
if ret.get('result', True) and not start_:
try:
stop(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
ret['result'] = False
state_post = state(name, path=path)
if state_pre != state_post:
changes.append({'state': {'old': state_pre, 'new': state_post}})
if ret.get('result', True):
ret['comment'] = ('Container \'{0}\' successfully initialized'
.format(name))
ret['result'] = True
if changes:
ret['changes'] = changes_dict
return ret
def cloud_init(name, vm_=None, **kwargs):
'''
Thin wrapper to lxc.init to be used from the saltcloud lxc driver
name
Name of the container
may be None and then guessed from saltcloud mapping
`vm_`
saltcloud mapping defaults for the vm
CLI Example:
.. code-block:: bash
salt '*' lxc.cloud_init foo
'''
init_interface = cloud_init_interface(name, vm_, **kwargs)
name = init_interface.pop('name', name)
return init(name, **init_interface)
def images(dist=None):
'''
.. versionadded:: 2015.5.0
List the available images for LXC's ``download`` template.
dist : None
Filter results to a single Linux distribution
CLI Examples:
.. code-block:: bash
salt myminion lxc.images
salt myminion lxc.images dist=centos
'''
out = __salt__['cmd.run_stdout'](
'lxc-create -n __imgcheck -t download -- --list',
ignore_retcode=True
)
if 'DIST' not in out:
raise CommandExecutionError(
'Unable to run the \'download\' template script. Is it installed?'
)
ret = {}
passed_header = False
for line in out.splitlines():
try:
distro, release, arch, variant, build_time = line.split()
except ValueError:
continue
if not passed_header:
if distro == 'DIST':
passed_header = True
continue
dist_list = ret.setdefault(distro, [])
dist_list.append({
'release': release,
'arch': arch,
'variant': variant,
'build_time': build_time,
})
if dist is not None:
return dict([(dist, ret.get(dist, []))])
return ret
def templates():
'''
.. versionadded:: 2015.5.0
List the available LXC template scripts installed on the minion
CLI Examples:
.. code-block:: bash
salt myminion lxc.templates
'''
try:
template_scripts = os.listdir('/usr/share/lxc/templates')
except OSError:
return []
else:
return [x[4:] for x in template_scripts if x.startswith('lxc-')]
def _after_ignition_network_profile(cmd,
ret,
name,
network_profile,
path,
nic_opts):
_clear_context()
if ret['retcode'] == 0 and exists(name, path=path):
if network_profile:
network_changes = apply_network_profile(name,
network_profile,
path=path,
nic_opts=nic_opts)
if network_changes:
log.info(
'Network changes from applying network profile \'%s\' '
'to newly-created container \'%s\':\n%s',
network_profile, name, network_changes
)
c_state = state(name, path=path)
return {'result': True,
'state': {'old': None, 'new': c_state}}
else:
if exists(name, path=path):
# destroy the container if it was partially created
cmd = 'lxc-destroy'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0}'.format(name)
__salt__['cmd.retcode'](cmd, python_shell=False)
raise CommandExecutionError(
'Container could not be created with cmd \'{0}\': {1}'
.format(cmd, ret['stderr'])
)
def create(name,
config=None,
profile=None,
network_profile=None,
nic_opts=None,
**kwargs):
'''
Create a new container.
name
Name of the container
config
The config file to use for the container. Defaults to system-wide
config (usually in /etc/lxc/lxc.conf).
profile
Profile to use in container creation (see
:mod:`lxc.get_container_profile
<salt.modules.lxc.get_container_profile>`). Values in a profile will be
overridden by the **Container Creation Arguments** listed below.
network_profile
Network profile to use for container
.. versionadded:: 2015.5.0
**Container Creation Arguments**
template
The template to use. For example, ``ubuntu`` or ``fedora``.
For a full list of available templates, check out
the :mod:`lxc.templates <salt.modules.lxc.templates>` function.
Conflicts with the ``image`` argument.
.. note::
The ``download`` template requires the following three parameters
to be defined in ``options``:
* **dist** - The name of the distribution
* **release** - Release name/version
* **arch** - Architecture of the container
The available images can be listed using the :mod:`lxc.images
<salt.modules.lxc.images>` function.
options
Template-specific options to pass to the lxc-create command. These
correspond to the long options (ones beginning with two dashes) that
the template script accepts. For example:
.. code-block:: bash
options='{"dist": "centos", "release": "6", "arch": "amd64"}'
For available template options, refer to the lxc template scripts
which are ususally located under ``/usr/share/lxc/templates``,
or run ``lxc-create -t <template> -h``.
image
A tar archive to use as the rootfs for the container. Conflicts with
the ``template`` argument.
backing
The type of storage to use. Set to ``lvm`` to use an LVM group.
Defaults to filesystem within /var/lib/lxc.
fstype
Filesystem type to use on LVM logical volume
size : 1G
Size of the volume to create. Only applicable if ``backing=lvm``.
vgname : lxc
Name of the LVM volume group in which to create the volume for this
container. Only applicable if ``backing=lvm``.
lvname
Name of the LVM logical volume in which to create the volume for this
container. Only applicable if ``backing=lvm``.
thinpool
Name of a pool volume that will be used for thin-provisioning this
container. Only applicable if ``backing=lvm``.
nic_opts
give extra opts overriding network profile values
path
parent path for the container creation (default: /var/lib/lxc)
zfsroot
Name of the ZFS root in which to create the volume for this container.
Only applicable if ``backing=zfs``. (default: tank/lxc)
.. versionadded:: 2015.8.0
'''
# Required params for 'download' template
download_template_deps = ('dist', 'release', 'arch')
cmd = 'lxc-create -n {0}'.format(name)
profile = get_container_profile(copy.deepcopy(profile))
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, None)
profile_match = profile.pop(key, default)
# Return the profile match if the the kwarg match was None, as the
# lxc.present state will pass these kwargs set to None by default.
if kw_overrides_match is None:
return profile_match
return kw_overrides_match
path = select('path')
if exists(name, path=path):
raise CommandExecutionError(
'Container \'{0}\' already exists'.format(name)
)
tvg = select('vgname')
vgname = tvg if tvg else __salt__['config.get']('lxc.vgname')
# The 'template' and 'image' params conflict
template = select('template')
image = select('image')
if template and image:
raise SaltInvocationError(
'Only one of \'template\' and \'image\' is permitted'
)
elif not any((template, image, profile)):
raise SaltInvocationError(
'At least one of \'template\', \'image\', and \'profile\' is '
'required'
)
options = select('options') or {}
backing = select('backing')
if vgname and not backing:
backing = 'lvm'
lvname = select('lvname')
thinpool = select('thinpool')
fstype = select('fstype')
size = select('size', '1G')
zfsroot = select('zfsroot')
if backing in ('dir', 'overlayfs', 'btrfs', 'zfs'):
fstype = None
size = None
# some backends won't support some parameters
if backing in ('aufs', 'dir', 'overlayfs', 'btrfs'):
lvname = vgname = thinpool = None
if image:
img_tar = __salt__['cp.cache_file'](image)
template = os.path.join(
os.path.dirname(salt.__file__),
'templates',
'lxc',
'salt_tarball')
options['imgtar'] = img_tar
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
if not os.path.exists(path):
os.makedirs(path)
if config:
cmd += ' -f {0}'.format(config)
if template:
cmd += ' -t {0}'.format(template)
if backing:
backing = backing.lower()
cmd += ' -B {0}'.format(backing)
if backing in ('zfs',):
if zfsroot:
cmd += ' --zfsroot {0}'.format(zfsroot)
if backing in ('lvm',):
if lvname:
cmd += ' --lvname {0}'.format(lvname)
if vgname:
cmd += ' --vgname {0}'.format(vgname)
if thinpool:
cmd += ' --thinpool {0}'.format(thinpool)
if backing not in ('dir', 'overlayfs'):
if fstype:
cmd += ' --fstype {0}'.format(fstype)
if size:
cmd += ' --fssize {0}'.format(size)
if options:
if template == 'download':
missing_deps = [x for x in download_template_deps
if x not in options]
if missing_deps:
raise SaltInvocationError(
'Missing params in \'options\' dict: {0}'
.format(', '.join(missing_deps))
)
cmd += ' --'
for key, val in six.iteritems(options):
cmd += ' --{0} {1}'.format(key, val)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
# please do not merge extra conflicting stuff
# inside those two line (ret =, return)
return _after_ignition_network_profile(cmd,
ret,
name,
network_profile,
path,
nic_opts)
def clone(name,
orig,
profile=None,
network_profile=None,
nic_opts=None,
**kwargs):
'''
Create a new container as a clone of another container
name
Name of the container
orig
Name of the original container to be cloned
profile
Profile to use in container cloning (see
:mod:`lxc.get_container_profile
<salt.modules.lxc.get_container_profile>`). Values in a profile will be
overridden by the **Container Cloning Arguments** listed below.
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
**Container Cloning Arguments**
snapshot
Use Copy On Write snapshots (LVM)
size : 1G
Size of the volume to create. Only applicable if ``backing=lvm``.
backing
The type of storage to use. Set to ``lvm`` to use an LVM group.
Defaults to filesystem within /var/lib/lxc.
network_profile
Network profile to use for container
.. versionadded:: 2015.8.0
nic_opts
give extra opts overriding network profile values
.. versionadded:: 2015.8.0
CLI Examples:
.. code-block:: bash
salt '*' lxc.clone myclone orig=orig_container
salt '*' lxc.clone myclone orig=orig_container snapshot=True
'''
profile = get_container_profile(copy.deepcopy(profile))
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, None)
profile_match = profile.pop(key, default)
# let kwarg overrides be the preferred choice
if kw_overrides_match is None:
return profile_match
return kw_overrides_match
path = select('path')
if exists(name, path=path):
raise CommandExecutionError(
'Container \'{0}\' already exists'.format(name)
)
_ensure_exists(orig, path=path)
if state(orig, path=path) != 'stopped':
raise CommandExecutionError(
'Container \'{0}\' must be stopped to be cloned'.format(orig)
)
backing = select('backing')
snapshot = select('snapshot')
if backing in ('dir',):
snapshot = False
if not snapshot:
snapshot = ''
else:
snapshot = '-s'
size = select('size', '1G')
if backing in ('dir', 'overlayfs', 'btrfs'):
size = None
# LXC commands and options changed in 2.0 - CF issue #34086 for details
if _LooseVersion(version()) >= _LooseVersion('2.0'):
# https://linuxcontainers.org/lxc/manpages//man1/lxc-copy.1.html
cmd = 'lxc-copy'
cmd += ' {0} -n {1} -N {2}'.format(snapshot, orig, name)
else:
# https://linuxcontainers.org/lxc/manpages//man1/lxc-clone.1.html
cmd = 'lxc-clone'
cmd += ' {0} -o {1} -n {2}'.format(snapshot, orig, name)
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
if not os.path.exists(path):
os.makedirs(path)
if backing:
backing = backing.lower()
cmd += ' -B {0}'.format(backing)
if backing not in ('dir', 'overlayfs'):
if size:
cmd += ' -L {0}'.format(size)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
# please do not merge extra conflicting stuff
# inside those two line (ret =, return)
return _after_ignition_network_profile(cmd,
ret,
name,
network_profile,
path,
nic_opts)
def ls_(active=None, cache=True, path=None):
'''
Return a list of the containers available on the minion
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
active
If ``True``, return only active (i.e. running) containers
.. versionadded:: 2015.5.0
CLI Example:
.. code-block:: bash
salt '*' lxc.ls
salt '*' lxc.ls active=True
'''
contextvar = 'lxc.ls{0}'.format(path)
if active:
contextvar += '.active'
if cache and (contextvar in __context__):
return __context__[contextvar]
else:
ret = []
cmd = 'lxc-ls'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
if active:
cmd += ' --active'
output = __salt__['cmd.run_stdout'](cmd, python_shell=False)
for line in output.splitlines():
ret.extend(line.split())
__context__[contextvar] = ret
return ret
def list_(extra=False, limit=None, path=None):
'''
List containers classified by state
extra
Also get per-container specific info. This will change the return data.
Instead of returning a list of containers, a dictionary of containers
and each container's output from :mod:`lxc.info
<salt.modules.lxc.info>`.
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
limit
Return output matching a specific state (**frozen**, **running**, or
**stopped**).
.. versionadded:: 2015.5.0
CLI Examples:
.. code-block:: bash
salt '*' lxc.list
salt '*' lxc.list extra=True
salt '*' lxc.list limit=running
'''
ctnrs = ls_(path=path)
if extra:
stopped = {}
frozen = {}
running = {}
else:
stopped = []
frozen = []
running = []
ret = {'running': running,
'stopped': stopped,
'frozen': frozen}
for container in ctnrs:
cmd = 'lxc-info'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0}'.format(container)
c_info = __salt__['cmd.run'](
cmd,
python_shell=False,
output_loglevel='debug'
)
c_state = None
for line in c_info.splitlines():
stat = line.split(':')
if stat[0] in ('State', 'state'):
c_state = stat[1].strip()
break
if not c_state or (limit is not None and c_state.lower() != limit):
continue
if extra:
infos = info(container, path=path)
method = 'update'
value = {container: infos}
else:
method = 'append'
value = container
if c_state == 'STOPPED':
getattr(stopped, method)(value)
continue
if c_state == 'FROZEN':
getattr(frozen, method)(value)
continue
if c_state == 'RUNNING':
getattr(running, method)(value)
continue
if limit is not None:
return ret.get(limit, {} if extra else [])
return ret
def _change_state(cmd,
name,
expected,
stdin=_marker,
stdout=_marker,
stderr=_marker,
with_communicate=_marker,
use_vt=_marker,
path=None):
pre = state(name, path=path)
if pre == expected:
return {'result': True,
'state': {'old': expected, 'new': expected},
'comment': 'Container \'{0}\' already {1}'
.format(name, expected)}
if cmd == 'lxc-destroy':
# Kill the container first
scmd = 'lxc-stop'
if path:
scmd += ' -P {0}'.format(pipes.quote(path))
scmd += ' -k -n {0}'.format(name)
__salt__['cmd.run'](scmd,
python_shell=False)
if path and ' -P ' not in cmd:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0}'.format(name)
# certain lxc commands need to be taken with care (lxc-start)
# as te command itself mess with double forks; we must not
# communicate with it, but just wait for the exit status
pkwargs = {'python_shell': False,
'redirect_stderr': True,
'with_communicate': with_communicate,
'use_vt': use_vt,
'stdin': stdin,
'stdout': stdout}
for i in [a for a in pkwargs]:
val = pkwargs[i]
if val is _marker:
pkwargs.pop(i, None)
_cmdout = __salt__['cmd.run_all'](cmd, **pkwargs)
if _cmdout['retcode'] != 0:
raise CommandExecutionError(
'Error changing state for container \'{0}\' using command '
'\'{1}\': {2}'.format(name, cmd, _cmdout['stdout'])
)
if expected is not None:
# some commands do not wait, so we will
rcmd = 'lxc-wait'
if path:
rcmd += ' -P {0}'.format(pipes.quote(path))
rcmd += ' -n {0} -s {1}'.format(name, expected.upper())
__salt__['cmd.run'](rcmd, python_shell=False, timeout=30)
_clear_context()
post = state(name, path=path)
ret = {'result': post == expected,
'state': {'old': pre, 'new': post}}
return ret
def _ensure_exists(name, path=None):
'''
Raise an exception if the container does not exist
'''
if not exists(name, path=path):
raise CommandExecutionError(
'Container \'{0}\' does not exist'.format(name)
)
def _ensure_running(name, no_start=False, path=None):
'''
If the container is not currently running, start it. This function returns
the state that the container was in before changing
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
'''
_ensure_exists(name, path=path)
pre = state(name, path=path)
if pre == 'running':
# This will be a no-op but running the function will give us a pretty
# return dict.
return start(name, path=path)
elif pre == 'stopped':
if no_start:
raise CommandExecutionError(
'Container \'{0}\' is not running'.format(name)
)
return start(name, path=path)
elif pre == 'frozen':
if no_start:
raise CommandExecutionError(
'Container \'{0}\' is not running'.format(name)
)
return unfreeze(name, path=path)
def restart(name, path=None, lxc_config=None, force=False):
'''
.. versionadded:: 2015.5.0
Restart the named container. If the container was not running, the
container will merely be started.
name
The name of the container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
lxc_config
path to a lxc config file
config file will be guessed from container name otherwise
.. versionadded:: 2015.8.0
force : False
If ``True``, the container will be force-stopped instead of gracefully
shut down
CLI Example:
.. code-block:: bash
salt myminion lxc.restart name
'''
_ensure_exists(name, path=path)
orig_state = state(name, path=path)
if orig_state != 'stopped':
stop(name, kill=force, path=path)
ret = start(name, path=path, lxc_config=lxc_config)
ret['state']['old'] = orig_state
if orig_state != 'stopped':
ret['restarted'] = True
return ret
def start(name, **kwargs):
'''
Start the named container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
lxc_config
path to a lxc config file
config file will be guessed from container name otherwise
.. versionadded:: 2015.8.0
use_vt
run the command through VT
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.start name
'''
path = kwargs.get('path', None)
cpath = get_root_path(path)
lxc_config = kwargs.get('lxc_config', None)
cmd = 'lxc-start'
if not lxc_config:
lxc_config = os.path.join(cpath, name, 'config')
# we try to start, even without config, if global opts are there
if os.path.exists(lxc_config):
cmd += ' -f {0}'.format(pipes.quote(lxc_config))
cmd += ' -d'
_ensure_exists(name, path=path)
if state(name, path=path) == 'frozen':
raise CommandExecutionError(
'Container \'{0}\' is frozen, use lxc.unfreeze'.format(name)
)
# lxc-start daemonize itself violently, we must not communicate with it
use_vt = kwargs.get('use_vt', None)
with_communicate = kwargs.get('with_communicate', False)
return _change_state(cmd, name, 'running',
stdout=None,
stderr=None,
stdin=None,
with_communicate=with_communicate,
path=path,
use_vt=use_vt)
def stop(name, kill=False, path=None, use_vt=None):
'''
Stop the named container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
kill: False
Do not wait for the container to stop, kill all tasks in the container.
Older LXC versions will stop containers like this irrespective of this
argument.
.. versionchanged:: 2015.5.0
Default value changed to ``False``
use_vt
run the command through VT
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.stop name
'''
_ensure_exists(name, path=path)
orig_state = state(name, path=path)
if orig_state == 'frozen' and not kill:
# Gracefully stopping a frozen container is slower than unfreezing and
# then stopping it (at least in my testing), so if we're not
# force-stopping the container, unfreeze it first.
unfreeze(name, path=path)
cmd = 'lxc-stop'
if kill:
cmd += ' -k'
ret = _change_state(cmd, name, 'stopped', use_vt=use_vt, path=path)
ret['state']['old'] = orig_state
return ret
def freeze(name, **kwargs):
'''
Freeze the named container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
start : False
If ``True`` and the container is stopped, the container will be started
before attempting to freeze.
.. versionadded:: 2015.5.0
use_vt
run the command through VT
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.freeze name
'''
use_vt = kwargs.get('use_vt', None)
path = kwargs.get('path', None)
_ensure_exists(name, path=path)
orig_state = state(name, path=path)
start_ = kwargs.get('start', False)
if orig_state == 'stopped':
if not start_:
raise CommandExecutionError(
'Container \'{0}\' is stopped'.format(name)
)
start(name, path=path)
cmd = 'lxc-freeze'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
ret = _change_state(cmd, name, 'frozen', use_vt=use_vt, path=path)
if orig_state == 'stopped' and start_:
ret['state']['old'] = orig_state
ret['started'] = True
ret['state']['new'] = state(name, path=path)
return ret
def unfreeze(name, path=None, use_vt=None):
'''
Unfreeze the named container.
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
use_vt
run the command through VT
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.unfreeze name
'''
_ensure_exists(name, path=path)
if state(name, path=path) == 'stopped':
raise CommandExecutionError(
'Container \'{0}\' is stopped'.format(name)
)
cmd = 'lxc-unfreeze'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
return _change_state(cmd, name, 'running', path=path, use_vt=use_vt)
def destroy(name, stop=False, path=None):
'''
Destroy the named container.
.. warning::
Destroys all data associated with the container.
path
path to the container parent directory (default: /var/lib/lxc)
.. versionadded:: 2015.8.0
stop : False
If ``True``, the container will be destroyed even if it is
running/frozen.
.. versionchanged:: 2015.5.0
Default value changed to ``False``. This more closely matches the
behavior of ``lxc-destroy(1)``, and also makes it less likely that
an accidental command will destroy a running container that was
being used for important things.
CLI Examples:
.. code-block:: bash
salt '*' lxc.destroy foo
salt '*' lxc.destroy foo stop=True
'''
_ensure_exists(name, path=path)
if not stop and state(name, path=path) != 'stopped':
raise CommandExecutionError(
'Container \'{0}\' is not stopped'.format(name)
)
return _change_state('lxc-destroy', name, None, path=path)
# Compatibility between LXC and nspawn
remove = salt.utils.functools.alias_function(destroy, 'remove')
def exists(name, path=None):
'''
Returns whether the named container exists.
path
path to the container parent directory (default: /var/lib/lxc)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.exists name
'''
_exists = name in ls_(path=path)
# container may be just created but we did cached earlier the
# lxc-ls results
if not _exists:
_exists = name in ls_(cache=False, path=path)
return _exists
def state(name, path=None):
'''
Returns the state of a container.
path
path to the container parent directory (default: /var/lib/lxc)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.state name
'''
# Don't use _ensure_exists() here, it will mess with _change_state()
cachekey = 'lxc.state.{0}{1}'.format(name, path)
try:
return __context__[cachekey]
except KeyError:
if not exists(name, path=path):
__context__[cachekey] = None
else:
cmd = 'lxc-info'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0}'.format(name)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
if ret['retcode'] != 0:
_clear_context()
raise CommandExecutionError(
'Unable to get state of container \'{0}\''.format(name)
)
c_infos = ret['stdout'].splitlines()
c_state = None
for c_info in c_infos:
stat = c_info.split(':')
if stat[0].lower() == 'state':
c_state = stat[1].strip().lower()
break
__context__[cachekey] = c_state
return __context__[cachekey]
def get_parameter(name, parameter, path=None):
'''
Returns the value of a cgroup parameter for a container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.get_parameter container_name memory.limit_in_bytes
'''
_ensure_exists(name, path=path)
cmd = 'lxc-cgroup'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0} {1}'.format(name, parameter)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
if ret['retcode'] != 0:
raise CommandExecutionError(
'Unable to retrieve value for \'{0}\''.format(parameter)
)
return ret['stdout'].strip()
def set_parameter(name, parameter, value, path=None):
'''
Set the value of a cgroup parameter for a container.
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.set_parameter name parameter value
'''
if not exists(name, path=path):
return None
cmd = 'lxc-cgroup'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0} {1} {2}'.format(name, parameter, value)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
if ret['retcode'] != 0:
return False
else:
return True
def info(name, path=None):
'''
Returns information about a container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.info name
'''
cachekey = 'lxc.info.{0}{1}'.format(name, path)
try:
return __context__[cachekey]
except KeyError:
_ensure_exists(name, path=path)
cpath = get_root_path(path)
try:
conf_file = os.path.join(cpath, name, 'config')
except AttributeError:
conf_file = os.path.join(cpath, six.text_type(name), 'config')
if not os.path.isfile(conf_file):
raise CommandExecutionError(
'LXC config file {0} does not exist'.format(conf_file)
)
ret = {}
config = []
with salt.utils.files.fopen(conf_file) as fp_:
for line in fp_:
line = salt.utils.stringutils.to_unicode(line)
comps = [x.strip() for x in
line.split('#', 1)[0].strip().split('=', 1)]
if len(comps) == 2:
config.append(tuple(comps))
ifaces = []
current = None
for key, val in config:
if key == 'lxc.network.type':
current = {'type': val}
ifaces.append(current)
elif not current:
continue
elif key.startswith('lxc.network.'):
current[key.replace('lxc.network.', '', 1)] = val
if ifaces:
ret['nics'] = ifaces
ret['rootfs'] = next(
(x[1] for x in config if x[0] == 'lxc.rootfs'),
None
)
ret['state'] = state(name, path=path)
ret['ips'] = []
ret['public_ips'] = []
ret['private_ips'] = []
ret['public_ipv4_ips'] = []
ret['public_ipv6_ips'] = []
ret['private_ipv4_ips'] = []
ret['private_ipv6_ips'] = []
ret['ipv4_ips'] = []
ret['ipv6_ips'] = []
ret['size'] = None
ret['config'] = conf_file
if ret['state'] == 'running':
try:
limit = int(get_parameter(name, 'memory.limit_in_bytes'))
except (CommandExecutionError, TypeError, ValueError):
limit = 0
try:
usage = int(get_parameter(name, 'memory.usage_in_bytes'))
except (CommandExecutionError, TypeError, ValueError):
usage = 0
free = limit - usage
ret['memory_limit'] = limit
ret['memory_free'] = free
size = run_stdout(name, 'df /', path=path, python_shell=False)
# The size is the 2nd column of the last line
ret['size'] = size.splitlines()[-1].split()[1]
# First try iproute2
ip_cmd = run_all(
name, 'ip link show', path=path, python_shell=False)
if ip_cmd['retcode'] == 0:
ip_data = ip_cmd['stdout']
ip_cmd = run_all(
name, 'ip addr show', path=path, python_shell=False)
ip_data += '\n' + ip_cmd['stdout']
ip_data = salt.utils.network._interfaces_ip(ip_data)
else:
# That didn't work, try ifconfig
ip_cmd = run_all(
name, 'ifconfig', path=path, python_shell=False)
if ip_cmd['retcode'] == 0:
ip_data = \
salt.utils.network._interfaces_ifconfig(
ip_cmd['stdout'])
else:
# Neither was successful, give up
log.warning(
'Unable to run ip or ifconfig in container \'%s\'', name
)
ip_data = {}
ret['ipv4_ips'] = salt.utils.network.ip_addrs(
include_loopback=True,
interface_data=ip_data
)
ret['ipv6_ips'] = salt.utils.network.ip_addrs6(
include_loopback=True,
interface_data=ip_data
)
ret['ips'] = ret['ipv4_ips'] + ret['ipv6_ips']
for address in ret['ipv4_ips']:
if address == '127.0.0.1':
ret['private_ips'].append(address)
ret['private_ipv4_ips'].append(address)
elif salt.utils.cloud.is_public_ip(address):
ret['public_ips'].append(address)
ret['public_ipv4_ips'].append(address)
else:
ret['private_ips'].append(address)
ret['private_ipv4_ips'].append(address)
for address in ret['ipv6_ips']:
if address == '::1' or address.startswith('fe80'):
ret['private_ips'].append(address)
ret['private_ipv6_ips'].append(address)
else:
ret['public_ips'].append(address)
ret['public_ipv6_ips'].append(address)
for key in [x for x in ret if x == 'ips' or x.endswith('ips')]:
ret[key].sort(key=_ip_sort)
__context__[cachekey] = ret
return __context__[cachekey]
def set_password(name, users, password, encrypted=True, path=None):
'''
.. versionchanged:: 2015.5.0
Function renamed from ``set_pass`` to ``set_password``. Additionally,
this function now supports (and defaults to using) a password hash
instead of a plaintext password.
Set the password of one or more system users inside containers
users
Comma-separated list (or python list) of users to change password
password
Password to set for the specified user(s)
encrypted : True
If true, ``password`` must be a password hash. Set to ``False`` to set
a plaintext password (not recommended).
.. versionadded:: 2015.5.0
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.set_pass container-name root '$6$uJ2uAyLU$KoI67t8As/0fXtJOPcHKGXmUpcoYUcVR2K6x93walnShTCQvjRwq25yIkiCBOqgbfdKQSFnAo28/ek6716vEV1'
salt '*' lxc.set_pass container-name root foo encrypted=False
'''
def _bad_user_input():
raise SaltInvocationError('Invalid input for \'users\' parameter')
if not isinstance(users, list):
try:
users = users.split(',')
except AttributeError:
_bad_user_input()
if not users:
_bad_user_input()
failed_users = []
for user in users:
result = retcode(name,
'chpasswd{0}'.format(' -e' if encrypted else ''),
stdin=':'.join((user, password)),
python_shell=False,
path=path,
chroot_fallback=True,
output_loglevel='quiet')
if result != 0:
failed_users.append(user)
if failed_users:
raise CommandExecutionError(
'Password change failed for the following user(s): {0}'
.format(', '.join(failed_users))
)
return True
set_pass = salt.utils.functools.alias_function(set_password, 'set_pass')
def update_lxc_conf(name, lxc_conf, lxc_conf_unset, path=None):
'''
Edit LXC configuration options
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.update_lxc_conf ubuntu \\
lxc_conf="[{'network.ipv4.ip':'10.0.3.5'}]" \\
lxc_conf_unset="['lxc.utsname']"
'''
_ensure_exists(name, path=path)
cpath = get_root_path(path)
lxc_conf_p = os.path.join(cpath, name, 'config')
if not os.path.exists(lxc_conf_p):
raise SaltInvocationError(
'Configuration file {0} does not exist'.format(lxc_conf_p)
)
changes = {'edited': [], 'added': [], 'removed': []}
ret = {'changes': changes, 'result': True, 'comment': ''}
# do not use salt.utils.files.fopen !
with salt.utils.files.fopen(lxc_conf_p, 'r') as fic:
filtered_lxc_conf = []
for row in lxc_conf:
if not row:
continue
for conf in row:
filtered_lxc_conf.append((conf.strip(),
row[conf].strip()))
ret['comment'] = 'lxc.conf is up to date'
lines = []
orig_config = salt.utils.stringutils.to_unicode(fic.read())
for line in orig_config.splitlines():
if line.startswith('#') or not line.strip():
lines.append([line, ''])
else:
line = line.split('=')
index = line.pop(0)
val = (index.strip(), '='.join(line).strip())
if val not in lines:
lines.append(val)
for key, item in filtered_lxc_conf:
matched = False
for idx, line in enumerate(lines[:]):
if line[0] == key:
matched = True
lines[idx] = (key, item)
if '='.join(line[1:]).strip() != item.strip():
changes['edited'].append(
({line[0]: line[1:]}, {key: item}))
break
if not matched:
if (key, item) not in lines:
lines.append((key, item))
changes['added'].append({key: item})
dest_lxc_conf = []
# filter unset
if lxc_conf_unset:
for line in lines:
for opt in lxc_conf_unset:
if (
not line[0].startswith(opt) and
line not in dest_lxc_conf
):
dest_lxc_conf.append(line)
else:
changes['removed'].append(opt)
else:
dest_lxc_conf = lines
conf = ''
for key, val in dest_lxc_conf:
if not val:
conf += '{0}\n'.format(key)
else:
conf += '{0} = {1}\n'.format(key.strip(), val.strip())
conf_changed = conf != orig_config
chrono = datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S')
if conf_changed:
# DO NOT USE salt.utils.files.fopen here, i got (kiorky)
# problems with lxc configs which were wiped !
with salt.utils.files.fopen('{0}.{1}'.format(lxc_conf_p, chrono), 'w') as wfic:
wfic.write(salt.utils.stringutils.to_str(conf))
with salt.utils.files.fopen(lxc_conf_p, 'w') as wfic:
wfic.write(salt.utils.stringutils.to_str(conf))
ret['comment'] = 'Updated'
ret['result'] = True
if not any(changes[x] for x in changes):
# Ensure an empty changes dict if nothing was modified
ret['changes'] = {}
return ret
def set_dns(name, dnsservers=None, searchdomains=None, path=None):
'''
.. versionchanged:: 2015.5.0
The ``dnsservers`` and ``searchdomains`` parameters can now be passed
as a comma-separated list.
Update /etc/resolv.confo
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.set_dns ubuntu "['8.8.8.8', '4.4.4.4']"
'''
if dnsservers is None:
dnsservers = ['8.8.8.8', '4.4.4.4']
elif not isinstance(dnsservers, list):
try:
dnsservers = dnsservers.split(',')
except AttributeError:
raise SaltInvocationError(
'Invalid input for \'dnsservers\' parameter'
)
if searchdomains is None:
searchdomains = []
elif not isinstance(searchdomains, list):
try:
searchdomains = searchdomains.split(',')
except AttributeError:
raise SaltInvocationError(
'Invalid input for \'searchdomains\' parameter'
)
dns = ['nameserver {0}'.format(x) for x in dnsservers]
dns.extend(['search {0}'.format(x) for x in searchdomains])
dns = '\n'.join(dns) + '\n'
# we may be using resolvconf in the container
# We need to handle that case with care:
# - we create the resolv.conf runtime directory (the
# linked directory) as anyway it will be shadowed when the real
# runned tmpfs mountpoint will be mounted.
# ( /etc/resolv.conf -> ../run/resolvconf/resolv.conf)
# Indeed, it can save us in any other case (running, eg, in a
# bare chroot when repairing or preparing the container for
# operation.
# - We also teach resolvconf to use the aforementioned dns.
# - We finally also set /etc/resolv.conf in all cases
rstr = __salt__['test.random_hash']()
# no tmp here, apparmor won't let us execute !
script = '/sbin/{0}_dns.sh'.format(rstr)
DNS_SCRIPT = "\n".join([
# 'set -x',
'#!/usr/bin/env bash',
'if [ -h /etc/resolv.conf ];then',
' if [ "x$(readlink /etc/resolv.conf)"'
' = "x../run/resolvconf/resolv.conf" ];then',
' if [ ! -d /run/resolvconf/ ];then',
' mkdir -p /run/resolvconf',
' fi',
' cat > /etc/resolvconf/resolv.conf.d/head <<EOF',
dns,
'EOF',
'',
' fi',
'fi',
'cat > /etc/resolv.conf <<EOF',
dns,
'EOF',
''])
result = run_all(
name, 'tee {0}'.format(script), path=path,
stdin=DNS_SCRIPT, python_shell=True)
if result['retcode'] == 0:
result = run_all(
name, 'sh -c "chmod +x {0};{0}"'.format(script),
path=path, python_shell=True)
# blindly delete the setter file
run_all(name,
'sh -c \'if [ -f "{0}" ];then rm -f "{0}";fi\''.format(script),
path=path, python_shell=True)
if result['retcode'] != 0:
error = ('Unable to write to /etc/resolv.conf in container \'{0}\''
.format(name))
if result['stderr']:
error += ': {0}'.format(result['stderr'])
raise CommandExecutionError(error)
return True
def running_systemd(name, cache=True, path=None):
'''
Determine if systemD is running
path
path to the container parent
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.running_systemd ubuntu
'''
k = 'lxc.systemd.test.{0}{1}'.format(name, path)
ret = __context__.get(k, None)
if ret is None or not cache:
rstr = __salt__['test.random_hash']()
# no tmp here, apparmor won't let us execute !
script = '/sbin/{0}_testsystemd.sh'.format(rstr)
# ubuntu already had since trusty some bits of systemd but was
# still using upstart ...
# we need to be a bit more careful that just testing that systemd
# is present
_script = textwrap.dedent(
'''\
#!/usr/bin/env bash
set -x
if ! command -v systemctl 1>/dev/null 2>/dev/null;then exit 2;fi
for i in \\
/run/systemd/journal/dev-log\\
/run/systemd/journal/flushed\\
/run/systemd/journal/kernel-seqnum\\
/run/systemd/journal/socket\\
/run/systemd/journal/stdout\\
/var/run/systemd/journal/dev-log\\
/var/run/systemd/journal/flushed\\
/var/run/systemd/journal/kernel-seqnum\\
/var/run/systemd/journal/socket\\
/var/run/systemd/journal/stdout\\
;do\\
if test -e ${i};then exit 0;fi
done
if test -d /var/systemd/system;then exit 0;fi
exit 2
''')
result = run_all(
name, 'tee {0}'.format(script), path=path,
stdin=_script, python_shell=True)
if result['retcode'] == 0:
result = run_all(name,
'sh -c "chmod +x {0};{0}"'''.format(script),
path=path,
python_shell=True)
else:
raise CommandExecutionError(
'lxc {0} failed to copy initd tester'.format(name))
run_all(name,
'sh -c \'if [ -f "{0}" ];then rm -f "{0}";fi\''
''.format(script),
path=path,
ignore_retcode=True,
python_shell=True)
if result['retcode'] != 0:
error = ('Unable to determine if the container \'{0}\''
' was running systemd, assmuming it is not.'
''.format(name))
if result['stderr']:
error += ': {0}'.format(result['stderr'])
# only cache result if we got a known exit code
if result['retcode'] in (0, 2):
__context__[k] = ret = not result['retcode']
return ret
def systemd_running_state(name, path=None):
'''
Get the operational state of a systemd based container
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.systemd_running_state ubuntu
'''
try:
ret = run_all(name,
'systemctl is-system-running',
path=path,
ignore_retcode=True)['stdout']
except CommandExecutionError:
ret = ''
return ret
def test_sd_started_state(name, path=None):
'''
Test if a systemd container is fully started
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.test_sd_started_state ubuntu
'''
qstate = systemd_running_state(name, path=path)
if qstate in ('initializing', 'starting'):
return False
elif qstate == '':
return None
else:
return True
def test_bare_started_state(name, path=None):
'''
Test if a non systemd container is fully started
For now, it consists only to test if the container is attachable
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.test_bare_started_state ubuntu
'''
try:
ret = run_all(
name, 'ls', path=path, ignore_retcode=True
)['retcode'] == 0
except (CommandExecutionError,):
ret = None
return ret
def wait_started(name, path=None, timeout=300):
'''
Check that the system has fully inited
This is actually very important for systemD based containers
see https://github.com/saltstack/salt/issues/23847
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.wait_started ubuntu
'''
if not exists(name, path=path):
raise CommandExecutionError(
'Container {0} does does exists'.format(name))
if not state(name, path=path) == 'running':
raise CommandExecutionError(
'Container {0} is not running'.format(name))
ret = False
if running_systemd(name, path=path):
test_started = test_sd_started_state
logger = log.error
else:
test_started = test_bare_started_state
logger = log.debug
now = time.time()
expire = now + timeout
now = time.time()
started = test_started(name, path=path)
while time.time() < expire and not started:
time.sleep(0.3)
started = test_started(name, path=path)
if started is None:
logger(
'Assuming %s is started, although we failed to detect that'
' is fully started correctly', name)
ret = True
else:
ret = started
return ret
def _needs_install(name, path=None):
ret = 0
has_minion = retcode(name,
'which salt-minion',
path=path,
ignore_retcode=True)
# we assume that installing is when no minion is running
# but testing the executable presence is not enougth for custom
# installs where the bootstrap can do much more than installing
# the bare salt binaries.
if has_minion:
processes = run_stdout(name, "ps aux", path=path)
if 'salt-minion' not in processes:
ret = 1
else:
retcode(name, 'salt-call --local service.stop salt-minion')
else:
ret = 1
return ret
def bootstrap(name,
config=None,
approve_key=True,
install=True,
pub_key=None,
priv_key=None,
bootstrap_url=None,
force_install=False,
unconditional_install=False,
path=None,
bootstrap_delay=None,
bootstrap_args=None,
bootstrap_shell=None):
'''
Install and configure salt in a container.
config
Minion configuration options. By default, the ``master`` option is set
to the target host's master.
approve_key
Request a pre-approval of the generated minion key. Requires
that the salt-master be configured to either auto-accept all keys or
expect a signing request from the target host. Default: ``True``
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
pub_key
Explicit public key to pressed the minion with (optional).
This can be either a filepath or a string representing the key
priv_key
Explicit private key to pressed the minion with (optional).
This can be either a filepath or a string representing the key
bootstrap_delay
Delay in seconds between end of container creation and bootstrapping.
Useful when waiting for container to obtain a DHCP lease.
.. versionadded:: 2015.5.0
bootstrap_url
url, content or filepath to the salt bootstrap script
bootstrap_args
salt bootstrap script arguments
bootstrap_shell
shell to execute the script into
install
Whether to attempt a full installation of salt-minion if needed.
force_install
Force installation even if salt-minion is detected,
this is the way to run vendor bootstrap scripts even
if a salt minion is already present in the container
unconditional_install
Run the script even if the container seems seeded
CLI Examples:
.. code-block:: bash
salt 'minion' lxc.bootstrap container_name [config=config_data] \\
[approve_key=(True|False)] [install=(True|False)]
'''
wait_started(name, path=path)
if bootstrap_delay is not None:
try:
log.info('LXC %s: bootstrap_delay: %s', name, bootstrap_delay)
time.sleep(bootstrap_delay)
except TypeError:
# Bad input, but assume since a value was passed that
# a delay was desired, and sleep for 5 seconds
time.sleep(5)
c_info = info(name, path=path)
if not c_info:
return None
# default set here as we cannot set them
# in def as it can come from a chain of procedures.
if bootstrap_args:
# custom bootstrap args can be totally customized, and user could
# have inserted the placeholder for the config directory.
# For example, some salt bootstrap script do not use at all -c
if '{0}' not in bootstrap_args:
bootstrap_args += ' -c {0}'
else:
bootstrap_args = '-c {0}'
if not bootstrap_shell:
bootstrap_shell = 'sh'
orig_state = _ensure_running(name, path=path)
if not orig_state:
return orig_state
if not force_install:
needs_install = _needs_install(name, path=path)
else:
needs_install = True
seeded = retcode(name,
'test -e \'{0}\''.format(SEED_MARKER),
path=path,
chroot_fallback=True,
ignore_retcode=True) == 0
tmp = tempfile.mkdtemp()
if seeded and not unconditional_install:
ret = True
else:
ret = False
cfg_files = __salt__['seed.mkconfig'](
config, tmp=tmp, id_=name, approve_key=approve_key,
pub_key=pub_key, priv_key=priv_key)
if needs_install or force_install or unconditional_install:
if install:
rstr = __salt__['test.random_hash']()
configdir = '/var/tmp/.c_{0}'.format(rstr)
cmd = 'install -m 0700 -d {0}'.format(configdir)
if run_all(
name, cmd, path=path, python_shell=False
)['retcode'] != 0:
log.error('tmpdir %s creation failed %s', configdir, cmd)
return False
bs_ = __salt__['config.gather_bootstrap_script'](
bootstrap=bootstrap_url)
script = '/sbin/{0}_bootstrap.sh'.format(rstr)
copy_to(name, bs_, script, path=path)
result = run_all(name,
'sh -c "chmod +x {0}"'.format(script),
path=path,
python_shell=True)
copy_to(name, cfg_files['config'],
os.path.join(configdir, 'minion'),
path=path)
copy_to(name, cfg_files['privkey'],
os.path.join(configdir, 'minion.pem'),
path=path)
copy_to(name, cfg_files['pubkey'],
os.path.join(configdir, 'minion.pub'),
path=path)
bootstrap_args = bootstrap_args.format(configdir)
cmd = ('{0} {2} {1}'
.format(bootstrap_shell,
bootstrap_args.replace("'", "''"),
script))
# log ASAP the forged bootstrap command which can be wrapped
# out of the output in case of unexpected problem
log.info('Running %s in LXC container \'%s\'', cmd, name)
ret = retcode(name, cmd, output_loglevel='info',
path=path, use_vt=True) == 0
run_all(name,
'sh -c \'if [ -f "{0}" ];then rm -f "{0}";fi\''
''.format(script),
path=path,
ignore_retcode=True,
python_shell=True)
else:
ret = False
else:
minion_config = salt.config.minion_config(cfg_files['config'])
pki_dir = minion_config['pki_dir']
copy_to(name,
cfg_files['config'],
'/etc/salt/minion',
path=path)
copy_to(name,
cfg_files['privkey'],
os.path.join(pki_dir, 'minion.pem'),
path=path)
copy_to(name,
cfg_files['pubkey'],
os.path.join(pki_dir, 'minion.pub'),
path=path)
run(name,
'salt-call --local service.enable salt-minion',
path=path,
python_shell=False)
ret = True
shutil.rmtree(tmp)
if orig_state == 'stopped':
stop(name, path=path)
elif orig_state == 'frozen':
freeze(name, path=path)
# mark seeded upon successful install
if ret:
run(name,
'touch \'{0}\''.format(SEED_MARKER),
path=path,
python_shell=False)
return ret
def attachable(name, path=None):
'''
Return True if the named container can be attached to via the lxc-attach
command
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt 'minion' lxc.attachable ubuntu
'''
cachekey = 'lxc.attachable{0}{1}'.format(name, path)
try:
return __context__[cachekey]
except KeyError:
_ensure_exists(name, path=path)
# Can't use run() here because it uses attachable() and would
# endlessly recurse, resulting in a traceback
log.debug('Checking if LXC container %s is attachable', name)
cmd = 'lxc-attach'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' --clear-env -n {0} -- /usr/bin/env'.format(name)
result = __salt__['cmd.retcode'](cmd,
python_shell=False,
output_loglevel='quiet',
ignore_retcode=True) == 0
__context__[cachekey] = result
return __context__[cachekey]
def _run(name,
cmd,
output=None,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=None,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
Common logic for lxc.run functions
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
'''
orig_state = state(name, path=path)
try:
if attachable(name, path=path):
ret = __salt__['container_resource.run'](
name,
cmd,
path=path,
container_type=__virtualname__,
exec_driver=EXEC_DRIVER,
output=output,
no_start=no_start,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
ignore_retcode=ignore_retcode,
use_vt=use_vt,
keep_env=keep_env)
else:
if not chroot_fallback:
raise CommandExecutionError(
'{0} is not attachable.'.format(name))
rootfs = info(name, path=path).get('rootfs')
# Set context var to make cmd.run_chroot run cmd.run instead of
# cmd.run_all.
__context__['cmd.run_chroot.func'] = __salt__['cmd.run']
ret = __salt__['cmd.run_chroot'](rootfs,
cmd,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
ignore_retcode=ignore_retcode)
except Exception:
raise
finally:
# Make sure we honor preserve_state, even if there was an exception
new_state = state(name, path=path)
if preserve_state:
if orig_state == 'stopped' and new_state != 'stopped':
stop(name, path=path)
elif orig_state == 'frozen' and new_state != 'frozen':
freeze(name, start=True, path=path)
if output in (None, 'all'):
return ret
else:
return ret[output]
def run(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.8.0
Run :mod:`cmd.run <salt.modules.cmdmod.run>` within a container
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed in stderr if the command being run
does not exist. If no output is returned using this function, try using
:mod:`lxc.run_stderr <salt.modules.lxc.run_stderr>` or
:mod:`lxc.run_all <salt.modules.lxc.run_all>`.
name
Name of the container in which to run the command
cmd
Command to run
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console. Assumes
``output=all``.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
CLI Example:
.. code-block:: bash
salt myminion lxc.run mycontainer 'ifconfig -a'
'''
return _run(name,
cmd,
path=path,
output=None,
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def run_stdout(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.5.0
Run :mod:`cmd.run_stdout <salt.modules.cmdmod.run_stdout>` within a container
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed in stderr if the command being run
does not exist. If no output is returned using this function, try using
:mod:`lxc.run_stderr <salt.modules.lxc.run_stderr>` or
:mod:`lxc.run_all <salt.modules.lxc.run_all>`.
name
Name of the container in which to run the command
cmd
Command to run
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console
``output=all``.
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
CLI Example:
.. code-block:: bash
salt myminion lxc.run_stdout mycontainer 'ifconfig -a'
'''
return _run(name,
cmd,
path=path,
output='stdout',
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def run_stderr(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.5.0
Run :mod:`cmd.run_stderr <salt.modules.cmdmod.run_stderr>` within a container
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed if the command being run does not
exist.
name
Name of the container in which to run the command
cmd
Command to run
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console
``output=all``.
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
CLI Example:
.. code-block:: bash
salt myminion lxc.run_stderr mycontainer 'ip addr show'
'''
return _run(name,
cmd,
path=path,
output='stderr',
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def retcode(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.5.0
Run :mod:`cmd.retcode <salt.modules.cmdmod.retcode>` within a container
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed in stderr if the command being run
does not exist. If the retcode is nonzero and not what was expected,
try using :mod:`lxc.run_stderr <salt.modules.lxc.run_stderr>`
or :mod:`lxc.run_all <salt.modules.lxc.run_all>`.
name
Name of the container in which to run the command
cmd
Command to run
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console
``output=all``.
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
CLI Example:
.. code-block:: bash
salt myminion lxc.retcode mycontainer 'ip addr show'
'''
return _run(name,
cmd,
output='retcode',
path=path,
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def run_all(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.5.0
Run :mod:`cmd.run_all <salt.modules.cmdmod.run_all>` within a container
.. note::
While the command is run within the container, it is initiated from the
host. Therefore, the PID in the return dict is from the host, not from
the container.
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed in stderr if the command being run
does not exist.
name
Name of the container in which to run the command
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
cmd
Command to run
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console
``output=all``.
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
CLI Example:
.. code-block:: bash
salt myminion lxc.run_all mycontainer 'ip addr show'
'''
return _run(name,
cmd,
output='all',
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
path=path,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def _get_md5(name, path):
'''
Get the MD5 checksum of a file from a container
'''
output = run_stdout(name, 'md5sum "{0}"'.format(path),
chroot_fallback=True,
ignore_retcode=True)
try:
return output.split()[0]
except IndexError:
# Destination file does not exist or could not be accessed
return None
def copy_to(name, source, dest, overwrite=False, makedirs=False, path=None):
'''
.. versionchanged:: 2015.8.0
Function renamed from ``lxc.cp`` to ``lxc.copy_to`` for consistency
with other container types. ``lxc.cp`` will continue to work, however.
For versions 2015.2.x and earlier, use ``lxc.cp``.
Copy a file or directory from the host into a container
name
Container name
source
File to be copied to the container
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
dest
Destination on the container. Must be an absolute path.
.. versionchanged:: 2015.5.0
If the destination is a directory, the file will be copied into
that directory.
overwrite : False
Unless this option is set to ``True``, then if a file exists at the
location specified by the ``dest`` argument, an error will be raised.
.. versionadded:: 2015.8.0
makedirs : False
Create the parent directory on the container if it does not already
exist.
.. versionadded:: 2015.5.0
CLI Example:
.. code-block:: bash
salt 'minion' lxc.copy_to /tmp/foo /root/foo
salt 'minion' lxc.cp /tmp/foo /root/foo
'''
_ensure_running(name, no_start=True, path=path)
return __salt__['container_resource.copy_to'](
name,
source,
dest,
container_type=__virtualname__,
path=path,
exec_driver=EXEC_DRIVER,
overwrite=overwrite,
makedirs=makedirs)
cp = salt.utils.functools.alias_function(copy_to, 'cp')
def read_conf(conf_file, out_format='simple'):
'''
Read in an LXC configuration file. By default returns a simple, unsorted
dict, but can also return a more detailed structure including blank lines
and comments.
out_format:
set to 'simple' if you need the old and unsupported behavior.
This won't support the multiple lxc values (eg: multiple network nics)
CLI Examples:
.. code-block:: bash
salt 'minion' lxc.read_conf /etc/lxc/mycontainer.conf
salt 'minion' lxc.read_conf /etc/lxc/mycontainer.conf out_format=commented
'''
ret_commented = []
ret_simple = {}
with salt.utils.files.fopen(conf_file, 'r') as fp_:
for line in salt.utils.data.decode(fp_.readlines()):
if '=' not in line:
ret_commented.append(line)
continue
comps = line.split('=')
value = '='.join(comps[1:]).strip()
comment = None
if value.strip().startswith('#'):
vcomps = value.strip().split('#')
value = vcomps[1].strip()
comment = '#'.join(vcomps[1:]).strip()
ret_commented.append({comps[0].strip(): {
'value': value,
'comment': comment,
}})
else:
ret_commented.append({comps[0].strip(): value})
ret_simple[comps[0].strip()] = value
if out_format == 'simple':
return ret_simple
return ret_commented
def write_conf(conf_file, conf):
'''
Write out an LXC configuration file
This is normally only used internally. The format of the data structure
must match that which is returned from ``lxc.read_conf()``, with
``out_format`` set to ``commented``.
An example might look like:
.. code-block:: python
[
{'lxc.utsname': '$CONTAINER_NAME'},
'# This is a commented line\\n',
'\\n',
{'lxc.mount': '$CONTAINER_FSTAB'},
{'lxc.rootfs': {'comment': 'This is another test',
'value': 'This is another test'}},
'\\n',
{'lxc.network.type': 'veth'},
{'lxc.network.flags': 'up'},
{'lxc.network.link': 'br0'},
{'lxc.network.mac': '$CONTAINER_MACADDR'},
{'lxc.network.ipv4': '$CONTAINER_IPADDR'},
{'lxc.network.name': '$CONTAINER_DEVICENAME'},
]
CLI Example:
.. code-block:: bash
salt 'minion' lxc.write_conf /etc/lxc/mycontainer.conf \\
out_format=commented
'''
if not isinstance(conf, list):
raise SaltInvocationError('Configuration must be passed as a list')
# construct the content prior to write to the file
# to avoid half written configs
content = ''
for line in conf:
if isinstance(line, (six.text_type, six.string_types)):
content += line
elif isinstance(line, dict):
for key in list(line.keys()):
out_line = None
if isinstance(
line[key],
(six.text_type, six.string_types, six.integer_types, float)
):
out_line = ' = '.join((key, "{0}".format(line[key])))
elif isinstance(line[key], dict):
out_line = ' = '.join((key, line[key]['value']))
if 'comment' in line[key]:
out_line = ' # '.join((out_line, line[key]['comment']))
if out_line:
content += out_line
content += '\n'
with salt.utils.files.fopen(conf_file, 'w') as fp_:
fp_.write(salt.utils.stringutils.to_str(content))
return {}
def edit_conf(conf_file,
out_format='simple',
read_only=False,
lxc_config=None,
**kwargs):
'''
Edit an LXC configuration file. If a setting is already present inside the
file, its value will be replaced. If it does not exist, it will be appended
to the end of the file. Comments and blank lines will be kept in-tact if
they already exist in the file.
out_format:
Set to simple if you need backward compatibility (multiple items for a
simple key is not supported)
read_only:
return only the edited configuration without applying it
to the underlying lxc configuration file
lxc_config:
List of dict containning lxc configuration items
For network configuration, you also need to add the device it belongs
to, otherwise it will default to eth0.
Also, any change to a network parameter will result in the whole
network reconfiguration to avoid mismatchs, be aware of that !
After the file is edited, its contents will be returned. By default, it
will be returned in ``simple`` format, meaning an unordered dict (which
may not represent the actual file order). Passing in an ``out_format`` of
``commented`` will return a data structure which accurately represents the
order and content of the file.
CLI Example:
.. code-block:: bash
salt 'minion' lxc.edit_conf /etc/lxc/mycontainer.conf \\
out_format=commented lxc.network.type=veth
salt 'minion' lxc.edit_conf /etc/lxc/mycontainer.conf \\
out_format=commented \\
lxc_config="[{'lxc.network.name': 'eth0', \\
'lxc.network.ipv4': '1.2.3.4'},
{'lxc.network.name': 'eth2', \\
'lxc.network.ipv4': '1.2.3.5',\\
'lxc.network.gateway': '1.2.3.1'}]"
'''
data = []
try:
conf = read_conf(conf_file, out_format=out_format)
except Exception:
conf = []
if not lxc_config:
lxc_config = []
lxc_config = copy.deepcopy(lxc_config)
# search if we want to access net config
# in that case, we will replace all the net configuration
net_config = []
for lxc_kws in lxc_config + [kwargs]:
net_params = {}
for kwarg in [a for a in lxc_kws]:
if kwarg.startswith('__'):
continue
if kwarg.startswith('lxc.network.'):
net_params[kwarg] = lxc_kws[kwarg]
lxc_kws.pop(kwarg, None)
if net_params:
net_config.append(net_params)
nic_opts = salt.utils.odict.OrderedDict()
for params in net_config:
dev = params.get('lxc.network.name', DEFAULT_NIC)
dev_opts = nic_opts.setdefault(dev, salt.utils.odict.OrderedDict())
for param in params:
opt = param.replace('lxc.network.', '')
opt = {'hwaddr': 'mac'}.get(opt, opt)
dev_opts[opt] = params[param]
net_changes = []
if nic_opts:
net_changes = _config_list(conf, only_net=True,
**{'network_profile': DEFAULT_NIC,
'nic_opts': nic_opts})
if net_changes:
lxc_config.extend(net_changes)
for line in conf:
if not isinstance(line, dict):
data.append(line)
continue
else:
for key in list(line.keys()):
val = line[key]
if net_changes and key.startswith('lxc.network.'):
continue
found = False
for ix in range(len(lxc_config)):
kw = lxc_config[ix]
if key in kw:
found = True
data.append({key: kw[key]})
del kw[key]
if not found:
data.append({key: val})
for lxc_kws in lxc_config:
for kwarg in lxc_kws:
data.append({kwarg: lxc_kws[kwarg]})
if read_only:
return data
write_conf(conf_file, data)
return read_conf(conf_file, out_format)
def reboot(name, path=None):
'''
Reboot a container.
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Examples:
.. code-block:: bash
salt 'minion' lxc.reboot myvm
'''
ret = {'result': True,
'changes': {},
'comment': '{0} rebooted'.format(name)}
does_exist = exists(name, path=path)
if does_exist and (state(name, path=path) == 'running'):
try:
stop(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
ret['result'] = False
return ret
if does_exist and (state(name, path=path) != 'running'):
try:
start(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
ret['result'] = False
return ret
ret['changes'][name] = 'rebooted'
return ret
def reconfigure(name,
cpu=None,
cpuset=None,
cpushare=None,
memory=None,
profile=None,
network_profile=None,
nic_opts=None,
bridge=None,
gateway=None,
autostart=None,
utsname=None,
rootfs=None,
path=None,
**kwargs):
'''
Reconfigure a container.
This only applies to a few property
name
Name of the container.
utsname
utsname of the container.
.. versionadded:: 2016.3.0
rootfs
rootfs of the container.
.. versionadded:: 2016.3.0
cpu
Select a random number of cpu cores and assign it to the cpuset, if the
cpuset option is set then this option will be ignored
cpuset
Explicitly define the cpus this container will be bound to
cpushare
cgroups cpu shares.
autostart
autostart container on reboot
memory
cgroups memory limit, in MB.
(0 for nolimit, None for old default 1024MB)
gateway
the ipv4 gateway to use
the default does nothing more than lxcutils does
bridge
the bridge to use
the default does nothing more than lxcutils does
nic
Network interfaces profile (defined in config or pillar).
nic_opts
Extra options for network interfaces, will override
``{"eth0": {"mac": "aa:bb:cc:dd:ee:ff", "ipv4": "10.1.1.1", "ipv6": "2001:db8::ff00:42:8329"}}``
or
``{"eth0": {"mac": "aa:bb:cc:dd:ee:ff", "ipv4": "10.1.1.1/24", "ipv6": "2001:db8::ff00:42:8329"}}``
path
path to the container parent
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt-call -lall mc_lxc_fork.reconfigure foobar nic_opts="{'eth1': {'mac': '00:16:3e:dd:ee:44'}}" memory=4
'''
changes = {}
cpath = get_root_path(path)
path = os.path.join(cpath, name, 'config')
ret = {'name': name,
'comment': 'config for {0} up to date'.format(name),
'result': True,
'changes': changes}
profile = get_container_profile(copy.deepcopy(profile))
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, _marker)
profile_match = profile.pop(key, default)
# let kwarg overrides be the preferred choice
if kw_overrides_match is _marker:
return profile_match
return kw_overrides_match
if nic_opts is not None and not network_profile:
network_profile = DEFAULT_NIC
if autostart is not None:
autostart = select('autostart', autostart)
else:
autostart = 'keep'
if not utsname:
utsname = select('utsname', utsname)
if os.path.exists(path):
old_chunks = read_conf(path, out_format='commented')
make_kw = salt.utils.odict.OrderedDict([
('utsname', utsname),
('rootfs', rootfs),
('autostart', autostart),
('cpu', cpu),
('gateway', gateway),
('cpuset', cpuset),
('cpushare', cpushare),
('network_profile', network_profile),
('nic_opts', nic_opts),
('bridge', bridge)])
# match 0 and none as memory = 0 in lxc config is harmful
if memory:
make_kw['memory'] = memory
kw = salt.utils.odict.OrderedDict()
for key, val in six.iteritems(make_kw):
if val is not None:
kw[key] = val
new_cfg = _config_list(conf_tuples=old_chunks, **kw)
if new_cfg:
edit_conf(path, out_format='commented', lxc_config=new_cfg)
chunks = read_conf(path, out_format='commented')
if old_chunks != chunks:
ret['comment'] = '{0} lxc config updated'.format(name)
if state(name, path=path) == 'running':
cret = reboot(name, path=path)
ret['result'] = cret['result']
return ret
def apply_network_profile(name, network_profile, nic_opts=None, path=None):
'''
.. versionadded:: 2015.5.0
Apply a network profile to a container
network_profile
profile name or default values (dict)
nic_opts
values to override in defaults (dict)
indexed by nic card names
path
path to the container parent
.. versionadded:: 2015.8.0
CLI Examples:
.. code-block:: bash
salt 'minion' lxc.apply_network_profile web1 centos
salt 'minion' lxc.apply_network_profile web1 centos \\
nic_opts="{'eth0': {'mac': 'xx:xx:xx:xx:xx:xx'}}"
salt 'minion' lxc.apply_network_profile web1 \\
"{'eth0': {'mac': 'xx:xx:xx:xx:xx:yy'}}"
nic_opts="{'eth0': {'mac': 'xx:xx:xx:xx:xx:xx'}}"
The special case to disable use of ethernet nics:
.. code-block:: bash
salt 'minion' lxc.apply_network_profile web1 centos \\
"{eth0: {disable: true}}"
'''
cpath = get_root_path(path)
cfgpath = os.path.join(cpath, name, 'config')
before = []
with salt.utils.files.fopen(cfgpath, 'r') as fp_:
for line in fp_:
before.append(line)
lxcconfig = _LXCConfig(name=name, path=path)
old_net = lxcconfig._filter_data('lxc.network')
network_params = {}
for param in _network_conf(
conf_tuples=old_net,
network_profile=network_profile, nic_opts=nic_opts
):
network_params.update(param)
if network_params:
edit_conf(cfgpath, out_format='commented', **network_params)
after = []
with salt.utils.files.fopen(cfgpath, 'r') as fp_:
for line in fp_:
after.append(line)
diff = ''
for line in difflib.unified_diff(before,
after,
fromfile='before',
tofile='after'):
diff += line
return diff
def get_pid(name, path=None):
'''
Returns a container pid.
Throw an exception if the container isn't running.
CLI Example:
.. code-block:: bash
salt '*' lxc.get_pid name
'''
if name not in list_(limit='running', path=path):
raise CommandExecutionError('Container {0} is not running, can\'t determine PID'.format(name))
info = __salt__['cmd.run']('lxc-info -n {0}'.format(name)).split("\n")
pid = [line.split(':')[1].strip() for line in info if re.match(r'\s*PID', line)][0]
return pid
def add_veth(name, interface_name, bridge=None, path=None):
'''
Add a veth to a container.
Note : this function doesn't update the container config, just add the interface at runtime
name
Name of the container
interface_name
Name of the interface in the container
bridge
Name of the bridge to attach the interface to (facultative)
CLI Examples:
.. code-block:: bash
salt '*' lxc.add_veth container_name eth1 br1
salt '*' lxc.add_veth container_name eth1
'''
# Get container init PID
pid = get_pid(name, path=path)
# Generate a ramdom string for veth and ensure that is isn't present on the system
while True:
random_veth = 'veth'+''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(6))
if random_veth not in __salt__['network.interfaces']().keys():
break
# Check prerequisites
if not __salt__['file.directory_exists']('/var/run/'):
raise CommandExecutionError('Directory /var/run required for lxc.add_veth doesn\'t exists')
if not __salt__['file.file_exists']('/proc/{0}/ns/net'.format(pid)):
raise CommandExecutionError('Proc file for container {0} network namespace doesn\'t exists'.format(name))
if not __salt__['file.directory_exists']('/var/run/netns'):
__salt__['file.mkdir']('/var/run/netns')
# Ensure that the symlink is up to date (change on container restart)
if __salt__['file.is_link']('/var/run/netns/{0}'.format(name)):
__salt__['file.remove']('/var/run/netns/{0}'.format(name))
__salt__['file.symlink']('/proc/{0}/ns/net'.format(pid), '/var/run/netns/{0}'.format(name))
# Ensure that interface doesn't exists
interface_exists = 0 == __salt__['cmd.retcode']('ip netns exec {netns} ip address list {interface}'.format(
netns=name,
interface=interface_name
))
if interface_exists:
raise CommandExecutionError('Interface {interface} already exists in {container}'.format(
interface=interface_name,
container=name
))
# Create veth and bring it up
if __salt__['cmd.retcode']('ip link add name {veth} type veth peer name {veth}_c'.format(veth=random_veth)) != 0:
raise CommandExecutionError('Error while creating the veth pair {0}'.format(random_veth))
if __salt__['cmd.retcode']('ip link set dev {0} up'.format(random_veth)) != 0:
raise CommandExecutionError('Error while bringing up host-side veth {0}'.format(random_veth))
# Attach it to the container
attached = 0 == __salt__['cmd.retcode']('ip link set dev {veth}_c netns {container} name {interface_name}'.format(
veth=random_veth,
container=name,
interface_name=interface_name
))
if not attached:
raise CommandExecutionError('Error while attaching the veth {veth} to container {container}'.format(
veth=random_veth,
container=name
))
__salt__['file.remove']('/var/run/netns/{0}'.format(name))
if bridge is not None:
__salt__['bridge.addif'](bridge, random_veth)
|
saltstack/salt
|
salt/modules/lxc.py
|
init
|
python
|
def init(name,
config=None,
cpuset=None,
cpushare=None,
memory=None,
profile=None,
network_profile=None,
nic_opts=None,
cpu=None,
autostart=True,
password=None,
password_encrypted=None,
users=None,
dnsservers=None,
searchdomains=None,
bridge=None,
gateway=None,
pub_key=None,
priv_key=None,
force_install=False,
unconditional_install=False,
bootstrap_delay=None,
bootstrap_args=None,
bootstrap_shell=None,
bootstrap_url=None,
**kwargs):
'''
Initialize a new container.
This is a partial idempotent function as if it is already provisioned, we
will reset a bit the lxc configuration file but much of the hard work will
be escaped as markers will prevent re-execution of harmful tasks.
name
Name of the container
image
A tar archive to use as the rootfs for the container. Conflicts with
the ``template`` argument.
cpus
Select a random number of cpu cores and assign it to the cpuset, if the
cpuset option is set then this option will be ignored
cpuset
Explicitly define the cpus this container will be bound to
cpushare
cgroups cpu shares
autostart
autostart container on reboot
memory
cgroups memory limit, in MB
.. versionchanged:: 2015.5.0
If no value is passed, no limit is set. In earlier Salt versions,
not passing this value causes a 1024MB memory limit to be set, and
it was necessary to pass ``memory=0`` to set no limit.
gateway
the ipv4 gateway to use
the default does nothing more than lxcutils does
bridge
the bridge to use
the default does nothing more than lxcutils does
network_profile
Network profile to use for the container
.. versionadded:: 2015.5.0
nic_opts
Extra options for network interfaces, will override
``{"eth0": {"hwaddr": "aa:bb:cc:dd:ee:ff", "ipv4": "10.1.1.1", "ipv6": "2001:db8::ff00:42:8329"}}``
or
``{"eth0": {"hwaddr": "aa:bb:cc:dd:ee:ff", "ipv4": "10.1.1.1/24", "ipv6": "2001:db8::ff00:42:8329"}}``
users
Users for which the password defined in the ``password`` param should
be set. Can be passed as a comma separated list or a python list.
Defaults to just the ``root`` user.
password
Set the initial password for the users defined in the ``users``
parameter
password_encrypted : False
Set to ``True`` to denote a password hash instead of a plaintext
password
.. versionadded:: 2015.5.0
profile
A LXC profile (defined in config or pillar).
This can be either a real profile mapping or a string
to retrieve it in configuration
start
Start the newly-created container
dnsservers
list of dns servers to set in the container, default [] (no setting)
seed
Seed the container with the minion config. Default: ``True``
install
If salt-minion is not already installed, install it. Default: ``True``
config
Optional config parameters. By default, the id is set to
the name of the container.
master
salt master (default to minion's master)
master_port
salt master port (default to minion's master port)
pub_key
Explicit public key to preseed the minion with (optional).
This can be either a filepath or a string representing the key
priv_key
Explicit private key to preseed the minion with (optional).
This can be either a filepath or a string representing the key
approve_key
If explicit preseeding is not used;
Attempt to request key approval from the master. Default: ``True``
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
clone_from
Original from which to use a clone operation to create the container.
Default: ``None``
bootstrap_delay
Delay in seconds between end of container creation and bootstrapping.
Useful when waiting for container to obtain a DHCP lease.
.. versionadded:: 2015.5.0
bootstrap_url
See lxc.bootstrap
bootstrap_shell
See lxc.bootstrap
bootstrap_args
See lxc.bootstrap
force_install
Force installation even if salt-minion is detected,
this is the way to run vendor bootstrap scripts even
if a salt minion is already present in the container
unconditional_install
Run the script even if the container seems seeded
CLI Example:
.. code-block:: bash
salt 'minion' lxc.init name [cpuset=cgroups_cpuset] \\
[cpushare=cgroups_cpushare] [memory=cgroups_memory] \\
[nic=nic_profile] [profile=lxc_profile] \\
[nic_opts=nic_opts] [start=(True|False)] \\
[seed=(True|False)] [install=(True|False)] \\
[config=minion_config] [approve_key=(True|False) \\
[clone_from=original] [autostart=True] \\
[priv_key=/path_or_content] [pub_key=/path_or_content] \\
[bridge=lxcbr0] [gateway=10.0.3.1] \\
[dnsservers[dns1,dns2]] \\
[users=[foo]] [password='secret'] \\
[password_encrypted=(True|False)]
'''
ret = {'name': name,
'changes': {}}
profile = get_container_profile(copy.deepcopy(profile))
if not network_profile:
network_profile = profile.get('network_profile')
if not network_profile:
network_profile = DEFAULT_NIC
# Changes is a pointer to changes_dict['init']. This method is used so that
# we can have a list of changes as they are made, providing an ordered list
# of things that were changed.
changes_dict = {'init': []}
changes = changes_dict.get('init')
if users is None:
users = []
dusers = ['root']
for user in dusers:
if user not in users:
users.append(user)
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, _marker)
profile_match = profile.pop(key, default)
# let kwarg overrides be the preferred choice
if kw_overrides_match is _marker:
return profile_match
return kw_overrides_match
path = select('path')
bpath = get_root_path(path)
state_pre = state(name, path=path)
tvg = select('vgname')
vgname = tvg if tvg else __salt__['config.get']('lxc.vgname')
start_ = select('start', True)
autostart = select('autostart', autostart)
seed = select('seed', True)
install = select('install', True)
seed_cmd = select('seed_cmd')
salt_config = _get_salt_config(config, **kwargs)
approve_key = select('approve_key', True)
clone_from = select('clone_from')
# If using a volume group then set up to make snapshot cow clones
if vgname and not clone_from:
try:
kwargs['vgname'] = vgname
clone_from = _get_base(profile=profile, **kwargs)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = exc.strerror
if changes:
ret['changes'] = changes_dict
return ret
if not kwargs.get('snapshot') is False:
kwargs['snapshot'] = True
does_exist = exists(name, path=path)
to_reboot = False
remove_seed_marker = False
if does_exist:
pass
elif clone_from:
remove_seed_marker = True
try:
clone(name, clone_from, profile=profile, **kwargs)
changes.append({'create': 'Container cloned'})
except (SaltInvocationError, CommandExecutionError) as exc:
if 'already exists' in exc.strerror:
changes.append({'create': 'Container already exists'})
else:
ret['result'] = False
ret['comment'] = exc.strerror
if changes:
ret['changes'] = changes_dict
return ret
cfg = _LXCConfig(name=name, network_profile=network_profile,
nic_opts=nic_opts, bridge=bridge, path=path,
gateway=gateway, autostart=autostart,
cpuset=cpuset, cpushare=cpushare, memory=memory)
old_chunks = read_conf(cfg.path, out_format='commented')
cfg.write()
chunks = read_conf(cfg.path, out_format='commented')
if old_chunks != chunks:
to_reboot = True
else:
remove_seed_marker = True
cfg = _LXCConfig(network_profile=network_profile,
nic_opts=nic_opts, cpuset=cpuset, path=path,
bridge=bridge, gateway=gateway,
autostart=autostart,
cpushare=cpushare, memory=memory)
with cfg.tempfile() as cfile:
try:
create(name, config=cfile.name, profile=profile, **kwargs)
changes.append({'create': 'Container created'})
except (SaltInvocationError, CommandExecutionError) as exc:
if 'already exists' in exc.strerror:
changes.append({'create': 'Container already exists'})
else:
ret['comment'] = exc.strerror
if changes:
ret['changes'] = changes_dict
return ret
cpath = os.path.join(bpath, name, 'config')
old_chunks = []
if os.path.exists(cpath):
old_chunks = read_conf(cpath, out_format='commented')
new_cfg = _config_list(conf_tuples=old_chunks,
cpu=cpu,
network_profile=network_profile,
nic_opts=nic_opts, bridge=bridge,
cpuset=cpuset, cpushare=cpushare,
memory=memory)
if new_cfg:
edit_conf(cpath, out_format='commented', lxc_config=new_cfg)
chunks = read_conf(cpath, out_format='commented')
if old_chunks != chunks:
to_reboot = True
# last time to be sure any of our property is correctly applied
cfg = _LXCConfig(name=name, network_profile=network_profile,
nic_opts=nic_opts, bridge=bridge, path=path,
gateway=gateway, autostart=autostart,
cpuset=cpuset, cpushare=cpushare, memory=memory)
old_chunks = []
if os.path.exists(cfg.path):
old_chunks = read_conf(cfg.path, out_format='commented')
cfg.write()
chunks = read_conf(cfg.path, out_format='commented')
if old_chunks != chunks:
changes.append({'config': 'Container configuration updated'})
to_reboot = True
if to_reboot:
try:
stop(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
if changes:
ret['changes'] = changes_dict
return ret
if not does_exist or (does_exist and state(name, path=path) != 'running'):
try:
start(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
if changes:
ret['changes'] = changes_dict
return ret
if remove_seed_marker:
run(name,
'rm -f \'{0}\''.format(SEED_MARKER),
path=path,
chroot_fallback=False,
python_shell=False)
# set the default user/password, only the first time
if ret.get('result', True) and password:
gid = '/.lxc.initial_pass'
gids = [gid,
'/lxc.initial_pass',
'/.lxc.{0}.initial_pass'.format(name)]
if not any(retcode(name,
'test -e "{0}"'.format(x),
chroot_fallback=True,
path=path,
ignore_retcode=True) == 0
for x in gids):
# think to touch the default user generated by default templates
# which has a really unsecure passwords...
# root is defined as a member earlier in the code
for default_user in ['ubuntu']:
if (
default_user not in users and
retcode(name,
'id {0}'.format(default_user),
python_shell=False,
path=path,
chroot_fallback=True,
ignore_retcode=True) == 0
):
users.append(default_user)
for user in users:
try:
cret = set_password(name,
users=[user],
path=path,
password=password,
encrypted=password_encrypted)
except (SaltInvocationError, CommandExecutionError) as exc:
msg = '{0}: Failed to set password'.format(
user) + exc.strerror
# only hardfail in unrecoverable situation:
# root cannot be setted up
if user == 'root':
ret['comment'] = msg
ret['result'] = False
else:
log.debug(msg)
if ret.get('result', True):
changes.append({'password': 'Password(s) updated'})
if retcode(name,
('sh -c \'touch "{0}"; test -e "{0}"\''
.format(gid)),
path=path,
chroot_fallback=True,
ignore_retcode=True) != 0:
ret['comment'] = 'Failed to set password marker'
changes[-1]['password'] += '. ' + ret['comment'] + '.'
ret['result'] = False
# set dns servers if any, only the first time
if ret.get('result', True) and dnsservers:
# retro compatibility, test also old markers
gid = '/.lxc.initial_dns'
gids = [gid,
'/lxc.initial_dns',
'/lxc.{0}.initial_dns'.format(name)]
if not any(retcode(name,
'test -e "{0}"'.format(x),
chroot_fallback=True,
path=path,
ignore_retcode=True) == 0
for x in gids):
try:
set_dns(name,
path=path,
dnsservers=dnsservers,
searchdomains=searchdomains)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Failed to set DNS: ' + exc.strerror
ret['result'] = False
else:
changes.append({'dns': 'DNS updated'})
if retcode(name,
('sh -c \'touch "{0}"; test -e "{0}"\''
.format(gid)),
chroot_fallback=True,
path=path,
ignore_retcode=True) != 0:
ret['comment'] = 'Failed to set DNS marker'
changes[-1]['dns'] += '. ' + ret['comment'] + '.'
ret['result'] = False
# retro compatibility, test also old markers
if remove_seed_marker:
run(name,
'rm -f \'{0}\''.format(SEED_MARKER),
path=path,
python_shell=False)
gid = '/.lxc.initial_seed'
gids = [gid, '/lxc.initial_seed']
if (
any(retcode(name,
'test -e {0}'.format(x),
path=path,
chroot_fallback=True,
ignore_retcode=True) == 0
for x in gids) or not ret.get('result', True)
):
pass
elif seed or seed_cmd:
if seed:
try:
result = bootstrap(
name, config=salt_config, path=path,
approve_key=approve_key,
pub_key=pub_key, priv_key=priv_key,
install=install,
force_install=force_install,
unconditional_install=unconditional_install,
bootstrap_delay=bootstrap_delay,
bootstrap_url=bootstrap_url,
bootstrap_shell=bootstrap_shell,
bootstrap_args=bootstrap_args)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Bootstrap failed: ' + exc.strerror
ret['result'] = False
else:
if not result:
ret['comment'] = ('Bootstrap failed, see minion log for '
'more information')
ret['result'] = False
else:
changes.append(
{'bootstrap': 'Container successfully bootstrapped'}
)
elif seed_cmd:
try:
result = __salt__[seed_cmd](info(name, path=path)['rootfs'],
name,
salt_config)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = ('Bootstrap via seed_cmd \'{0}\' failed: {1}'
.format(seed_cmd, exc.strerror))
ret['result'] = False
else:
if not result:
ret['comment'] = ('Bootstrap via seed_cmd \'{0}\' failed, '
'see minion log for more information '
.format(seed_cmd))
ret['result'] = False
else:
changes.append(
{'bootstrap': 'Container successfully bootstrapped '
'using seed_cmd \'{0}\''
.format(seed_cmd)}
)
if ret.get('result', True) and not start_:
try:
stop(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
ret['result'] = False
state_post = state(name, path=path)
if state_pre != state_post:
changes.append({'state': {'old': state_pre, 'new': state_post}})
if ret.get('result', True):
ret['comment'] = ('Container \'{0}\' successfully initialized'
.format(name))
ret['result'] = True
if changes:
ret['changes'] = changes_dict
return ret
|
Initialize a new container.
This is a partial idempotent function as if it is already provisioned, we
will reset a bit the lxc configuration file but much of the hard work will
be escaped as markers will prevent re-execution of harmful tasks.
name
Name of the container
image
A tar archive to use as the rootfs for the container. Conflicts with
the ``template`` argument.
cpus
Select a random number of cpu cores and assign it to the cpuset, if the
cpuset option is set then this option will be ignored
cpuset
Explicitly define the cpus this container will be bound to
cpushare
cgroups cpu shares
autostart
autostart container on reboot
memory
cgroups memory limit, in MB
.. versionchanged:: 2015.5.0
If no value is passed, no limit is set. In earlier Salt versions,
not passing this value causes a 1024MB memory limit to be set, and
it was necessary to pass ``memory=0`` to set no limit.
gateway
the ipv4 gateway to use
the default does nothing more than lxcutils does
bridge
the bridge to use
the default does nothing more than lxcutils does
network_profile
Network profile to use for the container
.. versionadded:: 2015.5.0
nic_opts
Extra options for network interfaces, will override
``{"eth0": {"hwaddr": "aa:bb:cc:dd:ee:ff", "ipv4": "10.1.1.1", "ipv6": "2001:db8::ff00:42:8329"}}``
or
``{"eth0": {"hwaddr": "aa:bb:cc:dd:ee:ff", "ipv4": "10.1.1.1/24", "ipv6": "2001:db8::ff00:42:8329"}}``
users
Users for which the password defined in the ``password`` param should
be set. Can be passed as a comma separated list or a python list.
Defaults to just the ``root`` user.
password
Set the initial password for the users defined in the ``users``
parameter
password_encrypted : False
Set to ``True`` to denote a password hash instead of a plaintext
password
.. versionadded:: 2015.5.0
profile
A LXC profile (defined in config or pillar).
This can be either a real profile mapping or a string
to retrieve it in configuration
start
Start the newly-created container
dnsservers
list of dns servers to set in the container, default [] (no setting)
seed
Seed the container with the minion config. Default: ``True``
install
If salt-minion is not already installed, install it. Default: ``True``
config
Optional config parameters. By default, the id is set to
the name of the container.
master
salt master (default to minion's master)
master_port
salt master port (default to minion's master port)
pub_key
Explicit public key to preseed the minion with (optional).
This can be either a filepath or a string representing the key
priv_key
Explicit private key to preseed the minion with (optional).
This can be either a filepath or a string representing the key
approve_key
If explicit preseeding is not used;
Attempt to request key approval from the master. Default: ``True``
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
clone_from
Original from which to use a clone operation to create the container.
Default: ``None``
bootstrap_delay
Delay in seconds between end of container creation and bootstrapping.
Useful when waiting for container to obtain a DHCP lease.
.. versionadded:: 2015.5.0
bootstrap_url
See lxc.bootstrap
bootstrap_shell
See lxc.bootstrap
bootstrap_args
See lxc.bootstrap
force_install
Force installation even if salt-minion is detected,
this is the way to run vendor bootstrap scripts even
if a salt minion is already present in the container
unconditional_install
Run the script even if the container seems seeded
CLI Example:
.. code-block:: bash
salt 'minion' lxc.init name [cpuset=cgroups_cpuset] \\
[cpushare=cgroups_cpushare] [memory=cgroups_memory] \\
[nic=nic_profile] [profile=lxc_profile] \\
[nic_opts=nic_opts] [start=(True|False)] \\
[seed=(True|False)] [install=(True|False)] \\
[config=minion_config] [approve_key=(True|False) \\
[clone_from=original] [autostart=True] \\
[priv_key=/path_or_content] [pub_key=/path_or_content] \\
[bridge=lxcbr0] [gateway=10.0.3.1] \\
[dnsservers[dns1,dns2]] \\
[users=[foo]] [password='secret'] \\
[password_encrypted=(True|False)]
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/lxc.py#L1125-L1642
|
[
"def start(name, **kwargs):\n '''\n Start the named container\n\n path\n path to the container parent directory\n default: /var/lib/lxc (system)\n\n .. versionadded:: 2015.8.0\n\n lxc_config\n path to a lxc config file\n config file will be guessed from container name otherwise\n\n .. versionadded:: 2015.8.0\n\n use_vt\n run the command through VT\n\n .. versionadded:: 2015.8.0\n\n CLI Example:\n\n .. code-block:: bash\n\n salt myminion lxc.start name\n '''\n path = kwargs.get('path', None)\n cpath = get_root_path(path)\n lxc_config = kwargs.get('lxc_config', None)\n cmd = 'lxc-start'\n if not lxc_config:\n lxc_config = os.path.join(cpath, name, 'config')\n # we try to start, even without config, if global opts are there\n if os.path.exists(lxc_config):\n cmd += ' -f {0}'.format(pipes.quote(lxc_config))\n cmd += ' -d'\n _ensure_exists(name, path=path)\n if state(name, path=path) == 'frozen':\n raise CommandExecutionError(\n 'Container \\'{0}\\' is frozen, use lxc.unfreeze'.format(name)\n )\n # lxc-start daemonize itself violently, we must not communicate with it\n use_vt = kwargs.get('use_vt', None)\n with_communicate = kwargs.get('with_communicate', False)\n return _change_state(cmd, name, 'running',\n stdout=None,\n stderr=None,\n stdin=None,\n with_communicate=with_communicate,\n path=path,\n use_vt=use_vt)\n",
"def stop(name, kill=False, path=None, use_vt=None):\n '''\n Stop the named container\n\n path\n path to the container parent directory\n default: /var/lib/lxc (system)\n\n .. versionadded:: 2015.8.0\n\n kill: False\n Do not wait for the container to stop, kill all tasks in the container.\n Older LXC versions will stop containers like this irrespective of this\n argument.\n\n .. versionchanged:: 2015.5.0\n Default value changed to ``False``\n\n use_vt\n run the command through VT\n\n .. versionadded:: 2015.8.0\n\n CLI Example:\n\n .. code-block:: bash\n\n salt myminion lxc.stop name\n '''\n _ensure_exists(name, path=path)\n orig_state = state(name, path=path)\n if orig_state == 'frozen' and not kill:\n # Gracefully stopping a frozen container is slower than unfreezing and\n # then stopping it (at least in my testing), so if we're not\n # force-stopping the container, unfreeze it first.\n unfreeze(name, path=path)\n cmd = 'lxc-stop'\n if kill:\n cmd += ' -k'\n ret = _change_state(cmd, name, 'stopped', use_vt=use_vt, path=path)\n ret['state']['old'] = orig_state\n return ret\n",
"def state(name, path=None):\n '''\n Returns the state of a container.\n\n path\n path to the container parent directory (default: /var/lib/lxc)\n\n .. versionadded:: 2015.8.0\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' lxc.state name\n '''\n # Don't use _ensure_exists() here, it will mess with _change_state()\n\n cachekey = 'lxc.state.{0}{1}'.format(name, path)\n try:\n return __context__[cachekey]\n except KeyError:\n if not exists(name, path=path):\n __context__[cachekey] = None\n else:\n cmd = 'lxc-info'\n if path:\n cmd += ' -P {0}'.format(pipes.quote(path))\n cmd += ' -n {0}'.format(name)\n ret = __salt__['cmd.run_all'](cmd, python_shell=False)\n if ret['retcode'] != 0:\n _clear_context()\n raise CommandExecutionError(\n 'Unable to get state of container \\'{0}\\''.format(name)\n )\n c_infos = ret['stdout'].splitlines()\n c_state = None\n for c_info in c_infos:\n stat = c_info.split(':')\n if stat[0].lower() == 'state':\n c_state = stat[1].strip().lower()\n break\n __context__[cachekey] = c_state\n return __context__[cachekey]\n",
"def retcode(name,\n cmd,\n no_start=False,\n preserve_state=True,\n stdin=None,\n python_shell=True,\n output_loglevel='debug',\n use_vt=False,\n path=None,\n ignore_retcode=False,\n chroot_fallback=False,\n keep_env='http_proxy,https_proxy,no_proxy'):\n '''\n .. versionadded:: 2015.5.0\n\n Run :mod:`cmd.retcode <salt.modules.cmdmod.retcode>` within a container\n\n .. warning::\n\n Many shell builtins do not work, failing with stderr similar to the\n following:\n\n .. code-block:: bash\n\n lxc_container: No such file or directory - failed to exec 'command'\n\n The same error will be displayed in stderr if the command being run\n does not exist. If the retcode is nonzero and not what was expected,\n try using :mod:`lxc.run_stderr <salt.modules.lxc.run_stderr>`\n or :mod:`lxc.run_all <salt.modules.lxc.run_all>`.\n\n name\n Name of the container in which to run the command\n\n cmd\n Command to run\n\n no_start : False\n If the container is not running, don't start it\n\n preserve_state : True\n After running the command, return the container to its previous state\n\n path\n path to the container parent\n default: /var/lib/lxc (system default)\n\n .. versionadded:: 2015.8.0\n\n stdin : None\n Standard input to be used for the command\n\n output_loglevel : debug\n Level at which to log the output from the command. Set to ``quiet`` to\n suppress logging.\n\n use_vt : False\n Use SaltStack's utils.vt to stream output to console\n ``output=all``.\n\n keep_env : http_proxy,https_proxy,no_proxy\n A list of env vars to preserve. May be passed as commma-delimited list.\n\n chroot_fallback\n if the container is not running, try to run the command using chroot\n default: false\n\n\n CLI Example:\n\n .. code-block:: bash\n\n salt myminion lxc.retcode mycontainer 'ip addr show'\n '''\n return _run(name,\n cmd,\n output='retcode',\n path=path,\n no_start=no_start,\n preserve_state=preserve_state,\n stdin=stdin,\n python_shell=python_shell,\n output_loglevel=output_loglevel,\n use_vt=use_vt,\n ignore_retcode=ignore_retcode,\n chroot_fallback=chroot_fallback,\n keep_env=keep_env)\n",
"def exists(name, path=None):\n '''\n Returns whether the named container exists.\n\n path\n path to the container parent directory (default: /var/lib/lxc)\n\n .. versionadded:: 2015.8.0\n\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' lxc.exists name\n '''\n\n _exists = name in ls_(path=path)\n # container may be just created but we did cached earlier the\n # lxc-ls results\n if not _exists:\n _exists = name in ls_(cache=False, path=path)\n return _exists\n",
"def run(name,\n cmd,\n no_start=False,\n preserve_state=True,\n stdin=None,\n python_shell=True,\n output_loglevel='debug',\n use_vt=False,\n path=None,\n ignore_retcode=False,\n chroot_fallback=False,\n keep_env='http_proxy,https_proxy,no_proxy'):\n '''\n .. versionadded:: 2015.8.0\n\n Run :mod:`cmd.run <salt.modules.cmdmod.run>` within a container\n\n .. warning::\n\n Many shell builtins do not work, failing with stderr similar to the\n following:\n\n .. code-block:: bash\n\n lxc_container: No such file or directory - failed to exec 'command'\n\n The same error will be displayed in stderr if the command being run\n does not exist. If no output is returned using this function, try using\n :mod:`lxc.run_stderr <salt.modules.lxc.run_stderr>` or\n :mod:`lxc.run_all <salt.modules.lxc.run_all>`.\n\n name\n Name of the container in which to run the command\n\n cmd\n Command to run\n\n path\n path to the container parent\n default: /var/lib/lxc (system default)\n\n .. versionadded:: 2015.8.0\n\n no_start : False\n If the container is not running, don't start it\n\n preserve_state : True\n After running the command, return the container to its previous state\n\n stdin : None\n Standard input to be used for the command\n\n output_loglevel : debug\n Level at which to log the output from the command. Set to ``quiet`` to\n suppress logging.\n\n use_vt : False\n Use SaltStack's utils.vt to stream output to console. Assumes\n ``output=all``.\n\n chroot_fallback\n if the container is not running, try to run the command using chroot\n default: false\n\n keep_env : http_proxy,https_proxy,no_proxy\n A list of env vars to preserve. May be passed as commma-delimited list.\n\n\n CLI Example:\n\n .. code-block:: bash\n\n salt myminion lxc.run mycontainer 'ifconfig -a'\n '''\n return _run(name,\n cmd,\n path=path,\n output=None,\n no_start=no_start,\n preserve_state=preserve_state,\n stdin=stdin,\n python_shell=python_shell,\n output_loglevel=output_loglevel,\n use_vt=use_vt,\n ignore_retcode=ignore_retcode,\n chroot_fallback=chroot_fallback,\n keep_env=keep_env)\n",
"def clone(name,\n orig,\n profile=None,\n network_profile=None,\n nic_opts=None,\n **kwargs):\n '''\n Create a new container as a clone of another container\n\n name\n Name of the container\n\n orig\n Name of the original container to be cloned\n\n profile\n Profile to use in container cloning (see\n :mod:`lxc.get_container_profile\n <salt.modules.lxc.get_container_profile>`). Values in a profile will be\n overridden by the **Container Cloning Arguments** listed below.\n\n path\n path to the container parent directory\n default: /var/lib/lxc (system)\n\n .. versionadded:: 2015.8.0\n\n **Container Cloning Arguments**\n\n snapshot\n Use Copy On Write snapshots (LVM)\n\n size : 1G\n Size of the volume to create. Only applicable if ``backing=lvm``.\n\n backing\n The type of storage to use. Set to ``lvm`` to use an LVM group.\n Defaults to filesystem within /var/lib/lxc.\n\n network_profile\n Network profile to use for container\n\n .. versionadded:: 2015.8.0\n\n nic_opts\n give extra opts overriding network profile values\n\n .. versionadded:: 2015.8.0\n\n\n CLI Examples:\n\n .. code-block:: bash\n\n salt '*' lxc.clone myclone orig=orig_container\n salt '*' lxc.clone myclone orig=orig_container snapshot=True\n '''\n profile = get_container_profile(copy.deepcopy(profile))\n kw_overrides = copy.deepcopy(kwargs)\n\n def select(key, default=None):\n kw_overrides_match = kw_overrides.pop(key, None)\n profile_match = profile.pop(key, default)\n # let kwarg overrides be the preferred choice\n if kw_overrides_match is None:\n return profile_match\n return kw_overrides_match\n\n path = select('path')\n if exists(name, path=path):\n raise CommandExecutionError(\n 'Container \\'{0}\\' already exists'.format(name)\n )\n\n _ensure_exists(orig, path=path)\n if state(orig, path=path) != 'stopped':\n raise CommandExecutionError(\n 'Container \\'{0}\\' must be stopped to be cloned'.format(orig)\n )\n\n backing = select('backing')\n snapshot = select('snapshot')\n if backing in ('dir',):\n snapshot = False\n if not snapshot:\n snapshot = ''\n else:\n snapshot = '-s'\n\n size = select('size', '1G')\n if backing in ('dir', 'overlayfs', 'btrfs'):\n size = None\n # LXC commands and options changed in 2.0 - CF issue #34086 for details\n if _LooseVersion(version()) >= _LooseVersion('2.0'):\n # https://linuxcontainers.org/lxc/manpages//man1/lxc-copy.1.html\n cmd = 'lxc-copy'\n cmd += ' {0} -n {1} -N {2}'.format(snapshot, orig, name)\n else:\n # https://linuxcontainers.org/lxc/manpages//man1/lxc-clone.1.html\n cmd = 'lxc-clone'\n cmd += ' {0} -o {1} -n {2}'.format(snapshot, orig, name)\n if path:\n cmd += ' -P {0}'.format(pipes.quote(path))\n if not os.path.exists(path):\n os.makedirs(path)\n if backing:\n backing = backing.lower()\n cmd += ' -B {0}'.format(backing)\n if backing not in ('dir', 'overlayfs'):\n if size:\n cmd += ' -L {0}'.format(size)\n ret = __salt__['cmd.run_all'](cmd, python_shell=False)\n # please do not merge extra conflicting stuff\n # inside those two line (ret =, return)\n return _after_ignition_network_profile(cmd,\n ret,\n name,\n network_profile,\n path,\n nic_opts)\n",
"def create(name,\n config=None,\n profile=None,\n network_profile=None,\n nic_opts=None,\n **kwargs):\n '''\n Create a new container.\n\n name\n Name of the container\n\n config\n The config file to use for the container. Defaults to system-wide\n config (usually in /etc/lxc/lxc.conf).\n\n profile\n Profile to use in container creation (see\n :mod:`lxc.get_container_profile\n <salt.modules.lxc.get_container_profile>`). Values in a profile will be\n overridden by the **Container Creation Arguments** listed below.\n\n network_profile\n Network profile to use for container\n\n .. versionadded:: 2015.5.0\n\n **Container Creation Arguments**\n\n template\n The template to use. For example, ``ubuntu`` or ``fedora``.\n For a full list of available templates, check out\n the :mod:`lxc.templates <salt.modules.lxc.templates>` function.\n\n Conflicts with the ``image`` argument.\n\n .. note::\n\n The ``download`` template requires the following three parameters\n to be defined in ``options``:\n\n * **dist** - The name of the distribution\n * **release** - Release name/version\n * **arch** - Architecture of the container\n\n The available images can be listed using the :mod:`lxc.images\n <salt.modules.lxc.images>` function.\n\n options\n Template-specific options to pass to the lxc-create command. These\n correspond to the long options (ones beginning with two dashes) that\n the template script accepts. For example:\n\n .. code-block:: bash\n\n options='{\"dist\": \"centos\", \"release\": \"6\", \"arch\": \"amd64\"}'\n\n For available template options, refer to the lxc template scripts\n which are ususally located under ``/usr/share/lxc/templates``,\n or run ``lxc-create -t <template> -h``.\n\n image\n A tar archive to use as the rootfs for the container. Conflicts with\n the ``template`` argument.\n\n backing\n The type of storage to use. Set to ``lvm`` to use an LVM group.\n Defaults to filesystem within /var/lib/lxc.\n\n fstype\n Filesystem type to use on LVM logical volume\n\n size : 1G\n Size of the volume to create. Only applicable if ``backing=lvm``.\n\n vgname : lxc\n Name of the LVM volume group in which to create the volume for this\n container. Only applicable if ``backing=lvm``.\n\n lvname\n Name of the LVM logical volume in which to create the volume for this\n container. Only applicable if ``backing=lvm``.\n\n thinpool\n Name of a pool volume that will be used for thin-provisioning this\n container. Only applicable if ``backing=lvm``.\n\n nic_opts\n give extra opts overriding network profile values\n\n path\n parent path for the container creation (default: /var/lib/lxc)\n\n zfsroot\n Name of the ZFS root in which to create the volume for this container.\n Only applicable if ``backing=zfs``. (default: tank/lxc)\n\n .. versionadded:: 2015.8.0\n '''\n # Required params for 'download' template\n download_template_deps = ('dist', 'release', 'arch')\n\n cmd = 'lxc-create -n {0}'.format(name)\n\n profile = get_container_profile(copy.deepcopy(profile))\n kw_overrides = copy.deepcopy(kwargs)\n\n def select(key, default=None):\n kw_overrides_match = kw_overrides.pop(key, None)\n profile_match = profile.pop(key, default)\n # Return the profile match if the the kwarg match was None, as the\n # lxc.present state will pass these kwargs set to None by default.\n if kw_overrides_match is None:\n return profile_match\n return kw_overrides_match\n\n path = select('path')\n if exists(name, path=path):\n raise CommandExecutionError(\n 'Container \\'{0}\\' already exists'.format(name)\n )\n\n tvg = select('vgname')\n vgname = tvg if tvg else __salt__['config.get']('lxc.vgname')\n\n # The 'template' and 'image' params conflict\n template = select('template')\n image = select('image')\n if template and image:\n raise SaltInvocationError(\n 'Only one of \\'template\\' and \\'image\\' is permitted'\n )\n elif not any((template, image, profile)):\n raise SaltInvocationError(\n 'At least one of \\'template\\', \\'image\\', and \\'profile\\' is '\n 'required'\n )\n\n options = select('options') or {}\n backing = select('backing')\n if vgname and not backing:\n backing = 'lvm'\n lvname = select('lvname')\n thinpool = select('thinpool')\n fstype = select('fstype')\n size = select('size', '1G')\n zfsroot = select('zfsroot')\n if backing in ('dir', 'overlayfs', 'btrfs', 'zfs'):\n fstype = None\n size = None\n # some backends won't support some parameters\n if backing in ('aufs', 'dir', 'overlayfs', 'btrfs'):\n lvname = vgname = thinpool = None\n\n if image:\n img_tar = __salt__['cp.cache_file'](image)\n template = os.path.join(\n os.path.dirname(salt.__file__),\n 'templates',\n 'lxc',\n 'salt_tarball')\n options['imgtar'] = img_tar\n if path:\n cmd += ' -P {0}'.format(pipes.quote(path))\n if not os.path.exists(path):\n os.makedirs(path)\n if config:\n cmd += ' -f {0}'.format(config)\n if template:\n cmd += ' -t {0}'.format(template)\n if backing:\n backing = backing.lower()\n cmd += ' -B {0}'.format(backing)\n if backing in ('zfs',):\n if zfsroot:\n cmd += ' --zfsroot {0}'.format(zfsroot)\n if backing in ('lvm',):\n if lvname:\n cmd += ' --lvname {0}'.format(lvname)\n if vgname:\n cmd += ' --vgname {0}'.format(vgname)\n if thinpool:\n cmd += ' --thinpool {0}'.format(thinpool)\n if backing not in ('dir', 'overlayfs'):\n if fstype:\n cmd += ' --fstype {0}'.format(fstype)\n if size:\n cmd += ' --fssize {0}'.format(size)\n\n if options:\n if template == 'download':\n missing_deps = [x for x in download_template_deps\n if x not in options]\n if missing_deps:\n raise SaltInvocationError(\n 'Missing params in \\'options\\' dict: {0}'\n .format(', '.join(missing_deps))\n )\n cmd += ' --'\n for key, val in six.iteritems(options):\n cmd += ' --{0} {1}'.format(key, val)\n\n ret = __salt__['cmd.run_all'](cmd, python_shell=False)\n # please do not merge extra conflicting stuff\n # inside those two line (ret =, return)\n return _after_ignition_network_profile(cmd,\n ret,\n name,\n network_profile,\n path,\n nic_opts)\n",
"def set_password(name, users, password, encrypted=True, path=None):\n '''\n .. versionchanged:: 2015.5.0\n Function renamed from ``set_pass`` to ``set_password``. Additionally,\n this function now supports (and defaults to using) a password hash\n instead of a plaintext password.\n\n Set the password of one or more system users inside containers\n\n\n users\n Comma-separated list (or python list) of users to change password\n\n password\n Password to set for the specified user(s)\n\n encrypted : True\n If true, ``password`` must be a password hash. Set to ``False`` to set\n a plaintext password (not recommended).\n\n .. versionadded:: 2015.5.0\n\n path\n path to the container parent directory\n default: /var/lib/lxc (system)\n\n .. versionadded:: 2015.8.0\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' lxc.set_pass container-name root '$6$uJ2uAyLU$KoI67t8As/0fXtJOPcHKGXmUpcoYUcVR2K6x93walnShTCQvjRwq25yIkiCBOqgbfdKQSFnAo28/ek6716vEV1'\n salt '*' lxc.set_pass container-name root foo encrypted=False\n\n '''\n def _bad_user_input():\n raise SaltInvocationError('Invalid input for \\'users\\' parameter')\n\n if not isinstance(users, list):\n try:\n users = users.split(',')\n except AttributeError:\n _bad_user_input()\n if not users:\n _bad_user_input()\n\n failed_users = []\n for user in users:\n result = retcode(name,\n 'chpasswd{0}'.format(' -e' if encrypted else ''),\n stdin=':'.join((user, password)),\n python_shell=False,\n path=path,\n chroot_fallback=True,\n output_loglevel='quiet')\n if result != 0:\n failed_users.append(user)\n if failed_users:\n raise CommandExecutionError(\n 'Password change failed for the following user(s): {0}'\n .format(', '.join(failed_users))\n )\n return True\n",
"def get_root_path(path):\n '''\n Get the configured lxc root for containers\n\n .. versionadded:: 2015.8.0\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' lxc.get_root_path\n\n '''\n if not path:\n path = __opts__.get('lxc.root_path', DEFAULT_PATH)\n return path\n",
"def _get_salt_config(config, **kwargs):\n if not config:\n config = kwargs.get('minion', {})\n if not config:\n config = {}\n config.setdefault('master',\n kwargs.get('master',\n __opts__.get('master',\n __opts__['id'])))\n config.setdefault(\n 'master_port',\n kwargs.get('master_port',\n __opts__.get('master_port',\n __opts__.get('ret_port',\n __opts__.get('4506')))))\n if not config['master']:\n config = {}\n return config\n",
"def get_container_profile(name=None, **kwargs):\n '''\n .. versionadded:: 2015.5.0\n\n Gather a pre-configured set of container configuration parameters. If no\n arguments are passed, an empty profile is returned.\n\n Profiles can be defined in the minion or master config files, or in pillar\n or grains, and are loaded using :mod:`config.get\n <salt.modules.config.get>`. The key under which LXC profiles must be\n configured is ``lxc.container_profile.profile_name``. An example container\n profile would be as follows:\n\n .. code-block:: yaml\n\n lxc.container_profile:\n ubuntu:\n template: ubuntu\n backing: lvm\n vgname: lxc\n size: 1G\n\n Parameters set in a profile can be overridden by passing additional\n container creation arguments (such as the ones passed to :mod:`lxc.create\n <salt.modules.lxc.create>`) to this function.\n\n A profile can be defined either as the name of the profile, or a dictionary\n of variable names and values. See the :ref:`LXC Tutorial\n <tutorial-lxc-profiles>` for more information on how to use LXC profiles.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt-call lxc.get_container_profile centos\n salt-call lxc.get_container_profile ubuntu template=ubuntu backing=overlayfs\n '''\n profile = _get_profile('container_profile', name, **kwargs)\n return profile\n",
"def _config_list(conf_tuples=None, only_net=False, **kwargs):\n '''\n Return a list of dicts from the salt level configurations\n\n conf_tuples\n _LXCConfig compatible list of entries which can contain\n\n - string line\n - tuple (lxc config param,value)\n - dict of one entry: {lxc config param: value)\n\n only_net\n by default we add to the tuples a reflection of both\n the real config if avalaible and a certain amount of\n default values like the cpu parameters, the memory\n and etc.\n On the other hand, we also no matter the case reflect\n the network configuration computed from the actual config if\n available and given values.\n if no_default_loads is set, we will only\n reflect the network configuration back to the conf tuples\n list\n\n '''\n # explicit cast\n only_net = bool(only_net)\n if not conf_tuples:\n conf_tuples = []\n kwargs = copy.deepcopy(kwargs)\n ret = []\n if not only_net:\n default_data = _get_lxc_default_data(**kwargs)\n for k, val in six.iteritems(default_data):\n ret.append({k: val})\n net_datas = _network_conf(conf_tuples=conf_tuples, **kwargs)\n ret.extend(net_datas)\n return ret\n",
"def _get_base(**kwargs):\n '''\n If the needed base does not exist, then create it, if it does exist\n create nothing and return the name of the base lxc container so\n it can be cloned.\n '''\n profile = get_container_profile(copy.deepcopy(kwargs.get('profile')))\n kw_overrides = copy.deepcopy(kwargs)\n\n def select(key, default=None):\n kw_overrides_match = kw_overrides.pop(key, _marker)\n profile_match = profile.pop(key, default)\n # let kwarg overrides be the preferred choice\n if kw_overrides_match is _marker:\n return profile_match\n return kw_overrides_match\n\n template = select('template')\n image = select('image')\n vgname = select('vgname')\n path = kwargs.get('path', None)\n # remove the above three variables from kwargs, if they exist, to avoid\n # duplicates if create() is invoked below.\n for param in ('path', 'image', 'vgname', 'template'):\n kwargs.pop(param, None)\n\n if image:\n proto = _urlparse(image).scheme\n img_tar = __salt__['cp.cache_file'](image)\n img_name = os.path.basename(img_tar)\n hash_ = salt.utils.hashutils.get_hash(\n img_tar,\n __salt__['config.get']('hash_type'))\n name = '__base_{0}_{1}_{2}'.format(proto, img_name, hash_)\n if not exists(name, path=path):\n create(name, template=template, image=image,\n path=path, vgname=vgname, **kwargs)\n if vgname:\n rootfs = os.path.join('/dev', vgname, name)\n edit_conf(info(name, path=path)['config'],\n out_format='commented', **{'lxc.rootfs': rootfs})\n return name\n elif template:\n name = '__base_{0}'.format(template)\n if not exists(name, path=path):\n create(name, template=template, image=image, path=path,\n vgname=vgname, **kwargs)\n if vgname:\n rootfs = os.path.join('/dev', vgname, name)\n edit_conf(info(name, path=path)['config'],\n out_format='commented', **{'lxc.rootfs': rootfs})\n return name\n return ''\n",
"def edit_conf(conf_file,\n out_format='simple',\n read_only=False,\n lxc_config=None,\n **kwargs):\n '''\n Edit an LXC configuration file. If a setting is already present inside the\n file, its value will be replaced. If it does not exist, it will be appended\n to the end of the file. Comments and blank lines will be kept in-tact if\n they already exist in the file.\n\n out_format:\n Set to simple if you need backward compatibility (multiple items for a\n simple key is not supported)\n read_only:\n return only the edited configuration without applying it\n to the underlying lxc configuration file\n lxc_config:\n List of dict containning lxc configuration items\n For network configuration, you also need to add the device it belongs\n to, otherwise it will default to eth0.\n Also, any change to a network parameter will result in the whole\n network reconfiguration to avoid mismatchs, be aware of that !\n\n After the file is edited, its contents will be returned. By default, it\n will be returned in ``simple`` format, meaning an unordered dict (which\n may not represent the actual file order). Passing in an ``out_format`` of\n ``commented`` will return a data structure which accurately represents the\n order and content of the file.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt 'minion' lxc.edit_conf /etc/lxc/mycontainer.conf \\\\\n out_format=commented lxc.network.type=veth\n salt 'minion' lxc.edit_conf /etc/lxc/mycontainer.conf \\\\\n out_format=commented \\\\\n lxc_config=\"[{'lxc.network.name': 'eth0', \\\\\n 'lxc.network.ipv4': '1.2.3.4'},\n {'lxc.network.name': 'eth2', \\\\\n 'lxc.network.ipv4': '1.2.3.5',\\\\\n 'lxc.network.gateway': '1.2.3.1'}]\"\n '''\n data = []\n\n try:\n conf = read_conf(conf_file, out_format=out_format)\n except Exception:\n conf = []\n\n if not lxc_config:\n lxc_config = []\n lxc_config = copy.deepcopy(lxc_config)\n\n # search if we want to access net config\n # in that case, we will replace all the net configuration\n net_config = []\n for lxc_kws in lxc_config + [kwargs]:\n net_params = {}\n for kwarg in [a for a in lxc_kws]:\n if kwarg.startswith('__'):\n continue\n if kwarg.startswith('lxc.network.'):\n net_params[kwarg] = lxc_kws[kwarg]\n lxc_kws.pop(kwarg, None)\n if net_params:\n net_config.append(net_params)\n nic_opts = salt.utils.odict.OrderedDict()\n for params in net_config:\n dev = params.get('lxc.network.name', DEFAULT_NIC)\n dev_opts = nic_opts.setdefault(dev, salt.utils.odict.OrderedDict())\n for param in params:\n opt = param.replace('lxc.network.', '')\n opt = {'hwaddr': 'mac'}.get(opt, opt)\n dev_opts[opt] = params[param]\n\n net_changes = []\n if nic_opts:\n net_changes = _config_list(conf, only_net=True,\n **{'network_profile': DEFAULT_NIC,\n 'nic_opts': nic_opts})\n if net_changes:\n lxc_config.extend(net_changes)\n\n for line in conf:\n if not isinstance(line, dict):\n data.append(line)\n continue\n else:\n for key in list(line.keys()):\n val = line[key]\n if net_changes and key.startswith('lxc.network.'):\n continue\n found = False\n for ix in range(len(lxc_config)):\n kw = lxc_config[ix]\n if key in kw:\n found = True\n data.append({key: kw[key]})\n del kw[key]\n if not found:\n data.append({key: val})\n\n for lxc_kws in lxc_config:\n for kwarg in lxc_kws:\n data.append({kwarg: lxc_kws[kwarg]})\n if read_only:\n return data\n write_conf(conf_file, data)\n return read_conf(conf_file, out_format)\n",
"def read_conf(conf_file, out_format='simple'):\n '''\n Read in an LXC configuration file. By default returns a simple, unsorted\n dict, but can also return a more detailed structure including blank lines\n and comments.\n\n out_format:\n set to 'simple' if you need the old and unsupported behavior.\n This won't support the multiple lxc values (eg: multiple network nics)\n\n CLI Examples:\n\n .. code-block:: bash\n\n salt 'minion' lxc.read_conf /etc/lxc/mycontainer.conf\n salt 'minion' lxc.read_conf /etc/lxc/mycontainer.conf out_format=commented\n '''\n ret_commented = []\n ret_simple = {}\n with salt.utils.files.fopen(conf_file, 'r') as fp_:\n for line in salt.utils.data.decode(fp_.readlines()):\n if '=' not in line:\n ret_commented.append(line)\n continue\n comps = line.split('=')\n value = '='.join(comps[1:]).strip()\n comment = None\n if value.strip().startswith('#'):\n vcomps = value.strip().split('#')\n value = vcomps[1].strip()\n comment = '#'.join(vcomps[1:]).strip()\n ret_commented.append({comps[0].strip(): {\n 'value': value,\n 'comment': comment,\n }})\n else:\n ret_commented.append({comps[0].strip(): value})\n ret_simple[comps[0].strip()] = value\n\n if out_format == 'simple':\n return ret_simple\n return ret_commented\n",
"def select(key, default=None):\n kw_overrides_match = kw_overrides.pop(key, _marker)\n profile_match = profile.pop(key, default)\n # let kwarg overrides be the preferred choice\n if kw_overrides_match is _marker:\n return profile_match\n return kw_overrides_match\n",
"def write(self):\n if self.path:\n content = self.as_string()\n # 2 step rendering to be sure not to open/wipe the config\n # before as_string succeeds.\n with salt.utils.files.fopen(self.path, 'w') as fic:\n fic.write(salt.utils.stringutils.to_str(content))\n fic.flush()\n",
"def tempfile(self):\n # this might look like the function name is shadowing the\n # module, but it's not since the method belongs to the class\n ntf = tempfile.NamedTemporaryFile()\n ntf.write(self.as_string())\n ntf.flush()\n return ntf\n"
] |
# -*- coding: utf-8 -*-
'''
Control Linux Containers via Salt
:depends: lxc package for distribution
lxc >= 1.0 (even beta alpha) is required
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import datetime
import copy
import string
import textwrap
import difflib
import logging
import tempfile
import os
import pipes
import time
import shutil
import re
import random
# Import salt libs
import salt.utils.args
import salt.utils.cloud
import salt.utils.data
import salt.utils.dictupdate
import salt.utils.files
import salt.utils.functools
import salt.utils.hashutils
import salt.utils.network
import salt.utils.odict
import salt.utils.path
import salt.utils.stringutils
from salt.exceptions import CommandExecutionError, SaltInvocationError
import salt.config
from salt.utils.versions import LooseVersion as _LooseVersion
# Import 3rd-party libs
from salt.ext import six
# pylint: disable=import-error,no-name-in-module
from salt.ext.six.moves import range # pylint: disable=redefined-builtin
from salt.ext.six.moves.urllib.parse import urlparse as _urlparse
# pylint: enable=import-error,no-name-in-module
# Set up logging
log = logging.getLogger(__name__)
# Don't shadow built-in's.
__func_alias__ = {
'list_': 'list',
'ls_': 'ls'
}
__virtualname__ = 'lxc'
DEFAULT_NIC = 'eth0'
DEFAULT_BR = 'br0'
SEED_MARKER = '/lxc.initial_seed'
EXEC_DRIVER = 'lxc-attach'
DEFAULT_PATH = '/var/lib/lxc'
_marker = object()
def __virtual__():
if salt.utils.path.which('lxc-start'):
return __virtualname__
# To speed up the whole thing, we decided to not use the
# subshell way and assume things are in place for lxc
# Discussion made by @kiorky and @thatch45
# lxc-version presence is not sufficient, in lxc1.0 alpha
# (precise backports), we have it and it is sufficient
# for the module to execute.
# elif salt.utils.path.which('lxc-version'):
# passed = False
# try:
# passed = subprocess.check_output(
# 'lxc-version').split(':')[1].strip() >= '1.0'
# except Exception:
# pass
# if not passed:
# log.warning('Support for lxc < 1.0 may be incomplete.')
# return 'lxc'
# return False
#
return (False, 'The lxc execution module cannot be loaded: the lxc-start binary is not in the path.')
def get_root_path(path):
'''
Get the configured lxc root for containers
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.get_root_path
'''
if not path:
path = __opts__.get('lxc.root_path', DEFAULT_PATH)
return path
def version():
'''
Return the actual lxc client version
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.version
'''
k = 'lxc.version'
if not __context__.get(k, None):
cversion = __salt__['cmd.run_all']('lxc-info --version')
if not cversion['retcode']:
ver = _LooseVersion(cversion['stdout'])
if ver < _LooseVersion('1.0'):
raise CommandExecutionError('LXC should be at least 1.0')
__context__[k] = "{0}".format(ver)
return __context__.get(k, None)
def _clear_context():
'''
Clear any lxc variables set in __context__
'''
for var in [x for x in __context__ if x.startswith('lxc.')]:
log.trace('Clearing __context__[\'%s\']', var)
__context__.pop(var, None)
def _ip_sort(ip):
'''Ip sorting'''
idx = '001'
if ip == '127.0.0.1':
idx = '200'
if ip == '::1':
idx = '201'
elif '::' in ip:
idx = '100'
return '{0}___{1}'.format(idx, ip)
def search_lxc_bridges():
'''
Search which bridges are potentially available as LXC bridges
CLI Example:
.. code-block:: bash
salt '*' lxc.search_lxc_bridges
'''
bridges = __context__.get('lxc.bridges', None)
# either match not yet called or no bridges were found
# to handle the case where lxc was not installed on the first
# call
if not bridges:
bridges = set()
running_bridges = set()
bridges.add(DEFAULT_BR)
try:
output = __salt__['cmd.run_all']('brctl show')
for line in output['stdout'].splitlines()[1:]:
if not line.startswith(' '):
running_bridges.add(line.split()[0].strip())
except (SaltInvocationError, CommandExecutionError):
pass
for ifc, ip in six.iteritems(
__grains__.get('ip_interfaces', {})
):
if ifc in running_bridges:
bridges.add(ifc)
elif os.path.exists(
'/sys/devices/virtual/net/{0}/bridge'.format(ifc)
):
bridges.add(ifc)
bridges = list(bridges)
# if we found interfaces that have lxc in their names
# we filter them as being the potential lxc bridges
# we also try to default on br0 on other cases
def sort_bridges(a):
pref = 'z'
if 'lxc' in a:
pref = 'a'
elif 'br0' == a:
pref = 'c'
return '{0}_{1}'.format(pref, a)
bridges.sort(key=sort_bridges)
__context__['lxc.bridges'] = bridges
return bridges
def search_lxc_bridge():
'''
Search the first bridge which is potentially available as LXC bridge
CLI Example:
.. code-block:: bash
salt '*' lxc.search_lxc_bridge
'''
return search_lxc_bridges()[0]
def _get_salt_config(config, **kwargs):
if not config:
config = kwargs.get('minion', {})
if not config:
config = {}
config.setdefault('master',
kwargs.get('master',
__opts__.get('master',
__opts__['id'])))
config.setdefault(
'master_port',
kwargs.get('master_port',
__opts__.get('master_port',
__opts__.get('ret_port',
__opts__.get('4506')))))
if not config['master']:
config = {}
return config
def cloud_init_interface(name, vm_=None, **kwargs):
'''
Interface between salt.cloud.lxc driver and lxc.init
``vm_`` is a mapping of vm opts in the salt.cloud format
as documented for the lxc driver.
This can be used either:
- from the salt cloud driver
- because you find the argument to give easier here
than using directly lxc.init
.. warning::
BE REALLY CAREFUL CHANGING DEFAULTS !!!
IT'S A RETRO COMPATIBLE INTERFACE WITH
THE SALT CLOUD DRIVER (ask kiorky).
name
name of the lxc container to create
pub_key
public key to preseed the minion with.
Can be the keycontent or a filepath
priv_key
private key to preseed the minion with.
Can be the keycontent or a filepath
path
path to the container parent directory (default: /var/lib/lxc)
.. versionadded:: 2015.8.0
profile
:ref:`profile <tutorial-lxc-profiles-container>` selection
network_profile
:ref:`network profile <tutorial-lxc-profiles-network>` selection
nic_opts
per interface settings compatibles with
network profile (ipv4/ipv6/link/gateway/mac/netmask)
eg::
- {'eth0': {'mac': '00:16:3e:01:29:40',
'gateway': None, (default)
'link': 'br0', (default)
'gateway': None, (default)
'netmask': '', (default)
'ip': '22.1.4.25'}}
unconditional_install
given to lxc.bootstrap (see relative doc)
force_install
given to lxc.bootstrap (see relative doc)
config
any extra argument for the salt minion config
dnsservers
list of DNS servers to set inside the container
dns_via_dhcp
do not set the dns servers, let them be set by the dhcp.
autostart
autostart the container at boot time
password
administrative password for the container
bootstrap_delay
delay before launching bootstrap script at Container init
.. warning::
Legacy but still supported options:
from_container
which container we use as a template
when running lxc.clone
image
which template do we use when we
are using lxc.create. This is the default
mode unless you specify something in from_container
backing
which backing store to use.
Values can be: overlayfs, dir(default), lvm, zfs, brtfs
fstype
When using a blockdevice level backing store,
which filesystem to use on
size
When using a blockdevice level backing store,
which size for the filesystem to use on
snapshot
Use snapshot when cloning the container source
vgname
if using LVM: vgname
lvname
if using LVM: lvname
thinpool:
if using LVM: thinpool
ip
ip for the primary nic
mac
mac address for the primary nic
netmask
netmask for the primary nic (24)
= ``vm_.get('netmask', '24')``
bridge
bridge for the primary nic (lxcbr0)
gateway
network gateway for the container
additional_ips
additional ips which will be wired on the main bridge (br0)
which is connected to internet.
Be aware that you may use manual virtual mac addresses
providen by you provider (online, ovh, etc).
This is a list of mappings {ip: '', mac: '', netmask:''}
Set gateway to None and an interface with a gateway
to escape from another interface that eth0.
eg::
- {'mac': '00:16:3e:01:29:40',
'gateway': None, (default)
'link': 'br0', (default)
'netmask': '', (default)
'ip': '22.1.4.25'}
users
administrative users for the container
default: [root] and [root, ubuntu] on ubuntu
default_nic
name of the first interface, you should
really not override this
CLI Example:
.. code-block:: bash
salt '*' lxc.cloud_init_interface foo
'''
if vm_ is None:
vm_ = {}
vm_ = copy.deepcopy(vm_)
vm_ = salt.utils.dictupdate.update(vm_, kwargs)
profile_data = copy.deepcopy(
vm_.get('lxc_profile',
vm_.get('profile', {})))
if not isinstance(profile_data, (dict, six.string_types)):
profile_data = {}
profile = get_container_profile(profile_data)
def _cloud_get(k, default=None):
return vm_.get(k, profile.get(k, default))
if name is None:
name = vm_['name']
# if we are on ubuntu, default to ubuntu
default_template = ''
if __grains__.get('os', '') in ['Ubuntu']:
default_template = 'ubuntu'
image = _cloud_get('image')
if not image:
_cloud_get('template', default_template)
backing = _cloud_get('backing', 'dir')
if image:
profile['template'] = image
vgname = _cloud_get('vgname', None)
if vgname:
profile['vgname'] = vgname
if backing:
profile['backing'] = backing
snapshot = _cloud_get('snapshot', False)
autostart = bool(_cloud_get('autostart', True))
dnsservers = _cloud_get('dnsservers', [])
dns_via_dhcp = _cloud_get('dns_via_dhcp', True)
password = _cloud_get('password', 's3cr3t')
password_encrypted = _cloud_get('password_encrypted', False)
fstype = _cloud_get('fstype', None)
lvname = _cloud_get('lvname', None)
thinpool = _cloud_get('thinpool', None)
pub_key = _cloud_get('pub_key', None)
priv_key = _cloud_get('priv_key', None)
size = _cloud_get('size', '20G')
script = _cloud_get('script', None)
script_args = _cloud_get('script_args', None)
users = _cloud_get('users', None)
if users is None:
users = []
ssh_username = _cloud_get('ssh_username', None)
if ssh_username and (ssh_username not in users):
users.append(ssh_username)
network_profile = _cloud_get('network_profile', None)
nic_opts = kwargs.get('nic_opts', None)
netmask = _cloud_get('netmask', '24')
path = _cloud_get('path', None)
bridge = _cloud_get('bridge', None)
gateway = _cloud_get('gateway', None)
unconditional_install = _cloud_get('unconditional_install', False)
force_install = _cloud_get('force_install', True)
config = _get_salt_config(_cloud_get('config', {}), **vm_)
default_nic = _cloud_get('default_nic', DEFAULT_NIC)
# do the interface with lxc.init mainly via nic_opts
# to avoid extra and confusing extra use cases.
if not isinstance(nic_opts, dict):
nic_opts = salt.utils.odict.OrderedDict()
# have a reference to the default nic
eth0 = nic_opts.setdefault(default_nic,
salt.utils.odict.OrderedDict())
# lxc config is based of ifc order, be sure to use odicts.
if not isinstance(nic_opts, salt.utils.odict.OrderedDict):
bnic_opts = salt.utils.odict.OrderedDict()
bnic_opts.update(nic_opts)
nic_opts = bnic_opts
gw = None
# legacy salt.cloud scheme for network interfaces settings support
bridge = _cloud_get('bridge', None)
ip = _cloud_get('ip', None)
mac = _cloud_get('mac', None)
if ip:
fullip = ip
if netmask:
fullip += '/{0}'.format(netmask)
eth0['ipv4'] = fullip
if mac is not None:
eth0['mac'] = mac
for ix, iopts in enumerate(_cloud_get("additional_ips", [])):
ifh = "eth{0}".format(ix+1)
ethx = nic_opts.setdefault(ifh, {})
if gw is None:
gw = iopts.get('gateway', ethx.get('gateway', None))
if gw:
# only one and only one default gateway is allowed !
eth0.pop('gateway', None)
gateway = None
# even if the gateway if on default "eth0" nic
# and we popped it will work
# as we reinject or set it here.
ethx['gateway'] = gw
elink = iopts.get('link', ethx.get('link', None))
if elink:
ethx['link'] = elink
# allow dhcp
aip = iopts.get('ipv4', iopts.get('ip', None))
if aip:
ethx['ipv4'] = aip
nm = iopts.get('netmask', '')
if nm:
ethx['ipv4'] += '/{0}'.format(nm)
for i in ('mac', 'hwaddr'):
if i in iopts:
ethx['mac'] = iopts[i]
break
if 'mac' not in ethx:
ethx['mac'] = salt.utils.network.gen_mac()
# last round checking for unique gateway and such
gw = None
for ethx in [a for a in nic_opts]:
ndata = nic_opts[ethx]
if gw:
ndata.pop('gateway', None)
if 'gateway' in ndata:
gw = ndata['gateway']
gateway = None
# only use a default bridge / gateway if we configured them
# via the legacy salt cloud configuration style.
# On other cases, we should rely on settings provided by the new
# salt lxc network profile style configuration which can
# be also be overridden or a per interface basis via the nic_opts dict.
if bridge:
eth0['link'] = bridge
if gateway:
eth0['gateway'] = gateway
#
lxc_init_interface = {}
lxc_init_interface['name'] = name
lxc_init_interface['config'] = config
lxc_init_interface['memory'] = _cloud_get('memory', 0) # nolimit
lxc_init_interface['pub_key'] = pub_key
lxc_init_interface['priv_key'] = priv_key
lxc_init_interface['nic_opts'] = nic_opts
for clone_from in ['clone_from', 'clone', 'from_container']:
# clone_from should default to None if not available
lxc_init_interface['clone_from'] = _cloud_get(clone_from, None)
if lxc_init_interface['clone_from'] is not None:
break
lxc_init_interface['profile'] = profile
lxc_init_interface['snapshot'] = snapshot
lxc_init_interface['dnsservers'] = dnsservers
lxc_init_interface['fstype'] = fstype
lxc_init_interface['path'] = path
lxc_init_interface['vgname'] = vgname
lxc_init_interface['size'] = size
lxc_init_interface['lvname'] = lvname
lxc_init_interface['thinpool'] = thinpool
lxc_init_interface['force_install'] = force_install
lxc_init_interface['unconditional_install'] = (
unconditional_install
)
lxc_init_interface['bootstrap_url'] = script
lxc_init_interface['bootstrap_args'] = script_args
lxc_init_interface['bootstrap_shell'] = _cloud_get('bootstrap_shell', 'sh')
lxc_init_interface['bootstrap_delay'] = _cloud_get('bootstrap_delay', None)
lxc_init_interface['autostart'] = autostart
lxc_init_interface['users'] = users
lxc_init_interface['password'] = password
lxc_init_interface['password_encrypted'] = password_encrypted
# be sure not to let objects goes inside the return
# as this return will be msgpacked for use in the runner !
lxc_init_interface['network_profile'] = network_profile
for i in ['cpu', 'cpuset', 'cpushare']:
if _cloud_get(i, None):
try:
lxc_init_interface[i] = vm_[i]
except KeyError:
lxc_init_interface[i] = profile[i]
return lxc_init_interface
def _get_profile(key, name, **kwargs):
if isinstance(name, dict):
profilename = name.pop('name', None)
return _get_profile(key, profilename, **name)
if name is None:
profile_match = {}
else:
profile_match = \
__salt__['config.get'](
'lxc.{1}:{0}'.format(name, key),
default=None,
merge='recurse'
)
if profile_match is None:
# No matching profile, make the profile an empty dict so that
# overrides can be applied below.
profile_match = {}
if not isinstance(profile_match, dict):
raise CommandExecutionError('lxc.{0} must be a dictionary'.format(key))
# Overlay the kwargs to override matched profile data
overrides = salt.utils.args.clean_kwargs(**copy.deepcopy(kwargs))
profile_match = salt.utils.dictupdate.update(
copy.deepcopy(profile_match),
overrides
)
return profile_match
def get_container_profile(name=None, **kwargs):
'''
.. versionadded:: 2015.5.0
Gather a pre-configured set of container configuration parameters. If no
arguments are passed, an empty profile is returned.
Profiles can be defined in the minion or master config files, or in pillar
or grains, and are loaded using :mod:`config.get
<salt.modules.config.get>`. The key under which LXC profiles must be
configured is ``lxc.container_profile.profile_name``. An example container
profile would be as follows:
.. code-block:: yaml
lxc.container_profile:
ubuntu:
template: ubuntu
backing: lvm
vgname: lxc
size: 1G
Parameters set in a profile can be overridden by passing additional
container creation arguments (such as the ones passed to :mod:`lxc.create
<salt.modules.lxc.create>`) to this function.
A profile can be defined either as the name of the profile, or a dictionary
of variable names and values. See the :ref:`LXC Tutorial
<tutorial-lxc-profiles>` for more information on how to use LXC profiles.
CLI Example:
.. code-block:: bash
salt-call lxc.get_container_profile centos
salt-call lxc.get_container_profile ubuntu template=ubuntu backing=overlayfs
'''
profile = _get_profile('container_profile', name, **kwargs)
return profile
def get_network_profile(name=None, **kwargs):
'''
.. versionadded:: 2015.5.0
Gather a pre-configured set of network configuration parameters. If no
arguments are passed, the following default profile is returned:
.. code-block:: python
{'eth0': {'link': 'br0', 'type': 'veth', 'flags': 'up'}}
Profiles can be defined in the minion or master config files, or in pillar
or grains, and are loaded using :mod:`config.get
<salt.modules.config.get>`. The key under which LXC profiles must be
configured is ``lxc.network_profile``. An example network profile would be
as follows:
.. code-block:: yaml
lxc.network_profile.centos:
eth0:
link: br0
type: veth
flags: up
To disable networking entirely:
.. code-block:: yaml
lxc.network_profile.centos:
eth0:
disable: true
Parameters set in a profile can be overridden by passing additional
arguments to this function.
A profile can be passed either as the name of the profile, or a
dictionary of variable names and values. See the :ref:`LXC Tutorial
<tutorial-lxc-profiles>` for more information on how to use network
profiles.
.. warning::
The ``ipv4``, ``ipv6``, ``gateway``, and ``link`` (bridge) settings in
network profiles will only work if the container doesn't redefine the
network configuration (for example in
``/etc/sysconfig/network-scripts/ifcfg-<interface_name>`` on
RHEL/CentOS, or ``/etc/network/interfaces`` on Debian/Ubuntu/etc.)
CLI Example:
.. code-block:: bash
salt-call lxc.get_network_profile default
'''
profile = _get_profile('network_profile', name, **kwargs)
return profile
def _rand_cpu_str(cpu):
'''
Return a random subset of cpus for the cpuset config
'''
cpu = int(cpu)
avail = __salt__['status.nproc']()
if cpu < avail:
return '0-{0}'.format(avail)
to_set = set()
while len(to_set) < cpu:
choice = random.randint(0, avail - 1)
if choice not in to_set:
to_set.add(six.text_type(choice))
return ','.join(sorted(to_set))
def _network_conf(conf_tuples=None, **kwargs):
'''
Network configuration defaults
network_profile
as for containers, we can either call this function
either with a network_profile dict or network profile name
in the kwargs
nic_opts
overrides or extra nics in the form {nic_name: {set: tings}
'''
nic = kwargs.get('network_profile', None)
ret = []
nic_opts = kwargs.get('nic_opts', {})
if nic_opts is None:
# coming from elsewhere
nic_opts = {}
if not conf_tuples:
conf_tuples = []
old = _get_veths(conf_tuples)
if not old:
old = {}
# if we have a profile name, get the profile and load the network settings
# this will obviously by default look for a profile called "eth0"
# or by what is defined in nic_opts
# and complete each nic settings by sane defaults
if nic and isinstance(nic, (six.string_types, dict)):
nicp = get_network_profile(nic)
else:
nicp = {}
if DEFAULT_NIC not in nicp:
nicp[DEFAULT_NIC] = {}
kwargs = copy.deepcopy(kwargs)
gateway = kwargs.pop('gateway', None)
bridge = kwargs.get('bridge', None)
if nic_opts:
for dev, args in six.iteritems(nic_opts):
ethx = nicp.setdefault(dev, {})
try:
ethx = salt.utils.dictupdate.update(ethx, args)
except AttributeError:
raise SaltInvocationError('Invalid nic_opts configuration')
ifs = [a for a in nicp]
ifs += [a for a in old if a not in nicp]
ifs.sort()
gateway_set = False
for dev in ifs:
args = nicp.get(dev, {})
opts = nic_opts.get(dev, {}) if nic_opts else {}
old_if = old.get(dev, {})
disable = opts.get('disable', args.get('disable', False))
if disable:
continue
mac = opts.get('mac',
opts.get('hwaddr',
args.get('mac',
args.get('hwaddr', ''))))
type_ = opts.get('type', args.get('type', ''))
flags = opts.get('flags', args.get('flags', ''))
link = opts.get('link', args.get('link', ''))
ipv4 = opts.get('ipv4', args.get('ipv4', ''))
ipv6 = opts.get('ipv6', args.get('ipv6', ''))
infos = salt.utils.odict.OrderedDict([
('lxc.network.type', {
'test': not type_,
'value': type_,
'old': old_if.get('lxc.network.type'),
'default': 'veth'}),
('lxc.network.name', {
'test': False,
'value': dev,
'old': dev,
'default': dev}),
('lxc.network.flags', {
'test': not flags,
'value': flags,
'old': old_if.get('lxc.network.flags'),
'default': 'up'}),
('lxc.network.link', {
'test': not link,
'value': link,
'old': old_if.get('lxc.network.link'),
'default': search_lxc_bridge()}),
('lxc.network.hwaddr', {
'test': not mac,
'value': mac,
'old': old_if.get('lxc.network.hwaddr'),
'default': salt.utils.network.gen_mac()}),
('lxc.network.ipv4', {
'test': not ipv4,
'value': ipv4,
'old': old_if.get('lxc.network.ipv4', ''),
'default': None}),
('lxc.network.ipv6', {
'test': not ipv6,
'value': ipv6,
'old': old_if.get('lxc.network.ipv6', ''),
'default': None})])
# for each parameter, if not explicitly set, the
# config value present in the LXC configuration should
# take precedence over the profile configuration
for info in list(infos.keys()):
bundle = infos[info]
if bundle['test']:
if bundle['old']:
bundle['value'] = bundle['old']
elif bundle['default']:
bundle['value'] = bundle['default']
for info, data in six.iteritems(infos):
if data['value']:
ret.append({info: data['value']})
for key, val in six.iteritems(args):
if key == 'link' and bridge:
val = bridge
val = opts.get(key, val)
if key in [
'type', 'flags', 'name',
'gateway', 'mac', 'link', 'ipv4', 'ipv6'
]:
continue
ret.append({'lxc.network.{0}'.format(key): val})
# gateway (in automode) must be appended following network conf !
if not gateway:
gateway = args.get('gateway', None)
if gateway is not None and not gateway_set:
ret.append({'lxc.network.ipv4.gateway': gateway})
# only one network gateway ;)
gateway_set = True
# normally, this won't happen
# set the gateway if specified even if we did
# not managed the network underlying
if gateway is not None and not gateway_set:
ret.append({'lxc.network.ipv4.gateway': gateway})
# only one network gateway ;)
gateway_set = True
new = _get_veths(ret)
# verify that we did not loose the mac settings
for iface in [a for a in new]:
ndata = new[iface]
nmac = ndata.get('lxc.network.hwaddr', '')
ntype = ndata.get('lxc.network.type', '')
omac, otype = '', ''
if iface in old:
odata = old[iface]
omac = odata.get('lxc.network.hwaddr', '')
otype = odata.get('lxc.network.type', '')
# default for network type is setted here
# attention not to change the network type
# without a good and explicit reason to.
if otype and not ntype:
ntype = otype
if not ntype:
ntype = 'veth'
new[iface]['lxc.network.type'] = ntype
if omac and not nmac:
new[iface]['lxc.network.hwaddr'] = omac
ret = []
for val in six.itervalues(new):
for row in val:
ret.append(salt.utils.odict.OrderedDict([(row, val[row])]))
# on old versions of lxc, still support the gateway auto mode
# if we didn't explicitly say no to
# (lxc.network.ipv4.gateway: auto)
if _LooseVersion(version()) <= _LooseVersion('1.0.7') and \
True not in ['lxc.network.ipv4.gateway' in a for a in ret] and \
True in ['lxc.network.ipv4' in a for a in ret]:
ret.append({'lxc.network.ipv4.gateway': 'auto'})
return ret
def _get_lxc_default_data(**kwargs):
kwargs = copy.deepcopy(kwargs)
ret = {}
for k in ['utsname', 'rootfs']:
val = kwargs.get(k, None)
if val is not None:
ret['lxc.{0}'.format(k)] = val
autostart = kwargs.get('autostart')
# autostart can have made in kwargs, but with the None
# value which is invalid, we need an explicit boolean
# autostart = on is the default.
if autostart is None:
autostart = True
# we will set the regular lxc marker to restart container at
# machine (re)boot only if we did not explicitly ask
# not to touch to the autostart settings via
# autostart == 'keep'
if autostart != 'keep':
if autostart:
ret['lxc.start.auto'] = '1'
else:
ret['lxc.start.auto'] = '0'
memory = kwargs.get('memory')
if memory is not None:
# converting the config value from MB to bytes
ret['lxc.cgroup.memory.limit_in_bytes'] = memory * 1024 * 1024
cpuset = kwargs.get('cpuset')
if cpuset:
ret['lxc.cgroup.cpuset.cpus'] = cpuset
cpushare = kwargs.get('cpushare')
cpu = kwargs.get('cpu')
if cpushare:
ret['lxc.cgroup.cpu.shares'] = cpushare
if cpu and not cpuset:
ret['lxc.cgroup.cpuset.cpus'] = _rand_cpu_str(cpu)
return ret
def _config_list(conf_tuples=None, only_net=False, **kwargs):
'''
Return a list of dicts from the salt level configurations
conf_tuples
_LXCConfig compatible list of entries which can contain
- string line
- tuple (lxc config param,value)
- dict of one entry: {lxc config param: value)
only_net
by default we add to the tuples a reflection of both
the real config if avalaible and a certain amount of
default values like the cpu parameters, the memory
and etc.
On the other hand, we also no matter the case reflect
the network configuration computed from the actual config if
available and given values.
if no_default_loads is set, we will only
reflect the network configuration back to the conf tuples
list
'''
# explicit cast
only_net = bool(only_net)
if not conf_tuples:
conf_tuples = []
kwargs = copy.deepcopy(kwargs)
ret = []
if not only_net:
default_data = _get_lxc_default_data(**kwargs)
for k, val in six.iteritems(default_data):
ret.append({k: val})
net_datas = _network_conf(conf_tuples=conf_tuples, **kwargs)
ret.extend(net_datas)
return ret
def _get_veths(net_data):
'''
Parse the nic setup inside lxc conf tuples back to a dictionary indexed by
network interface
'''
if isinstance(net_data, dict):
net_data = list(net_data.items())
nics = salt.utils.odict.OrderedDict()
current_nic = salt.utils.odict.OrderedDict()
no_names = True
for item in net_data:
if item and isinstance(item, dict):
item = list(item.items())[0]
# skip LXC configuration comment lines, and play only with tuples conf
elif isinstance(item, six.string_types):
# deal with reflection of commented lxc configs
sitem = item.strip()
if sitem.startswith('#') or not sitem:
continue
elif '=' in item:
item = tuple([a.strip() for a in item.split('=', 1)])
if item[0] == 'lxc.network.type':
current_nic = salt.utils.odict.OrderedDict()
if item[0] == 'lxc.network.name':
no_names = False
nics[item[1].strip()] = current_nic
current_nic[item[0].strip()] = item[1].strip()
# if not ethernet card name has been collected, assuming we collected
# data for eth0
if no_names and current_nic:
nics[DEFAULT_NIC] = current_nic
return nics
class _LXCConfig(object):
'''
LXC configuration data
'''
pattern = re.compile(r'^(\S+)(\s*)(=)(\s*)(.*)')
non_interpretable_pattern = re.compile(r'^((#.*)|(\s*))$')
def __init__(self, **kwargs):
kwargs = copy.deepcopy(kwargs)
self.name = kwargs.pop('name', None)
path = get_root_path(kwargs.get('path', None))
self.data = []
if self.name:
self.path = os.path.join(path, self.name, 'config')
if os.path.isfile(self.path):
with salt.utils.files.fopen(self.path) as fhr:
for line in salt.utils.data.decode(fhr.readlines()):
match = self.pattern.findall((line.strip()))
if match:
self.data.append((match[0][0], match[0][-1]))
match = self.non_interpretable_pattern.findall(
(line.strip()))
if match:
self.data.append(('', match[0][0]))
else:
self.path = None
def _replace(key, val):
if val:
self._filter_data(key)
self.data.append((key, val))
default_data = _get_lxc_default_data(**kwargs)
for key, val in six.iteritems(default_data):
_replace(key, val)
old_net = self._filter_data('lxc.network')
net_datas = _network_conf(conf_tuples=old_net, **kwargs)
if net_datas:
for row in net_datas:
self.data.extend(list(row.items()))
# be sure to reset harmful settings
for idx in ['lxc.cgroup.memory.limit_in_bytes']:
if not default_data.get(idx):
self._filter_data(idx)
def as_string(self):
chunks = ('{0[0]}{1}{0[1]}'.format(item, (' = ' if item[0] else '')) for item in self.data)
return '\n'.join(chunks) + '\n'
def write(self):
if self.path:
content = self.as_string()
# 2 step rendering to be sure not to open/wipe the config
# before as_string succeeds.
with salt.utils.files.fopen(self.path, 'w') as fic:
fic.write(salt.utils.stringutils.to_str(content))
fic.flush()
def tempfile(self):
# this might look like the function name is shadowing the
# module, but it's not since the method belongs to the class
ntf = tempfile.NamedTemporaryFile()
ntf.write(self.as_string())
ntf.flush()
return ntf
def _filter_data(self, pattern):
'''
Removes parameters which match the pattern from the config data
'''
removed = []
filtered = []
for param in self.data:
if not param[0].startswith(pattern):
filtered.append(param)
else:
removed.append(param)
self.data = filtered
return removed
def _get_base(**kwargs):
'''
If the needed base does not exist, then create it, if it does exist
create nothing and return the name of the base lxc container so
it can be cloned.
'''
profile = get_container_profile(copy.deepcopy(kwargs.get('profile')))
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, _marker)
profile_match = profile.pop(key, default)
# let kwarg overrides be the preferred choice
if kw_overrides_match is _marker:
return profile_match
return kw_overrides_match
template = select('template')
image = select('image')
vgname = select('vgname')
path = kwargs.get('path', None)
# remove the above three variables from kwargs, if they exist, to avoid
# duplicates if create() is invoked below.
for param in ('path', 'image', 'vgname', 'template'):
kwargs.pop(param, None)
if image:
proto = _urlparse(image).scheme
img_tar = __salt__['cp.cache_file'](image)
img_name = os.path.basename(img_tar)
hash_ = salt.utils.hashutils.get_hash(
img_tar,
__salt__['config.get']('hash_type'))
name = '__base_{0}_{1}_{2}'.format(proto, img_name, hash_)
if not exists(name, path=path):
create(name, template=template, image=image,
path=path, vgname=vgname, **kwargs)
if vgname:
rootfs = os.path.join('/dev', vgname, name)
edit_conf(info(name, path=path)['config'],
out_format='commented', **{'lxc.rootfs': rootfs})
return name
elif template:
name = '__base_{0}'.format(template)
if not exists(name, path=path):
create(name, template=template, image=image, path=path,
vgname=vgname, **kwargs)
if vgname:
rootfs = os.path.join('/dev', vgname, name)
edit_conf(info(name, path=path)['config'],
out_format='commented', **{'lxc.rootfs': rootfs})
return name
return ''
def cloud_init(name, vm_=None, **kwargs):
'''
Thin wrapper to lxc.init to be used from the saltcloud lxc driver
name
Name of the container
may be None and then guessed from saltcloud mapping
`vm_`
saltcloud mapping defaults for the vm
CLI Example:
.. code-block:: bash
salt '*' lxc.cloud_init foo
'''
init_interface = cloud_init_interface(name, vm_, **kwargs)
name = init_interface.pop('name', name)
return init(name, **init_interface)
def images(dist=None):
'''
.. versionadded:: 2015.5.0
List the available images for LXC's ``download`` template.
dist : None
Filter results to a single Linux distribution
CLI Examples:
.. code-block:: bash
salt myminion lxc.images
salt myminion lxc.images dist=centos
'''
out = __salt__['cmd.run_stdout'](
'lxc-create -n __imgcheck -t download -- --list',
ignore_retcode=True
)
if 'DIST' not in out:
raise CommandExecutionError(
'Unable to run the \'download\' template script. Is it installed?'
)
ret = {}
passed_header = False
for line in out.splitlines():
try:
distro, release, arch, variant, build_time = line.split()
except ValueError:
continue
if not passed_header:
if distro == 'DIST':
passed_header = True
continue
dist_list = ret.setdefault(distro, [])
dist_list.append({
'release': release,
'arch': arch,
'variant': variant,
'build_time': build_time,
})
if dist is not None:
return dict([(dist, ret.get(dist, []))])
return ret
def templates():
'''
.. versionadded:: 2015.5.0
List the available LXC template scripts installed on the minion
CLI Examples:
.. code-block:: bash
salt myminion lxc.templates
'''
try:
template_scripts = os.listdir('/usr/share/lxc/templates')
except OSError:
return []
else:
return [x[4:] for x in template_scripts if x.startswith('lxc-')]
def _after_ignition_network_profile(cmd,
ret,
name,
network_profile,
path,
nic_opts):
_clear_context()
if ret['retcode'] == 0 and exists(name, path=path):
if network_profile:
network_changes = apply_network_profile(name,
network_profile,
path=path,
nic_opts=nic_opts)
if network_changes:
log.info(
'Network changes from applying network profile \'%s\' '
'to newly-created container \'%s\':\n%s',
network_profile, name, network_changes
)
c_state = state(name, path=path)
return {'result': True,
'state': {'old': None, 'new': c_state}}
else:
if exists(name, path=path):
# destroy the container if it was partially created
cmd = 'lxc-destroy'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0}'.format(name)
__salt__['cmd.retcode'](cmd, python_shell=False)
raise CommandExecutionError(
'Container could not be created with cmd \'{0}\': {1}'
.format(cmd, ret['stderr'])
)
def create(name,
config=None,
profile=None,
network_profile=None,
nic_opts=None,
**kwargs):
'''
Create a new container.
name
Name of the container
config
The config file to use for the container. Defaults to system-wide
config (usually in /etc/lxc/lxc.conf).
profile
Profile to use in container creation (see
:mod:`lxc.get_container_profile
<salt.modules.lxc.get_container_profile>`). Values in a profile will be
overridden by the **Container Creation Arguments** listed below.
network_profile
Network profile to use for container
.. versionadded:: 2015.5.0
**Container Creation Arguments**
template
The template to use. For example, ``ubuntu`` or ``fedora``.
For a full list of available templates, check out
the :mod:`lxc.templates <salt.modules.lxc.templates>` function.
Conflicts with the ``image`` argument.
.. note::
The ``download`` template requires the following three parameters
to be defined in ``options``:
* **dist** - The name of the distribution
* **release** - Release name/version
* **arch** - Architecture of the container
The available images can be listed using the :mod:`lxc.images
<salt.modules.lxc.images>` function.
options
Template-specific options to pass to the lxc-create command. These
correspond to the long options (ones beginning with two dashes) that
the template script accepts. For example:
.. code-block:: bash
options='{"dist": "centos", "release": "6", "arch": "amd64"}'
For available template options, refer to the lxc template scripts
which are ususally located under ``/usr/share/lxc/templates``,
or run ``lxc-create -t <template> -h``.
image
A tar archive to use as the rootfs for the container. Conflicts with
the ``template`` argument.
backing
The type of storage to use. Set to ``lvm`` to use an LVM group.
Defaults to filesystem within /var/lib/lxc.
fstype
Filesystem type to use on LVM logical volume
size : 1G
Size of the volume to create. Only applicable if ``backing=lvm``.
vgname : lxc
Name of the LVM volume group in which to create the volume for this
container. Only applicable if ``backing=lvm``.
lvname
Name of the LVM logical volume in which to create the volume for this
container. Only applicable if ``backing=lvm``.
thinpool
Name of a pool volume that will be used for thin-provisioning this
container. Only applicable if ``backing=lvm``.
nic_opts
give extra opts overriding network profile values
path
parent path for the container creation (default: /var/lib/lxc)
zfsroot
Name of the ZFS root in which to create the volume for this container.
Only applicable if ``backing=zfs``. (default: tank/lxc)
.. versionadded:: 2015.8.0
'''
# Required params for 'download' template
download_template_deps = ('dist', 'release', 'arch')
cmd = 'lxc-create -n {0}'.format(name)
profile = get_container_profile(copy.deepcopy(profile))
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, None)
profile_match = profile.pop(key, default)
# Return the profile match if the the kwarg match was None, as the
# lxc.present state will pass these kwargs set to None by default.
if kw_overrides_match is None:
return profile_match
return kw_overrides_match
path = select('path')
if exists(name, path=path):
raise CommandExecutionError(
'Container \'{0}\' already exists'.format(name)
)
tvg = select('vgname')
vgname = tvg if tvg else __salt__['config.get']('lxc.vgname')
# The 'template' and 'image' params conflict
template = select('template')
image = select('image')
if template and image:
raise SaltInvocationError(
'Only one of \'template\' and \'image\' is permitted'
)
elif not any((template, image, profile)):
raise SaltInvocationError(
'At least one of \'template\', \'image\', and \'profile\' is '
'required'
)
options = select('options') or {}
backing = select('backing')
if vgname and not backing:
backing = 'lvm'
lvname = select('lvname')
thinpool = select('thinpool')
fstype = select('fstype')
size = select('size', '1G')
zfsroot = select('zfsroot')
if backing in ('dir', 'overlayfs', 'btrfs', 'zfs'):
fstype = None
size = None
# some backends won't support some parameters
if backing in ('aufs', 'dir', 'overlayfs', 'btrfs'):
lvname = vgname = thinpool = None
if image:
img_tar = __salt__['cp.cache_file'](image)
template = os.path.join(
os.path.dirname(salt.__file__),
'templates',
'lxc',
'salt_tarball')
options['imgtar'] = img_tar
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
if not os.path.exists(path):
os.makedirs(path)
if config:
cmd += ' -f {0}'.format(config)
if template:
cmd += ' -t {0}'.format(template)
if backing:
backing = backing.lower()
cmd += ' -B {0}'.format(backing)
if backing in ('zfs',):
if zfsroot:
cmd += ' --zfsroot {0}'.format(zfsroot)
if backing in ('lvm',):
if lvname:
cmd += ' --lvname {0}'.format(lvname)
if vgname:
cmd += ' --vgname {0}'.format(vgname)
if thinpool:
cmd += ' --thinpool {0}'.format(thinpool)
if backing not in ('dir', 'overlayfs'):
if fstype:
cmd += ' --fstype {0}'.format(fstype)
if size:
cmd += ' --fssize {0}'.format(size)
if options:
if template == 'download':
missing_deps = [x for x in download_template_deps
if x not in options]
if missing_deps:
raise SaltInvocationError(
'Missing params in \'options\' dict: {0}'
.format(', '.join(missing_deps))
)
cmd += ' --'
for key, val in six.iteritems(options):
cmd += ' --{0} {1}'.format(key, val)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
# please do not merge extra conflicting stuff
# inside those two line (ret =, return)
return _after_ignition_network_profile(cmd,
ret,
name,
network_profile,
path,
nic_opts)
def clone(name,
orig,
profile=None,
network_profile=None,
nic_opts=None,
**kwargs):
'''
Create a new container as a clone of another container
name
Name of the container
orig
Name of the original container to be cloned
profile
Profile to use in container cloning (see
:mod:`lxc.get_container_profile
<salt.modules.lxc.get_container_profile>`). Values in a profile will be
overridden by the **Container Cloning Arguments** listed below.
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
**Container Cloning Arguments**
snapshot
Use Copy On Write snapshots (LVM)
size : 1G
Size of the volume to create. Only applicable if ``backing=lvm``.
backing
The type of storage to use. Set to ``lvm`` to use an LVM group.
Defaults to filesystem within /var/lib/lxc.
network_profile
Network profile to use for container
.. versionadded:: 2015.8.0
nic_opts
give extra opts overriding network profile values
.. versionadded:: 2015.8.0
CLI Examples:
.. code-block:: bash
salt '*' lxc.clone myclone orig=orig_container
salt '*' lxc.clone myclone orig=orig_container snapshot=True
'''
profile = get_container_profile(copy.deepcopy(profile))
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, None)
profile_match = profile.pop(key, default)
# let kwarg overrides be the preferred choice
if kw_overrides_match is None:
return profile_match
return kw_overrides_match
path = select('path')
if exists(name, path=path):
raise CommandExecutionError(
'Container \'{0}\' already exists'.format(name)
)
_ensure_exists(orig, path=path)
if state(orig, path=path) != 'stopped':
raise CommandExecutionError(
'Container \'{0}\' must be stopped to be cloned'.format(orig)
)
backing = select('backing')
snapshot = select('snapshot')
if backing in ('dir',):
snapshot = False
if not snapshot:
snapshot = ''
else:
snapshot = '-s'
size = select('size', '1G')
if backing in ('dir', 'overlayfs', 'btrfs'):
size = None
# LXC commands and options changed in 2.0 - CF issue #34086 for details
if _LooseVersion(version()) >= _LooseVersion('2.0'):
# https://linuxcontainers.org/lxc/manpages//man1/lxc-copy.1.html
cmd = 'lxc-copy'
cmd += ' {0} -n {1} -N {2}'.format(snapshot, orig, name)
else:
# https://linuxcontainers.org/lxc/manpages//man1/lxc-clone.1.html
cmd = 'lxc-clone'
cmd += ' {0} -o {1} -n {2}'.format(snapshot, orig, name)
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
if not os.path.exists(path):
os.makedirs(path)
if backing:
backing = backing.lower()
cmd += ' -B {0}'.format(backing)
if backing not in ('dir', 'overlayfs'):
if size:
cmd += ' -L {0}'.format(size)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
# please do not merge extra conflicting stuff
# inside those two line (ret =, return)
return _after_ignition_network_profile(cmd,
ret,
name,
network_profile,
path,
nic_opts)
def ls_(active=None, cache=True, path=None):
'''
Return a list of the containers available on the minion
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
active
If ``True``, return only active (i.e. running) containers
.. versionadded:: 2015.5.0
CLI Example:
.. code-block:: bash
salt '*' lxc.ls
salt '*' lxc.ls active=True
'''
contextvar = 'lxc.ls{0}'.format(path)
if active:
contextvar += '.active'
if cache and (contextvar in __context__):
return __context__[contextvar]
else:
ret = []
cmd = 'lxc-ls'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
if active:
cmd += ' --active'
output = __salt__['cmd.run_stdout'](cmd, python_shell=False)
for line in output.splitlines():
ret.extend(line.split())
__context__[contextvar] = ret
return ret
def list_(extra=False, limit=None, path=None):
'''
List containers classified by state
extra
Also get per-container specific info. This will change the return data.
Instead of returning a list of containers, a dictionary of containers
and each container's output from :mod:`lxc.info
<salt.modules.lxc.info>`.
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
limit
Return output matching a specific state (**frozen**, **running**, or
**stopped**).
.. versionadded:: 2015.5.0
CLI Examples:
.. code-block:: bash
salt '*' lxc.list
salt '*' lxc.list extra=True
salt '*' lxc.list limit=running
'''
ctnrs = ls_(path=path)
if extra:
stopped = {}
frozen = {}
running = {}
else:
stopped = []
frozen = []
running = []
ret = {'running': running,
'stopped': stopped,
'frozen': frozen}
for container in ctnrs:
cmd = 'lxc-info'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0}'.format(container)
c_info = __salt__['cmd.run'](
cmd,
python_shell=False,
output_loglevel='debug'
)
c_state = None
for line in c_info.splitlines():
stat = line.split(':')
if stat[0] in ('State', 'state'):
c_state = stat[1].strip()
break
if not c_state or (limit is not None and c_state.lower() != limit):
continue
if extra:
infos = info(container, path=path)
method = 'update'
value = {container: infos}
else:
method = 'append'
value = container
if c_state == 'STOPPED':
getattr(stopped, method)(value)
continue
if c_state == 'FROZEN':
getattr(frozen, method)(value)
continue
if c_state == 'RUNNING':
getattr(running, method)(value)
continue
if limit is not None:
return ret.get(limit, {} if extra else [])
return ret
def _change_state(cmd,
name,
expected,
stdin=_marker,
stdout=_marker,
stderr=_marker,
with_communicate=_marker,
use_vt=_marker,
path=None):
pre = state(name, path=path)
if pre == expected:
return {'result': True,
'state': {'old': expected, 'new': expected},
'comment': 'Container \'{0}\' already {1}'
.format(name, expected)}
if cmd == 'lxc-destroy':
# Kill the container first
scmd = 'lxc-stop'
if path:
scmd += ' -P {0}'.format(pipes.quote(path))
scmd += ' -k -n {0}'.format(name)
__salt__['cmd.run'](scmd,
python_shell=False)
if path and ' -P ' not in cmd:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0}'.format(name)
# certain lxc commands need to be taken with care (lxc-start)
# as te command itself mess with double forks; we must not
# communicate with it, but just wait for the exit status
pkwargs = {'python_shell': False,
'redirect_stderr': True,
'with_communicate': with_communicate,
'use_vt': use_vt,
'stdin': stdin,
'stdout': stdout}
for i in [a for a in pkwargs]:
val = pkwargs[i]
if val is _marker:
pkwargs.pop(i, None)
_cmdout = __salt__['cmd.run_all'](cmd, **pkwargs)
if _cmdout['retcode'] != 0:
raise CommandExecutionError(
'Error changing state for container \'{0}\' using command '
'\'{1}\': {2}'.format(name, cmd, _cmdout['stdout'])
)
if expected is not None:
# some commands do not wait, so we will
rcmd = 'lxc-wait'
if path:
rcmd += ' -P {0}'.format(pipes.quote(path))
rcmd += ' -n {0} -s {1}'.format(name, expected.upper())
__salt__['cmd.run'](rcmd, python_shell=False, timeout=30)
_clear_context()
post = state(name, path=path)
ret = {'result': post == expected,
'state': {'old': pre, 'new': post}}
return ret
def _ensure_exists(name, path=None):
'''
Raise an exception if the container does not exist
'''
if not exists(name, path=path):
raise CommandExecutionError(
'Container \'{0}\' does not exist'.format(name)
)
def _ensure_running(name, no_start=False, path=None):
'''
If the container is not currently running, start it. This function returns
the state that the container was in before changing
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
'''
_ensure_exists(name, path=path)
pre = state(name, path=path)
if pre == 'running':
# This will be a no-op but running the function will give us a pretty
# return dict.
return start(name, path=path)
elif pre == 'stopped':
if no_start:
raise CommandExecutionError(
'Container \'{0}\' is not running'.format(name)
)
return start(name, path=path)
elif pre == 'frozen':
if no_start:
raise CommandExecutionError(
'Container \'{0}\' is not running'.format(name)
)
return unfreeze(name, path=path)
def restart(name, path=None, lxc_config=None, force=False):
'''
.. versionadded:: 2015.5.0
Restart the named container. If the container was not running, the
container will merely be started.
name
The name of the container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
lxc_config
path to a lxc config file
config file will be guessed from container name otherwise
.. versionadded:: 2015.8.0
force : False
If ``True``, the container will be force-stopped instead of gracefully
shut down
CLI Example:
.. code-block:: bash
salt myminion lxc.restart name
'''
_ensure_exists(name, path=path)
orig_state = state(name, path=path)
if orig_state != 'stopped':
stop(name, kill=force, path=path)
ret = start(name, path=path, lxc_config=lxc_config)
ret['state']['old'] = orig_state
if orig_state != 'stopped':
ret['restarted'] = True
return ret
def start(name, **kwargs):
'''
Start the named container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
lxc_config
path to a lxc config file
config file will be guessed from container name otherwise
.. versionadded:: 2015.8.0
use_vt
run the command through VT
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.start name
'''
path = kwargs.get('path', None)
cpath = get_root_path(path)
lxc_config = kwargs.get('lxc_config', None)
cmd = 'lxc-start'
if not lxc_config:
lxc_config = os.path.join(cpath, name, 'config')
# we try to start, even without config, if global opts are there
if os.path.exists(lxc_config):
cmd += ' -f {0}'.format(pipes.quote(lxc_config))
cmd += ' -d'
_ensure_exists(name, path=path)
if state(name, path=path) == 'frozen':
raise CommandExecutionError(
'Container \'{0}\' is frozen, use lxc.unfreeze'.format(name)
)
# lxc-start daemonize itself violently, we must not communicate with it
use_vt = kwargs.get('use_vt', None)
with_communicate = kwargs.get('with_communicate', False)
return _change_state(cmd, name, 'running',
stdout=None,
stderr=None,
stdin=None,
with_communicate=with_communicate,
path=path,
use_vt=use_vt)
def stop(name, kill=False, path=None, use_vt=None):
'''
Stop the named container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
kill: False
Do not wait for the container to stop, kill all tasks in the container.
Older LXC versions will stop containers like this irrespective of this
argument.
.. versionchanged:: 2015.5.0
Default value changed to ``False``
use_vt
run the command through VT
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.stop name
'''
_ensure_exists(name, path=path)
orig_state = state(name, path=path)
if orig_state == 'frozen' and not kill:
# Gracefully stopping a frozen container is slower than unfreezing and
# then stopping it (at least in my testing), so if we're not
# force-stopping the container, unfreeze it first.
unfreeze(name, path=path)
cmd = 'lxc-stop'
if kill:
cmd += ' -k'
ret = _change_state(cmd, name, 'stopped', use_vt=use_vt, path=path)
ret['state']['old'] = orig_state
return ret
def freeze(name, **kwargs):
'''
Freeze the named container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
start : False
If ``True`` and the container is stopped, the container will be started
before attempting to freeze.
.. versionadded:: 2015.5.0
use_vt
run the command through VT
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.freeze name
'''
use_vt = kwargs.get('use_vt', None)
path = kwargs.get('path', None)
_ensure_exists(name, path=path)
orig_state = state(name, path=path)
start_ = kwargs.get('start', False)
if orig_state == 'stopped':
if not start_:
raise CommandExecutionError(
'Container \'{0}\' is stopped'.format(name)
)
start(name, path=path)
cmd = 'lxc-freeze'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
ret = _change_state(cmd, name, 'frozen', use_vt=use_vt, path=path)
if orig_state == 'stopped' and start_:
ret['state']['old'] = orig_state
ret['started'] = True
ret['state']['new'] = state(name, path=path)
return ret
def unfreeze(name, path=None, use_vt=None):
'''
Unfreeze the named container.
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
use_vt
run the command through VT
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.unfreeze name
'''
_ensure_exists(name, path=path)
if state(name, path=path) == 'stopped':
raise CommandExecutionError(
'Container \'{0}\' is stopped'.format(name)
)
cmd = 'lxc-unfreeze'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
return _change_state(cmd, name, 'running', path=path, use_vt=use_vt)
def destroy(name, stop=False, path=None):
'''
Destroy the named container.
.. warning::
Destroys all data associated with the container.
path
path to the container parent directory (default: /var/lib/lxc)
.. versionadded:: 2015.8.0
stop : False
If ``True``, the container will be destroyed even if it is
running/frozen.
.. versionchanged:: 2015.5.0
Default value changed to ``False``. This more closely matches the
behavior of ``lxc-destroy(1)``, and also makes it less likely that
an accidental command will destroy a running container that was
being used for important things.
CLI Examples:
.. code-block:: bash
salt '*' lxc.destroy foo
salt '*' lxc.destroy foo stop=True
'''
_ensure_exists(name, path=path)
if not stop and state(name, path=path) != 'stopped':
raise CommandExecutionError(
'Container \'{0}\' is not stopped'.format(name)
)
return _change_state('lxc-destroy', name, None, path=path)
# Compatibility between LXC and nspawn
remove = salt.utils.functools.alias_function(destroy, 'remove')
def exists(name, path=None):
'''
Returns whether the named container exists.
path
path to the container parent directory (default: /var/lib/lxc)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.exists name
'''
_exists = name in ls_(path=path)
# container may be just created but we did cached earlier the
# lxc-ls results
if not _exists:
_exists = name in ls_(cache=False, path=path)
return _exists
def state(name, path=None):
'''
Returns the state of a container.
path
path to the container parent directory (default: /var/lib/lxc)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.state name
'''
# Don't use _ensure_exists() here, it will mess with _change_state()
cachekey = 'lxc.state.{0}{1}'.format(name, path)
try:
return __context__[cachekey]
except KeyError:
if not exists(name, path=path):
__context__[cachekey] = None
else:
cmd = 'lxc-info'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0}'.format(name)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
if ret['retcode'] != 0:
_clear_context()
raise CommandExecutionError(
'Unable to get state of container \'{0}\''.format(name)
)
c_infos = ret['stdout'].splitlines()
c_state = None
for c_info in c_infos:
stat = c_info.split(':')
if stat[0].lower() == 'state':
c_state = stat[1].strip().lower()
break
__context__[cachekey] = c_state
return __context__[cachekey]
def get_parameter(name, parameter, path=None):
'''
Returns the value of a cgroup parameter for a container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.get_parameter container_name memory.limit_in_bytes
'''
_ensure_exists(name, path=path)
cmd = 'lxc-cgroup'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0} {1}'.format(name, parameter)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
if ret['retcode'] != 0:
raise CommandExecutionError(
'Unable to retrieve value for \'{0}\''.format(parameter)
)
return ret['stdout'].strip()
def set_parameter(name, parameter, value, path=None):
'''
Set the value of a cgroup parameter for a container.
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.set_parameter name parameter value
'''
if not exists(name, path=path):
return None
cmd = 'lxc-cgroup'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0} {1} {2}'.format(name, parameter, value)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
if ret['retcode'] != 0:
return False
else:
return True
def info(name, path=None):
'''
Returns information about a container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.info name
'''
cachekey = 'lxc.info.{0}{1}'.format(name, path)
try:
return __context__[cachekey]
except KeyError:
_ensure_exists(name, path=path)
cpath = get_root_path(path)
try:
conf_file = os.path.join(cpath, name, 'config')
except AttributeError:
conf_file = os.path.join(cpath, six.text_type(name), 'config')
if not os.path.isfile(conf_file):
raise CommandExecutionError(
'LXC config file {0} does not exist'.format(conf_file)
)
ret = {}
config = []
with salt.utils.files.fopen(conf_file) as fp_:
for line in fp_:
line = salt.utils.stringutils.to_unicode(line)
comps = [x.strip() for x in
line.split('#', 1)[0].strip().split('=', 1)]
if len(comps) == 2:
config.append(tuple(comps))
ifaces = []
current = None
for key, val in config:
if key == 'lxc.network.type':
current = {'type': val}
ifaces.append(current)
elif not current:
continue
elif key.startswith('lxc.network.'):
current[key.replace('lxc.network.', '', 1)] = val
if ifaces:
ret['nics'] = ifaces
ret['rootfs'] = next(
(x[1] for x in config if x[0] == 'lxc.rootfs'),
None
)
ret['state'] = state(name, path=path)
ret['ips'] = []
ret['public_ips'] = []
ret['private_ips'] = []
ret['public_ipv4_ips'] = []
ret['public_ipv6_ips'] = []
ret['private_ipv4_ips'] = []
ret['private_ipv6_ips'] = []
ret['ipv4_ips'] = []
ret['ipv6_ips'] = []
ret['size'] = None
ret['config'] = conf_file
if ret['state'] == 'running':
try:
limit = int(get_parameter(name, 'memory.limit_in_bytes'))
except (CommandExecutionError, TypeError, ValueError):
limit = 0
try:
usage = int(get_parameter(name, 'memory.usage_in_bytes'))
except (CommandExecutionError, TypeError, ValueError):
usage = 0
free = limit - usage
ret['memory_limit'] = limit
ret['memory_free'] = free
size = run_stdout(name, 'df /', path=path, python_shell=False)
# The size is the 2nd column of the last line
ret['size'] = size.splitlines()[-1].split()[1]
# First try iproute2
ip_cmd = run_all(
name, 'ip link show', path=path, python_shell=False)
if ip_cmd['retcode'] == 0:
ip_data = ip_cmd['stdout']
ip_cmd = run_all(
name, 'ip addr show', path=path, python_shell=False)
ip_data += '\n' + ip_cmd['stdout']
ip_data = salt.utils.network._interfaces_ip(ip_data)
else:
# That didn't work, try ifconfig
ip_cmd = run_all(
name, 'ifconfig', path=path, python_shell=False)
if ip_cmd['retcode'] == 0:
ip_data = \
salt.utils.network._interfaces_ifconfig(
ip_cmd['stdout'])
else:
# Neither was successful, give up
log.warning(
'Unable to run ip or ifconfig in container \'%s\'', name
)
ip_data = {}
ret['ipv4_ips'] = salt.utils.network.ip_addrs(
include_loopback=True,
interface_data=ip_data
)
ret['ipv6_ips'] = salt.utils.network.ip_addrs6(
include_loopback=True,
interface_data=ip_data
)
ret['ips'] = ret['ipv4_ips'] + ret['ipv6_ips']
for address in ret['ipv4_ips']:
if address == '127.0.0.1':
ret['private_ips'].append(address)
ret['private_ipv4_ips'].append(address)
elif salt.utils.cloud.is_public_ip(address):
ret['public_ips'].append(address)
ret['public_ipv4_ips'].append(address)
else:
ret['private_ips'].append(address)
ret['private_ipv4_ips'].append(address)
for address in ret['ipv6_ips']:
if address == '::1' or address.startswith('fe80'):
ret['private_ips'].append(address)
ret['private_ipv6_ips'].append(address)
else:
ret['public_ips'].append(address)
ret['public_ipv6_ips'].append(address)
for key in [x for x in ret if x == 'ips' or x.endswith('ips')]:
ret[key].sort(key=_ip_sort)
__context__[cachekey] = ret
return __context__[cachekey]
def set_password(name, users, password, encrypted=True, path=None):
'''
.. versionchanged:: 2015.5.0
Function renamed from ``set_pass`` to ``set_password``. Additionally,
this function now supports (and defaults to using) a password hash
instead of a plaintext password.
Set the password of one or more system users inside containers
users
Comma-separated list (or python list) of users to change password
password
Password to set for the specified user(s)
encrypted : True
If true, ``password`` must be a password hash. Set to ``False`` to set
a plaintext password (not recommended).
.. versionadded:: 2015.5.0
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.set_pass container-name root '$6$uJ2uAyLU$KoI67t8As/0fXtJOPcHKGXmUpcoYUcVR2K6x93walnShTCQvjRwq25yIkiCBOqgbfdKQSFnAo28/ek6716vEV1'
salt '*' lxc.set_pass container-name root foo encrypted=False
'''
def _bad_user_input():
raise SaltInvocationError('Invalid input for \'users\' parameter')
if not isinstance(users, list):
try:
users = users.split(',')
except AttributeError:
_bad_user_input()
if not users:
_bad_user_input()
failed_users = []
for user in users:
result = retcode(name,
'chpasswd{0}'.format(' -e' if encrypted else ''),
stdin=':'.join((user, password)),
python_shell=False,
path=path,
chroot_fallback=True,
output_loglevel='quiet')
if result != 0:
failed_users.append(user)
if failed_users:
raise CommandExecutionError(
'Password change failed for the following user(s): {0}'
.format(', '.join(failed_users))
)
return True
set_pass = salt.utils.functools.alias_function(set_password, 'set_pass')
def update_lxc_conf(name, lxc_conf, lxc_conf_unset, path=None):
'''
Edit LXC configuration options
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.update_lxc_conf ubuntu \\
lxc_conf="[{'network.ipv4.ip':'10.0.3.5'}]" \\
lxc_conf_unset="['lxc.utsname']"
'''
_ensure_exists(name, path=path)
cpath = get_root_path(path)
lxc_conf_p = os.path.join(cpath, name, 'config')
if not os.path.exists(lxc_conf_p):
raise SaltInvocationError(
'Configuration file {0} does not exist'.format(lxc_conf_p)
)
changes = {'edited': [], 'added': [], 'removed': []}
ret = {'changes': changes, 'result': True, 'comment': ''}
# do not use salt.utils.files.fopen !
with salt.utils.files.fopen(lxc_conf_p, 'r') as fic:
filtered_lxc_conf = []
for row in lxc_conf:
if not row:
continue
for conf in row:
filtered_lxc_conf.append((conf.strip(),
row[conf].strip()))
ret['comment'] = 'lxc.conf is up to date'
lines = []
orig_config = salt.utils.stringutils.to_unicode(fic.read())
for line in orig_config.splitlines():
if line.startswith('#') or not line.strip():
lines.append([line, ''])
else:
line = line.split('=')
index = line.pop(0)
val = (index.strip(), '='.join(line).strip())
if val not in lines:
lines.append(val)
for key, item in filtered_lxc_conf:
matched = False
for idx, line in enumerate(lines[:]):
if line[0] == key:
matched = True
lines[idx] = (key, item)
if '='.join(line[1:]).strip() != item.strip():
changes['edited'].append(
({line[0]: line[1:]}, {key: item}))
break
if not matched:
if (key, item) not in lines:
lines.append((key, item))
changes['added'].append({key: item})
dest_lxc_conf = []
# filter unset
if lxc_conf_unset:
for line in lines:
for opt in lxc_conf_unset:
if (
not line[0].startswith(opt) and
line not in dest_lxc_conf
):
dest_lxc_conf.append(line)
else:
changes['removed'].append(opt)
else:
dest_lxc_conf = lines
conf = ''
for key, val in dest_lxc_conf:
if not val:
conf += '{0}\n'.format(key)
else:
conf += '{0} = {1}\n'.format(key.strip(), val.strip())
conf_changed = conf != orig_config
chrono = datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S')
if conf_changed:
# DO NOT USE salt.utils.files.fopen here, i got (kiorky)
# problems with lxc configs which were wiped !
with salt.utils.files.fopen('{0}.{1}'.format(lxc_conf_p, chrono), 'w') as wfic:
wfic.write(salt.utils.stringutils.to_str(conf))
with salt.utils.files.fopen(lxc_conf_p, 'w') as wfic:
wfic.write(salt.utils.stringutils.to_str(conf))
ret['comment'] = 'Updated'
ret['result'] = True
if not any(changes[x] for x in changes):
# Ensure an empty changes dict if nothing was modified
ret['changes'] = {}
return ret
def set_dns(name, dnsservers=None, searchdomains=None, path=None):
'''
.. versionchanged:: 2015.5.0
The ``dnsservers`` and ``searchdomains`` parameters can now be passed
as a comma-separated list.
Update /etc/resolv.confo
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.set_dns ubuntu "['8.8.8.8', '4.4.4.4']"
'''
if dnsservers is None:
dnsservers = ['8.8.8.8', '4.4.4.4']
elif not isinstance(dnsservers, list):
try:
dnsservers = dnsservers.split(',')
except AttributeError:
raise SaltInvocationError(
'Invalid input for \'dnsservers\' parameter'
)
if searchdomains is None:
searchdomains = []
elif not isinstance(searchdomains, list):
try:
searchdomains = searchdomains.split(',')
except AttributeError:
raise SaltInvocationError(
'Invalid input for \'searchdomains\' parameter'
)
dns = ['nameserver {0}'.format(x) for x in dnsservers]
dns.extend(['search {0}'.format(x) for x in searchdomains])
dns = '\n'.join(dns) + '\n'
# we may be using resolvconf in the container
# We need to handle that case with care:
# - we create the resolv.conf runtime directory (the
# linked directory) as anyway it will be shadowed when the real
# runned tmpfs mountpoint will be mounted.
# ( /etc/resolv.conf -> ../run/resolvconf/resolv.conf)
# Indeed, it can save us in any other case (running, eg, in a
# bare chroot when repairing or preparing the container for
# operation.
# - We also teach resolvconf to use the aforementioned dns.
# - We finally also set /etc/resolv.conf in all cases
rstr = __salt__['test.random_hash']()
# no tmp here, apparmor won't let us execute !
script = '/sbin/{0}_dns.sh'.format(rstr)
DNS_SCRIPT = "\n".join([
# 'set -x',
'#!/usr/bin/env bash',
'if [ -h /etc/resolv.conf ];then',
' if [ "x$(readlink /etc/resolv.conf)"'
' = "x../run/resolvconf/resolv.conf" ];then',
' if [ ! -d /run/resolvconf/ ];then',
' mkdir -p /run/resolvconf',
' fi',
' cat > /etc/resolvconf/resolv.conf.d/head <<EOF',
dns,
'EOF',
'',
' fi',
'fi',
'cat > /etc/resolv.conf <<EOF',
dns,
'EOF',
''])
result = run_all(
name, 'tee {0}'.format(script), path=path,
stdin=DNS_SCRIPT, python_shell=True)
if result['retcode'] == 0:
result = run_all(
name, 'sh -c "chmod +x {0};{0}"'.format(script),
path=path, python_shell=True)
# blindly delete the setter file
run_all(name,
'sh -c \'if [ -f "{0}" ];then rm -f "{0}";fi\''.format(script),
path=path, python_shell=True)
if result['retcode'] != 0:
error = ('Unable to write to /etc/resolv.conf in container \'{0}\''
.format(name))
if result['stderr']:
error += ': {0}'.format(result['stderr'])
raise CommandExecutionError(error)
return True
def running_systemd(name, cache=True, path=None):
'''
Determine if systemD is running
path
path to the container parent
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.running_systemd ubuntu
'''
k = 'lxc.systemd.test.{0}{1}'.format(name, path)
ret = __context__.get(k, None)
if ret is None or not cache:
rstr = __salt__['test.random_hash']()
# no tmp here, apparmor won't let us execute !
script = '/sbin/{0}_testsystemd.sh'.format(rstr)
# ubuntu already had since trusty some bits of systemd but was
# still using upstart ...
# we need to be a bit more careful that just testing that systemd
# is present
_script = textwrap.dedent(
'''\
#!/usr/bin/env bash
set -x
if ! command -v systemctl 1>/dev/null 2>/dev/null;then exit 2;fi
for i in \\
/run/systemd/journal/dev-log\\
/run/systemd/journal/flushed\\
/run/systemd/journal/kernel-seqnum\\
/run/systemd/journal/socket\\
/run/systemd/journal/stdout\\
/var/run/systemd/journal/dev-log\\
/var/run/systemd/journal/flushed\\
/var/run/systemd/journal/kernel-seqnum\\
/var/run/systemd/journal/socket\\
/var/run/systemd/journal/stdout\\
;do\\
if test -e ${i};then exit 0;fi
done
if test -d /var/systemd/system;then exit 0;fi
exit 2
''')
result = run_all(
name, 'tee {0}'.format(script), path=path,
stdin=_script, python_shell=True)
if result['retcode'] == 0:
result = run_all(name,
'sh -c "chmod +x {0};{0}"'''.format(script),
path=path,
python_shell=True)
else:
raise CommandExecutionError(
'lxc {0} failed to copy initd tester'.format(name))
run_all(name,
'sh -c \'if [ -f "{0}" ];then rm -f "{0}";fi\''
''.format(script),
path=path,
ignore_retcode=True,
python_shell=True)
if result['retcode'] != 0:
error = ('Unable to determine if the container \'{0}\''
' was running systemd, assmuming it is not.'
''.format(name))
if result['stderr']:
error += ': {0}'.format(result['stderr'])
# only cache result if we got a known exit code
if result['retcode'] in (0, 2):
__context__[k] = ret = not result['retcode']
return ret
def systemd_running_state(name, path=None):
'''
Get the operational state of a systemd based container
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.systemd_running_state ubuntu
'''
try:
ret = run_all(name,
'systemctl is-system-running',
path=path,
ignore_retcode=True)['stdout']
except CommandExecutionError:
ret = ''
return ret
def test_sd_started_state(name, path=None):
'''
Test if a systemd container is fully started
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.test_sd_started_state ubuntu
'''
qstate = systemd_running_state(name, path=path)
if qstate in ('initializing', 'starting'):
return False
elif qstate == '':
return None
else:
return True
def test_bare_started_state(name, path=None):
'''
Test if a non systemd container is fully started
For now, it consists only to test if the container is attachable
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.test_bare_started_state ubuntu
'''
try:
ret = run_all(
name, 'ls', path=path, ignore_retcode=True
)['retcode'] == 0
except (CommandExecutionError,):
ret = None
return ret
def wait_started(name, path=None, timeout=300):
'''
Check that the system has fully inited
This is actually very important for systemD based containers
see https://github.com/saltstack/salt/issues/23847
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.wait_started ubuntu
'''
if not exists(name, path=path):
raise CommandExecutionError(
'Container {0} does does exists'.format(name))
if not state(name, path=path) == 'running':
raise CommandExecutionError(
'Container {0} is not running'.format(name))
ret = False
if running_systemd(name, path=path):
test_started = test_sd_started_state
logger = log.error
else:
test_started = test_bare_started_state
logger = log.debug
now = time.time()
expire = now + timeout
now = time.time()
started = test_started(name, path=path)
while time.time() < expire and not started:
time.sleep(0.3)
started = test_started(name, path=path)
if started is None:
logger(
'Assuming %s is started, although we failed to detect that'
' is fully started correctly', name)
ret = True
else:
ret = started
return ret
def _needs_install(name, path=None):
ret = 0
has_minion = retcode(name,
'which salt-minion',
path=path,
ignore_retcode=True)
# we assume that installing is when no minion is running
# but testing the executable presence is not enougth for custom
# installs where the bootstrap can do much more than installing
# the bare salt binaries.
if has_minion:
processes = run_stdout(name, "ps aux", path=path)
if 'salt-minion' not in processes:
ret = 1
else:
retcode(name, 'salt-call --local service.stop salt-minion')
else:
ret = 1
return ret
def bootstrap(name,
config=None,
approve_key=True,
install=True,
pub_key=None,
priv_key=None,
bootstrap_url=None,
force_install=False,
unconditional_install=False,
path=None,
bootstrap_delay=None,
bootstrap_args=None,
bootstrap_shell=None):
'''
Install and configure salt in a container.
config
Minion configuration options. By default, the ``master`` option is set
to the target host's master.
approve_key
Request a pre-approval of the generated minion key. Requires
that the salt-master be configured to either auto-accept all keys or
expect a signing request from the target host. Default: ``True``
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
pub_key
Explicit public key to pressed the minion with (optional).
This can be either a filepath or a string representing the key
priv_key
Explicit private key to pressed the minion with (optional).
This can be either a filepath or a string representing the key
bootstrap_delay
Delay in seconds between end of container creation and bootstrapping.
Useful when waiting for container to obtain a DHCP lease.
.. versionadded:: 2015.5.0
bootstrap_url
url, content or filepath to the salt bootstrap script
bootstrap_args
salt bootstrap script arguments
bootstrap_shell
shell to execute the script into
install
Whether to attempt a full installation of salt-minion if needed.
force_install
Force installation even if salt-minion is detected,
this is the way to run vendor bootstrap scripts even
if a salt minion is already present in the container
unconditional_install
Run the script even if the container seems seeded
CLI Examples:
.. code-block:: bash
salt 'minion' lxc.bootstrap container_name [config=config_data] \\
[approve_key=(True|False)] [install=(True|False)]
'''
wait_started(name, path=path)
if bootstrap_delay is not None:
try:
log.info('LXC %s: bootstrap_delay: %s', name, bootstrap_delay)
time.sleep(bootstrap_delay)
except TypeError:
# Bad input, but assume since a value was passed that
# a delay was desired, and sleep for 5 seconds
time.sleep(5)
c_info = info(name, path=path)
if not c_info:
return None
# default set here as we cannot set them
# in def as it can come from a chain of procedures.
if bootstrap_args:
# custom bootstrap args can be totally customized, and user could
# have inserted the placeholder for the config directory.
# For example, some salt bootstrap script do not use at all -c
if '{0}' not in bootstrap_args:
bootstrap_args += ' -c {0}'
else:
bootstrap_args = '-c {0}'
if not bootstrap_shell:
bootstrap_shell = 'sh'
orig_state = _ensure_running(name, path=path)
if not orig_state:
return orig_state
if not force_install:
needs_install = _needs_install(name, path=path)
else:
needs_install = True
seeded = retcode(name,
'test -e \'{0}\''.format(SEED_MARKER),
path=path,
chroot_fallback=True,
ignore_retcode=True) == 0
tmp = tempfile.mkdtemp()
if seeded and not unconditional_install:
ret = True
else:
ret = False
cfg_files = __salt__['seed.mkconfig'](
config, tmp=tmp, id_=name, approve_key=approve_key,
pub_key=pub_key, priv_key=priv_key)
if needs_install or force_install or unconditional_install:
if install:
rstr = __salt__['test.random_hash']()
configdir = '/var/tmp/.c_{0}'.format(rstr)
cmd = 'install -m 0700 -d {0}'.format(configdir)
if run_all(
name, cmd, path=path, python_shell=False
)['retcode'] != 0:
log.error('tmpdir %s creation failed %s', configdir, cmd)
return False
bs_ = __salt__['config.gather_bootstrap_script'](
bootstrap=bootstrap_url)
script = '/sbin/{0}_bootstrap.sh'.format(rstr)
copy_to(name, bs_, script, path=path)
result = run_all(name,
'sh -c "chmod +x {0}"'.format(script),
path=path,
python_shell=True)
copy_to(name, cfg_files['config'],
os.path.join(configdir, 'minion'),
path=path)
copy_to(name, cfg_files['privkey'],
os.path.join(configdir, 'minion.pem'),
path=path)
copy_to(name, cfg_files['pubkey'],
os.path.join(configdir, 'minion.pub'),
path=path)
bootstrap_args = bootstrap_args.format(configdir)
cmd = ('{0} {2} {1}'
.format(bootstrap_shell,
bootstrap_args.replace("'", "''"),
script))
# log ASAP the forged bootstrap command which can be wrapped
# out of the output in case of unexpected problem
log.info('Running %s in LXC container \'%s\'', cmd, name)
ret = retcode(name, cmd, output_loglevel='info',
path=path, use_vt=True) == 0
run_all(name,
'sh -c \'if [ -f "{0}" ];then rm -f "{0}";fi\''
''.format(script),
path=path,
ignore_retcode=True,
python_shell=True)
else:
ret = False
else:
minion_config = salt.config.minion_config(cfg_files['config'])
pki_dir = minion_config['pki_dir']
copy_to(name,
cfg_files['config'],
'/etc/salt/minion',
path=path)
copy_to(name,
cfg_files['privkey'],
os.path.join(pki_dir, 'minion.pem'),
path=path)
copy_to(name,
cfg_files['pubkey'],
os.path.join(pki_dir, 'minion.pub'),
path=path)
run(name,
'salt-call --local service.enable salt-minion',
path=path,
python_shell=False)
ret = True
shutil.rmtree(tmp)
if orig_state == 'stopped':
stop(name, path=path)
elif orig_state == 'frozen':
freeze(name, path=path)
# mark seeded upon successful install
if ret:
run(name,
'touch \'{0}\''.format(SEED_MARKER),
path=path,
python_shell=False)
return ret
def attachable(name, path=None):
'''
Return True if the named container can be attached to via the lxc-attach
command
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt 'minion' lxc.attachable ubuntu
'''
cachekey = 'lxc.attachable{0}{1}'.format(name, path)
try:
return __context__[cachekey]
except KeyError:
_ensure_exists(name, path=path)
# Can't use run() here because it uses attachable() and would
# endlessly recurse, resulting in a traceback
log.debug('Checking if LXC container %s is attachable', name)
cmd = 'lxc-attach'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' --clear-env -n {0} -- /usr/bin/env'.format(name)
result = __salt__['cmd.retcode'](cmd,
python_shell=False,
output_loglevel='quiet',
ignore_retcode=True) == 0
__context__[cachekey] = result
return __context__[cachekey]
def _run(name,
cmd,
output=None,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=None,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
Common logic for lxc.run functions
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
'''
orig_state = state(name, path=path)
try:
if attachable(name, path=path):
ret = __salt__['container_resource.run'](
name,
cmd,
path=path,
container_type=__virtualname__,
exec_driver=EXEC_DRIVER,
output=output,
no_start=no_start,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
ignore_retcode=ignore_retcode,
use_vt=use_vt,
keep_env=keep_env)
else:
if not chroot_fallback:
raise CommandExecutionError(
'{0} is not attachable.'.format(name))
rootfs = info(name, path=path).get('rootfs')
# Set context var to make cmd.run_chroot run cmd.run instead of
# cmd.run_all.
__context__['cmd.run_chroot.func'] = __salt__['cmd.run']
ret = __salt__['cmd.run_chroot'](rootfs,
cmd,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
ignore_retcode=ignore_retcode)
except Exception:
raise
finally:
# Make sure we honor preserve_state, even if there was an exception
new_state = state(name, path=path)
if preserve_state:
if orig_state == 'stopped' and new_state != 'stopped':
stop(name, path=path)
elif orig_state == 'frozen' and new_state != 'frozen':
freeze(name, start=True, path=path)
if output in (None, 'all'):
return ret
else:
return ret[output]
def run(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.8.0
Run :mod:`cmd.run <salt.modules.cmdmod.run>` within a container
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed in stderr if the command being run
does not exist. If no output is returned using this function, try using
:mod:`lxc.run_stderr <salt.modules.lxc.run_stderr>` or
:mod:`lxc.run_all <salt.modules.lxc.run_all>`.
name
Name of the container in which to run the command
cmd
Command to run
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console. Assumes
``output=all``.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
CLI Example:
.. code-block:: bash
salt myminion lxc.run mycontainer 'ifconfig -a'
'''
return _run(name,
cmd,
path=path,
output=None,
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def run_stdout(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.5.0
Run :mod:`cmd.run_stdout <salt.modules.cmdmod.run_stdout>` within a container
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed in stderr if the command being run
does not exist. If no output is returned using this function, try using
:mod:`lxc.run_stderr <salt.modules.lxc.run_stderr>` or
:mod:`lxc.run_all <salt.modules.lxc.run_all>`.
name
Name of the container in which to run the command
cmd
Command to run
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console
``output=all``.
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
CLI Example:
.. code-block:: bash
salt myminion lxc.run_stdout mycontainer 'ifconfig -a'
'''
return _run(name,
cmd,
path=path,
output='stdout',
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def run_stderr(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.5.0
Run :mod:`cmd.run_stderr <salt.modules.cmdmod.run_stderr>` within a container
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed if the command being run does not
exist.
name
Name of the container in which to run the command
cmd
Command to run
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console
``output=all``.
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
CLI Example:
.. code-block:: bash
salt myminion lxc.run_stderr mycontainer 'ip addr show'
'''
return _run(name,
cmd,
path=path,
output='stderr',
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def retcode(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.5.0
Run :mod:`cmd.retcode <salt.modules.cmdmod.retcode>` within a container
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed in stderr if the command being run
does not exist. If the retcode is nonzero and not what was expected,
try using :mod:`lxc.run_stderr <salt.modules.lxc.run_stderr>`
or :mod:`lxc.run_all <salt.modules.lxc.run_all>`.
name
Name of the container in which to run the command
cmd
Command to run
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console
``output=all``.
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
CLI Example:
.. code-block:: bash
salt myminion lxc.retcode mycontainer 'ip addr show'
'''
return _run(name,
cmd,
output='retcode',
path=path,
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def run_all(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.5.0
Run :mod:`cmd.run_all <salt.modules.cmdmod.run_all>` within a container
.. note::
While the command is run within the container, it is initiated from the
host. Therefore, the PID in the return dict is from the host, not from
the container.
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed in stderr if the command being run
does not exist.
name
Name of the container in which to run the command
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
cmd
Command to run
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console
``output=all``.
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
CLI Example:
.. code-block:: bash
salt myminion lxc.run_all mycontainer 'ip addr show'
'''
return _run(name,
cmd,
output='all',
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
path=path,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def _get_md5(name, path):
'''
Get the MD5 checksum of a file from a container
'''
output = run_stdout(name, 'md5sum "{0}"'.format(path),
chroot_fallback=True,
ignore_retcode=True)
try:
return output.split()[0]
except IndexError:
# Destination file does not exist or could not be accessed
return None
def copy_to(name, source, dest, overwrite=False, makedirs=False, path=None):
'''
.. versionchanged:: 2015.8.0
Function renamed from ``lxc.cp`` to ``lxc.copy_to`` for consistency
with other container types. ``lxc.cp`` will continue to work, however.
For versions 2015.2.x and earlier, use ``lxc.cp``.
Copy a file or directory from the host into a container
name
Container name
source
File to be copied to the container
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
dest
Destination on the container. Must be an absolute path.
.. versionchanged:: 2015.5.0
If the destination is a directory, the file will be copied into
that directory.
overwrite : False
Unless this option is set to ``True``, then if a file exists at the
location specified by the ``dest`` argument, an error will be raised.
.. versionadded:: 2015.8.0
makedirs : False
Create the parent directory on the container if it does not already
exist.
.. versionadded:: 2015.5.0
CLI Example:
.. code-block:: bash
salt 'minion' lxc.copy_to /tmp/foo /root/foo
salt 'minion' lxc.cp /tmp/foo /root/foo
'''
_ensure_running(name, no_start=True, path=path)
return __salt__['container_resource.copy_to'](
name,
source,
dest,
container_type=__virtualname__,
path=path,
exec_driver=EXEC_DRIVER,
overwrite=overwrite,
makedirs=makedirs)
cp = salt.utils.functools.alias_function(copy_to, 'cp')
def read_conf(conf_file, out_format='simple'):
'''
Read in an LXC configuration file. By default returns a simple, unsorted
dict, but can also return a more detailed structure including blank lines
and comments.
out_format:
set to 'simple' if you need the old and unsupported behavior.
This won't support the multiple lxc values (eg: multiple network nics)
CLI Examples:
.. code-block:: bash
salt 'minion' lxc.read_conf /etc/lxc/mycontainer.conf
salt 'minion' lxc.read_conf /etc/lxc/mycontainer.conf out_format=commented
'''
ret_commented = []
ret_simple = {}
with salt.utils.files.fopen(conf_file, 'r') as fp_:
for line in salt.utils.data.decode(fp_.readlines()):
if '=' not in line:
ret_commented.append(line)
continue
comps = line.split('=')
value = '='.join(comps[1:]).strip()
comment = None
if value.strip().startswith('#'):
vcomps = value.strip().split('#')
value = vcomps[1].strip()
comment = '#'.join(vcomps[1:]).strip()
ret_commented.append({comps[0].strip(): {
'value': value,
'comment': comment,
}})
else:
ret_commented.append({comps[0].strip(): value})
ret_simple[comps[0].strip()] = value
if out_format == 'simple':
return ret_simple
return ret_commented
def write_conf(conf_file, conf):
'''
Write out an LXC configuration file
This is normally only used internally. The format of the data structure
must match that which is returned from ``lxc.read_conf()``, with
``out_format`` set to ``commented``.
An example might look like:
.. code-block:: python
[
{'lxc.utsname': '$CONTAINER_NAME'},
'# This is a commented line\\n',
'\\n',
{'lxc.mount': '$CONTAINER_FSTAB'},
{'lxc.rootfs': {'comment': 'This is another test',
'value': 'This is another test'}},
'\\n',
{'lxc.network.type': 'veth'},
{'lxc.network.flags': 'up'},
{'lxc.network.link': 'br0'},
{'lxc.network.mac': '$CONTAINER_MACADDR'},
{'lxc.network.ipv4': '$CONTAINER_IPADDR'},
{'lxc.network.name': '$CONTAINER_DEVICENAME'},
]
CLI Example:
.. code-block:: bash
salt 'minion' lxc.write_conf /etc/lxc/mycontainer.conf \\
out_format=commented
'''
if not isinstance(conf, list):
raise SaltInvocationError('Configuration must be passed as a list')
# construct the content prior to write to the file
# to avoid half written configs
content = ''
for line in conf:
if isinstance(line, (six.text_type, six.string_types)):
content += line
elif isinstance(line, dict):
for key in list(line.keys()):
out_line = None
if isinstance(
line[key],
(six.text_type, six.string_types, six.integer_types, float)
):
out_line = ' = '.join((key, "{0}".format(line[key])))
elif isinstance(line[key], dict):
out_line = ' = '.join((key, line[key]['value']))
if 'comment' in line[key]:
out_line = ' # '.join((out_line, line[key]['comment']))
if out_line:
content += out_line
content += '\n'
with salt.utils.files.fopen(conf_file, 'w') as fp_:
fp_.write(salt.utils.stringutils.to_str(content))
return {}
def edit_conf(conf_file,
out_format='simple',
read_only=False,
lxc_config=None,
**kwargs):
'''
Edit an LXC configuration file. If a setting is already present inside the
file, its value will be replaced. If it does not exist, it will be appended
to the end of the file. Comments and blank lines will be kept in-tact if
they already exist in the file.
out_format:
Set to simple if you need backward compatibility (multiple items for a
simple key is not supported)
read_only:
return only the edited configuration without applying it
to the underlying lxc configuration file
lxc_config:
List of dict containning lxc configuration items
For network configuration, you also need to add the device it belongs
to, otherwise it will default to eth0.
Also, any change to a network parameter will result in the whole
network reconfiguration to avoid mismatchs, be aware of that !
After the file is edited, its contents will be returned. By default, it
will be returned in ``simple`` format, meaning an unordered dict (which
may not represent the actual file order). Passing in an ``out_format`` of
``commented`` will return a data structure which accurately represents the
order and content of the file.
CLI Example:
.. code-block:: bash
salt 'minion' lxc.edit_conf /etc/lxc/mycontainer.conf \\
out_format=commented lxc.network.type=veth
salt 'minion' lxc.edit_conf /etc/lxc/mycontainer.conf \\
out_format=commented \\
lxc_config="[{'lxc.network.name': 'eth0', \\
'lxc.network.ipv4': '1.2.3.4'},
{'lxc.network.name': 'eth2', \\
'lxc.network.ipv4': '1.2.3.5',\\
'lxc.network.gateway': '1.2.3.1'}]"
'''
data = []
try:
conf = read_conf(conf_file, out_format=out_format)
except Exception:
conf = []
if not lxc_config:
lxc_config = []
lxc_config = copy.deepcopy(lxc_config)
# search if we want to access net config
# in that case, we will replace all the net configuration
net_config = []
for lxc_kws in lxc_config + [kwargs]:
net_params = {}
for kwarg in [a for a in lxc_kws]:
if kwarg.startswith('__'):
continue
if kwarg.startswith('lxc.network.'):
net_params[kwarg] = lxc_kws[kwarg]
lxc_kws.pop(kwarg, None)
if net_params:
net_config.append(net_params)
nic_opts = salt.utils.odict.OrderedDict()
for params in net_config:
dev = params.get('lxc.network.name', DEFAULT_NIC)
dev_opts = nic_opts.setdefault(dev, salt.utils.odict.OrderedDict())
for param in params:
opt = param.replace('lxc.network.', '')
opt = {'hwaddr': 'mac'}.get(opt, opt)
dev_opts[opt] = params[param]
net_changes = []
if nic_opts:
net_changes = _config_list(conf, only_net=True,
**{'network_profile': DEFAULT_NIC,
'nic_opts': nic_opts})
if net_changes:
lxc_config.extend(net_changes)
for line in conf:
if not isinstance(line, dict):
data.append(line)
continue
else:
for key in list(line.keys()):
val = line[key]
if net_changes and key.startswith('lxc.network.'):
continue
found = False
for ix in range(len(lxc_config)):
kw = lxc_config[ix]
if key in kw:
found = True
data.append({key: kw[key]})
del kw[key]
if not found:
data.append({key: val})
for lxc_kws in lxc_config:
for kwarg in lxc_kws:
data.append({kwarg: lxc_kws[kwarg]})
if read_only:
return data
write_conf(conf_file, data)
return read_conf(conf_file, out_format)
def reboot(name, path=None):
'''
Reboot a container.
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Examples:
.. code-block:: bash
salt 'minion' lxc.reboot myvm
'''
ret = {'result': True,
'changes': {},
'comment': '{0} rebooted'.format(name)}
does_exist = exists(name, path=path)
if does_exist and (state(name, path=path) == 'running'):
try:
stop(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
ret['result'] = False
return ret
if does_exist and (state(name, path=path) != 'running'):
try:
start(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
ret['result'] = False
return ret
ret['changes'][name] = 'rebooted'
return ret
def reconfigure(name,
cpu=None,
cpuset=None,
cpushare=None,
memory=None,
profile=None,
network_profile=None,
nic_opts=None,
bridge=None,
gateway=None,
autostart=None,
utsname=None,
rootfs=None,
path=None,
**kwargs):
'''
Reconfigure a container.
This only applies to a few property
name
Name of the container.
utsname
utsname of the container.
.. versionadded:: 2016.3.0
rootfs
rootfs of the container.
.. versionadded:: 2016.3.0
cpu
Select a random number of cpu cores and assign it to the cpuset, if the
cpuset option is set then this option will be ignored
cpuset
Explicitly define the cpus this container will be bound to
cpushare
cgroups cpu shares.
autostart
autostart container on reboot
memory
cgroups memory limit, in MB.
(0 for nolimit, None for old default 1024MB)
gateway
the ipv4 gateway to use
the default does nothing more than lxcutils does
bridge
the bridge to use
the default does nothing more than lxcutils does
nic
Network interfaces profile (defined in config or pillar).
nic_opts
Extra options for network interfaces, will override
``{"eth0": {"mac": "aa:bb:cc:dd:ee:ff", "ipv4": "10.1.1.1", "ipv6": "2001:db8::ff00:42:8329"}}``
or
``{"eth0": {"mac": "aa:bb:cc:dd:ee:ff", "ipv4": "10.1.1.1/24", "ipv6": "2001:db8::ff00:42:8329"}}``
path
path to the container parent
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt-call -lall mc_lxc_fork.reconfigure foobar nic_opts="{'eth1': {'mac': '00:16:3e:dd:ee:44'}}" memory=4
'''
changes = {}
cpath = get_root_path(path)
path = os.path.join(cpath, name, 'config')
ret = {'name': name,
'comment': 'config for {0} up to date'.format(name),
'result': True,
'changes': changes}
profile = get_container_profile(copy.deepcopy(profile))
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, _marker)
profile_match = profile.pop(key, default)
# let kwarg overrides be the preferred choice
if kw_overrides_match is _marker:
return profile_match
return kw_overrides_match
if nic_opts is not None and not network_profile:
network_profile = DEFAULT_NIC
if autostart is not None:
autostart = select('autostart', autostart)
else:
autostart = 'keep'
if not utsname:
utsname = select('utsname', utsname)
if os.path.exists(path):
old_chunks = read_conf(path, out_format='commented')
make_kw = salt.utils.odict.OrderedDict([
('utsname', utsname),
('rootfs', rootfs),
('autostart', autostart),
('cpu', cpu),
('gateway', gateway),
('cpuset', cpuset),
('cpushare', cpushare),
('network_profile', network_profile),
('nic_opts', nic_opts),
('bridge', bridge)])
# match 0 and none as memory = 0 in lxc config is harmful
if memory:
make_kw['memory'] = memory
kw = salt.utils.odict.OrderedDict()
for key, val in six.iteritems(make_kw):
if val is not None:
kw[key] = val
new_cfg = _config_list(conf_tuples=old_chunks, **kw)
if new_cfg:
edit_conf(path, out_format='commented', lxc_config=new_cfg)
chunks = read_conf(path, out_format='commented')
if old_chunks != chunks:
ret['comment'] = '{0} lxc config updated'.format(name)
if state(name, path=path) == 'running':
cret = reboot(name, path=path)
ret['result'] = cret['result']
return ret
def apply_network_profile(name, network_profile, nic_opts=None, path=None):
'''
.. versionadded:: 2015.5.0
Apply a network profile to a container
network_profile
profile name or default values (dict)
nic_opts
values to override in defaults (dict)
indexed by nic card names
path
path to the container parent
.. versionadded:: 2015.8.0
CLI Examples:
.. code-block:: bash
salt 'minion' lxc.apply_network_profile web1 centos
salt 'minion' lxc.apply_network_profile web1 centos \\
nic_opts="{'eth0': {'mac': 'xx:xx:xx:xx:xx:xx'}}"
salt 'minion' lxc.apply_network_profile web1 \\
"{'eth0': {'mac': 'xx:xx:xx:xx:xx:yy'}}"
nic_opts="{'eth0': {'mac': 'xx:xx:xx:xx:xx:xx'}}"
The special case to disable use of ethernet nics:
.. code-block:: bash
salt 'minion' lxc.apply_network_profile web1 centos \\
"{eth0: {disable: true}}"
'''
cpath = get_root_path(path)
cfgpath = os.path.join(cpath, name, 'config')
before = []
with salt.utils.files.fopen(cfgpath, 'r') as fp_:
for line in fp_:
before.append(line)
lxcconfig = _LXCConfig(name=name, path=path)
old_net = lxcconfig._filter_data('lxc.network')
network_params = {}
for param in _network_conf(
conf_tuples=old_net,
network_profile=network_profile, nic_opts=nic_opts
):
network_params.update(param)
if network_params:
edit_conf(cfgpath, out_format='commented', **network_params)
after = []
with salt.utils.files.fopen(cfgpath, 'r') as fp_:
for line in fp_:
after.append(line)
diff = ''
for line in difflib.unified_diff(before,
after,
fromfile='before',
tofile='after'):
diff += line
return diff
def get_pid(name, path=None):
'''
Returns a container pid.
Throw an exception if the container isn't running.
CLI Example:
.. code-block:: bash
salt '*' lxc.get_pid name
'''
if name not in list_(limit='running', path=path):
raise CommandExecutionError('Container {0} is not running, can\'t determine PID'.format(name))
info = __salt__['cmd.run']('lxc-info -n {0}'.format(name)).split("\n")
pid = [line.split(':')[1].strip() for line in info if re.match(r'\s*PID', line)][0]
return pid
def add_veth(name, interface_name, bridge=None, path=None):
'''
Add a veth to a container.
Note : this function doesn't update the container config, just add the interface at runtime
name
Name of the container
interface_name
Name of the interface in the container
bridge
Name of the bridge to attach the interface to (facultative)
CLI Examples:
.. code-block:: bash
salt '*' lxc.add_veth container_name eth1 br1
salt '*' lxc.add_veth container_name eth1
'''
# Get container init PID
pid = get_pid(name, path=path)
# Generate a ramdom string for veth and ensure that is isn't present on the system
while True:
random_veth = 'veth'+''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(6))
if random_veth not in __salt__['network.interfaces']().keys():
break
# Check prerequisites
if not __salt__['file.directory_exists']('/var/run/'):
raise CommandExecutionError('Directory /var/run required for lxc.add_veth doesn\'t exists')
if not __salt__['file.file_exists']('/proc/{0}/ns/net'.format(pid)):
raise CommandExecutionError('Proc file for container {0} network namespace doesn\'t exists'.format(name))
if not __salt__['file.directory_exists']('/var/run/netns'):
__salt__['file.mkdir']('/var/run/netns')
# Ensure that the symlink is up to date (change on container restart)
if __salt__['file.is_link']('/var/run/netns/{0}'.format(name)):
__salt__['file.remove']('/var/run/netns/{0}'.format(name))
__salt__['file.symlink']('/proc/{0}/ns/net'.format(pid), '/var/run/netns/{0}'.format(name))
# Ensure that interface doesn't exists
interface_exists = 0 == __salt__['cmd.retcode']('ip netns exec {netns} ip address list {interface}'.format(
netns=name,
interface=interface_name
))
if interface_exists:
raise CommandExecutionError('Interface {interface} already exists in {container}'.format(
interface=interface_name,
container=name
))
# Create veth and bring it up
if __salt__['cmd.retcode']('ip link add name {veth} type veth peer name {veth}_c'.format(veth=random_veth)) != 0:
raise CommandExecutionError('Error while creating the veth pair {0}'.format(random_veth))
if __salt__['cmd.retcode']('ip link set dev {0} up'.format(random_veth)) != 0:
raise CommandExecutionError('Error while bringing up host-side veth {0}'.format(random_veth))
# Attach it to the container
attached = 0 == __salt__['cmd.retcode']('ip link set dev {veth}_c netns {container} name {interface_name}'.format(
veth=random_veth,
container=name,
interface_name=interface_name
))
if not attached:
raise CommandExecutionError('Error while attaching the veth {veth} to container {container}'.format(
veth=random_veth,
container=name
))
__salt__['file.remove']('/var/run/netns/{0}'.format(name))
if bridge is not None:
__salt__['bridge.addif'](bridge, random_veth)
|
saltstack/salt
|
salt/modules/lxc.py
|
cloud_init
|
python
|
def cloud_init(name, vm_=None, **kwargs):
'''
Thin wrapper to lxc.init to be used from the saltcloud lxc driver
name
Name of the container
may be None and then guessed from saltcloud mapping
`vm_`
saltcloud mapping defaults for the vm
CLI Example:
.. code-block:: bash
salt '*' lxc.cloud_init foo
'''
init_interface = cloud_init_interface(name, vm_, **kwargs)
name = init_interface.pop('name', name)
return init(name, **init_interface)
|
Thin wrapper to lxc.init to be used from the saltcloud lxc driver
name
Name of the container
may be None and then guessed from saltcloud mapping
`vm_`
saltcloud mapping defaults for the vm
CLI Example:
.. code-block:: bash
salt '*' lxc.cloud_init foo
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/lxc.py#L1645-L1663
|
[
"def init(name,\n config=None,\n cpuset=None,\n cpushare=None,\n memory=None,\n profile=None,\n network_profile=None,\n nic_opts=None,\n cpu=None,\n autostart=True,\n password=None,\n password_encrypted=None,\n users=None,\n dnsservers=None,\n searchdomains=None,\n bridge=None,\n gateway=None,\n pub_key=None,\n priv_key=None,\n force_install=False,\n unconditional_install=False,\n bootstrap_delay=None,\n bootstrap_args=None,\n bootstrap_shell=None,\n bootstrap_url=None,\n **kwargs):\n '''\n Initialize a new container.\n\n This is a partial idempotent function as if it is already provisioned, we\n will reset a bit the lxc configuration file but much of the hard work will\n be escaped as markers will prevent re-execution of harmful tasks.\n\n name\n Name of the container\n\n image\n A tar archive to use as the rootfs for the container. Conflicts with\n the ``template`` argument.\n\n cpus\n Select a random number of cpu cores and assign it to the cpuset, if the\n cpuset option is set then this option will be ignored\n\n cpuset\n Explicitly define the cpus this container will be bound to\n\n cpushare\n cgroups cpu shares\n\n autostart\n autostart container on reboot\n\n memory\n cgroups memory limit, in MB\n\n .. versionchanged:: 2015.5.0\n If no value is passed, no limit is set. In earlier Salt versions,\n not passing this value causes a 1024MB memory limit to be set, and\n it was necessary to pass ``memory=0`` to set no limit.\n\n gateway\n the ipv4 gateway to use\n the default does nothing more than lxcutils does\n\n bridge\n the bridge to use\n the default does nothing more than lxcutils does\n\n network_profile\n Network profile to use for the container\n\n .. versionadded:: 2015.5.0\n\n nic_opts\n Extra options for network interfaces, will override\n\n ``{\"eth0\": {\"hwaddr\": \"aa:bb:cc:dd:ee:ff\", \"ipv4\": \"10.1.1.1\", \"ipv6\": \"2001:db8::ff00:42:8329\"}}``\n\n or\n\n ``{\"eth0\": {\"hwaddr\": \"aa:bb:cc:dd:ee:ff\", \"ipv4\": \"10.1.1.1/24\", \"ipv6\": \"2001:db8::ff00:42:8329\"}}``\n\n users\n Users for which the password defined in the ``password`` param should\n be set. Can be passed as a comma separated list or a python list.\n Defaults to just the ``root`` user.\n\n password\n Set the initial password for the users defined in the ``users``\n parameter\n\n password_encrypted : False\n Set to ``True`` to denote a password hash instead of a plaintext\n password\n\n .. versionadded:: 2015.5.0\n\n profile\n A LXC profile (defined in config or pillar).\n This can be either a real profile mapping or a string\n to retrieve it in configuration\n\n start\n Start the newly-created container\n\n dnsservers\n list of dns servers to set in the container, default [] (no setting)\n\n seed\n Seed the container with the minion config. Default: ``True``\n\n install\n If salt-minion is not already installed, install it. Default: ``True``\n\n config\n Optional config parameters. By default, the id is set to\n the name of the container.\n\n master\n salt master (default to minion's master)\n\n master_port\n salt master port (default to minion's master port)\n\n pub_key\n Explicit public key to preseed the minion with (optional).\n This can be either a filepath or a string representing the key\n\n priv_key\n Explicit private key to preseed the minion with (optional).\n This can be either a filepath or a string representing the key\n\n approve_key\n If explicit preseeding is not used;\n Attempt to request key approval from the master. Default: ``True``\n\n path\n path to the container parent directory\n default: /var/lib/lxc (system)\n\n .. versionadded:: 2015.8.0\n\n clone_from\n Original from which to use a clone operation to create the container.\n Default: ``None``\n\n bootstrap_delay\n Delay in seconds between end of container creation and bootstrapping.\n Useful when waiting for container to obtain a DHCP lease.\n\n .. versionadded:: 2015.5.0\n\n bootstrap_url\n See lxc.bootstrap\n\n bootstrap_shell\n See lxc.bootstrap\n\n bootstrap_args\n See lxc.bootstrap\n\n force_install\n Force installation even if salt-minion is detected,\n this is the way to run vendor bootstrap scripts even\n if a salt minion is already present in the container\n\n unconditional_install\n Run the script even if the container seems seeded\n\n CLI Example:\n\n .. code-block:: bash\n\n salt 'minion' lxc.init name [cpuset=cgroups_cpuset] \\\\\n [cpushare=cgroups_cpushare] [memory=cgroups_memory] \\\\\n [nic=nic_profile] [profile=lxc_profile] \\\\\n [nic_opts=nic_opts] [start=(True|False)] \\\\\n [seed=(True|False)] [install=(True|False)] \\\\\n [config=minion_config] [approve_key=(True|False) \\\\\n [clone_from=original] [autostart=True] \\\\\n [priv_key=/path_or_content] [pub_key=/path_or_content] \\\\\n [bridge=lxcbr0] [gateway=10.0.3.1] \\\\\n [dnsservers[dns1,dns2]] \\\\\n [users=[foo]] [password='secret'] \\\\\n [password_encrypted=(True|False)]\n\n '''\n ret = {'name': name,\n 'changes': {}}\n\n profile = get_container_profile(copy.deepcopy(profile))\n if not network_profile:\n network_profile = profile.get('network_profile')\n if not network_profile:\n network_profile = DEFAULT_NIC\n\n # Changes is a pointer to changes_dict['init']. This method is used so that\n # we can have a list of changes as they are made, providing an ordered list\n # of things that were changed.\n changes_dict = {'init': []}\n changes = changes_dict.get('init')\n\n if users is None:\n users = []\n dusers = ['root']\n for user in dusers:\n if user not in users:\n users.append(user)\n\n kw_overrides = copy.deepcopy(kwargs)\n\n def select(key, default=None):\n kw_overrides_match = kw_overrides.pop(key, _marker)\n profile_match = profile.pop(key, default)\n # let kwarg overrides be the preferred choice\n if kw_overrides_match is _marker:\n return profile_match\n return kw_overrides_match\n\n path = select('path')\n bpath = get_root_path(path)\n state_pre = state(name, path=path)\n tvg = select('vgname')\n vgname = tvg if tvg else __salt__['config.get']('lxc.vgname')\n start_ = select('start', True)\n autostart = select('autostart', autostart)\n seed = select('seed', True)\n install = select('install', True)\n seed_cmd = select('seed_cmd')\n salt_config = _get_salt_config(config, **kwargs)\n approve_key = select('approve_key', True)\n clone_from = select('clone_from')\n\n # If using a volume group then set up to make snapshot cow clones\n if vgname and not clone_from:\n try:\n kwargs['vgname'] = vgname\n clone_from = _get_base(profile=profile, **kwargs)\n except (SaltInvocationError, CommandExecutionError) as exc:\n ret['comment'] = exc.strerror\n if changes:\n ret['changes'] = changes_dict\n return ret\n if not kwargs.get('snapshot') is False:\n kwargs['snapshot'] = True\n does_exist = exists(name, path=path)\n to_reboot = False\n remove_seed_marker = False\n if does_exist:\n pass\n elif clone_from:\n remove_seed_marker = True\n try:\n clone(name, clone_from, profile=profile, **kwargs)\n changes.append({'create': 'Container cloned'})\n except (SaltInvocationError, CommandExecutionError) as exc:\n if 'already exists' in exc.strerror:\n changes.append({'create': 'Container already exists'})\n else:\n ret['result'] = False\n ret['comment'] = exc.strerror\n if changes:\n ret['changes'] = changes_dict\n return ret\n cfg = _LXCConfig(name=name, network_profile=network_profile,\n nic_opts=nic_opts, bridge=bridge, path=path,\n gateway=gateway, autostart=autostart,\n cpuset=cpuset, cpushare=cpushare, memory=memory)\n old_chunks = read_conf(cfg.path, out_format='commented')\n cfg.write()\n chunks = read_conf(cfg.path, out_format='commented')\n if old_chunks != chunks:\n to_reboot = True\n else:\n remove_seed_marker = True\n cfg = _LXCConfig(network_profile=network_profile,\n nic_opts=nic_opts, cpuset=cpuset, path=path,\n bridge=bridge, gateway=gateway,\n autostart=autostart,\n cpushare=cpushare, memory=memory)\n with cfg.tempfile() as cfile:\n try:\n create(name, config=cfile.name, profile=profile, **kwargs)\n changes.append({'create': 'Container created'})\n except (SaltInvocationError, CommandExecutionError) as exc:\n if 'already exists' in exc.strerror:\n changes.append({'create': 'Container already exists'})\n else:\n ret['comment'] = exc.strerror\n if changes:\n ret['changes'] = changes_dict\n return ret\n cpath = os.path.join(bpath, name, 'config')\n old_chunks = []\n if os.path.exists(cpath):\n old_chunks = read_conf(cpath, out_format='commented')\n new_cfg = _config_list(conf_tuples=old_chunks,\n cpu=cpu,\n network_profile=network_profile,\n nic_opts=nic_opts, bridge=bridge,\n cpuset=cpuset, cpushare=cpushare,\n memory=memory)\n if new_cfg:\n edit_conf(cpath, out_format='commented', lxc_config=new_cfg)\n chunks = read_conf(cpath, out_format='commented')\n if old_chunks != chunks:\n to_reboot = True\n\n # last time to be sure any of our property is correctly applied\n cfg = _LXCConfig(name=name, network_profile=network_profile,\n nic_opts=nic_opts, bridge=bridge, path=path,\n gateway=gateway, autostart=autostart,\n cpuset=cpuset, cpushare=cpushare, memory=memory)\n old_chunks = []\n if os.path.exists(cfg.path):\n old_chunks = read_conf(cfg.path, out_format='commented')\n cfg.write()\n chunks = read_conf(cfg.path, out_format='commented')\n if old_chunks != chunks:\n changes.append({'config': 'Container configuration updated'})\n to_reboot = True\n\n if to_reboot:\n try:\n stop(name, path=path)\n except (SaltInvocationError, CommandExecutionError) as exc:\n ret['comment'] = 'Unable to stop container: {0}'.format(exc)\n if changes:\n ret['changes'] = changes_dict\n return ret\n if not does_exist or (does_exist and state(name, path=path) != 'running'):\n try:\n start(name, path=path)\n except (SaltInvocationError, CommandExecutionError) as exc:\n ret['comment'] = 'Unable to stop container: {0}'.format(exc)\n if changes:\n ret['changes'] = changes_dict\n return ret\n\n if remove_seed_marker:\n run(name,\n 'rm -f \\'{0}\\''.format(SEED_MARKER),\n path=path,\n chroot_fallback=False,\n python_shell=False)\n\n # set the default user/password, only the first time\n if ret.get('result', True) and password:\n gid = '/.lxc.initial_pass'\n gids = [gid,\n '/lxc.initial_pass',\n '/.lxc.{0}.initial_pass'.format(name)]\n if not any(retcode(name,\n 'test -e \"{0}\"'.format(x),\n chroot_fallback=True,\n path=path,\n ignore_retcode=True) == 0\n for x in gids):\n # think to touch the default user generated by default templates\n # which has a really unsecure passwords...\n # root is defined as a member earlier in the code\n for default_user in ['ubuntu']:\n if (\n default_user not in users and\n retcode(name,\n 'id {0}'.format(default_user),\n python_shell=False,\n path=path,\n chroot_fallback=True,\n ignore_retcode=True) == 0\n ):\n users.append(default_user)\n for user in users:\n try:\n cret = set_password(name,\n users=[user],\n path=path,\n password=password,\n encrypted=password_encrypted)\n except (SaltInvocationError, CommandExecutionError) as exc:\n msg = '{0}: Failed to set password'.format(\n user) + exc.strerror\n # only hardfail in unrecoverable situation:\n # root cannot be setted up\n if user == 'root':\n ret['comment'] = msg\n ret['result'] = False\n else:\n log.debug(msg)\n if ret.get('result', True):\n changes.append({'password': 'Password(s) updated'})\n if retcode(name,\n ('sh -c \\'touch \"{0}\"; test -e \"{0}\"\\''\n .format(gid)),\n path=path,\n chroot_fallback=True,\n ignore_retcode=True) != 0:\n ret['comment'] = 'Failed to set password marker'\n changes[-1]['password'] += '. ' + ret['comment'] + '.'\n ret['result'] = False\n\n # set dns servers if any, only the first time\n if ret.get('result', True) and dnsservers:\n # retro compatibility, test also old markers\n gid = '/.lxc.initial_dns'\n gids = [gid,\n '/lxc.initial_dns',\n '/lxc.{0}.initial_dns'.format(name)]\n if not any(retcode(name,\n 'test -e \"{0}\"'.format(x),\n chroot_fallback=True,\n path=path,\n ignore_retcode=True) == 0\n for x in gids):\n try:\n set_dns(name,\n path=path,\n dnsservers=dnsservers,\n searchdomains=searchdomains)\n except (SaltInvocationError, CommandExecutionError) as exc:\n ret['comment'] = 'Failed to set DNS: ' + exc.strerror\n ret['result'] = False\n else:\n changes.append({'dns': 'DNS updated'})\n if retcode(name,\n ('sh -c \\'touch \"{0}\"; test -e \"{0}\"\\''\n .format(gid)),\n chroot_fallback=True,\n path=path,\n ignore_retcode=True) != 0:\n ret['comment'] = 'Failed to set DNS marker'\n changes[-1]['dns'] += '. ' + ret['comment'] + '.'\n ret['result'] = False\n\n # retro compatibility, test also old markers\n if remove_seed_marker:\n run(name,\n 'rm -f \\'{0}\\''.format(SEED_MARKER),\n path=path,\n python_shell=False)\n gid = '/.lxc.initial_seed'\n gids = [gid, '/lxc.initial_seed']\n if (\n any(retcode(name,\n 'test -e {0}'.format(x),\n path=path,\n chroot_fallback=True,\n ignore_retcode=True) == 0\n for x in gids) or not ret.get('result', True)\n ):\n pass\n elif seed or seed_cmd:\n if seed:\n try:\n result = bootstrap(\n name, config=salt_config, path=path,\n approve_key=approve_key,\n pub_key=pub_key, priv_key=priv_key,\n install=install,\n force_install=force_install,\n unconditional_install=unconditional_install,\n bootstrap_delay=bootstrap_delay,\n bootstrap_url=bootstrap_url,\n bootstrap_shell=bootstrap_shell,\n bootstrap_args=bootstrap_args)\n except (SaltInvocationError, CommandExecutionError) as exc:\n ret['comment'] = 'Bootstrap failed: ' + exc.strerror\n ret['result'] = False\n else:\n if not result:\n ret['comment'] = ('Bootstrap failed, see minion log for '\n 'more information')\n ret['result'] = False\n else:\n changes.append(\n {'bootstrap': 'Container successfully bootstrapped'}\n )\n elif seed_cmd:\n try:\n result = __salt__[seed_cmd](info(name, path=path)['rootfs'],\n name,\n salt_config)\n except (SaltInvocationError, CommandExecutionError) as exc:\n ret['comment'] = ('Bootstrap via seed_cmd \\'{0}\\' failed: {1}'\n .format(seed_cmd, exc.strerror))\n ret['result'] = False\n else:\n if not result:\n ret['comment'] = ('Bootstrap via seed_cmd \\'{0}\\' failed, '\n 'see minion log for more information '\n .format(seed_cmd))\n ret['result'] = False\n else:\n changes.append(\n {'bootstrap': 'Container successfully bootstrapped '\n 'using seed_cmd \\'{0}\\''\n .format(seed_cmd)}\n )\n\n if ret.get('result', True) and not start_:\n try:\n stop(name, path=path)\n except (SaltInvocationError, CommandExecutionError) as exc:\n ret['comment'] = 'Unable to stop container: {0}'.format(exc)\n ret['result'] = False\n\n state_post = state(name, path=path)\n if state_pre != state_post:\n changes.append({'state': {'old': state_pre, 'new': state_post}})\n\n if ret.get('result', True):\n ret['comment'] = ('Container \\'{0}\\' successfully initialized'\n .format(name))\n ret['result'] = True\n if changes:\n ret['changes'] = changes_dict\n return ret\n",
"def cloud_init_interface(name, vm_=None, **kwargs):\n '''\n Interface between salt.cloud.lxc driver and lxc.init\n ``vm_`` is a mapping of vm opts in the salt.cloud format\n as documented for the lxc driver.\n\n This can be used either:\n\n - from the salt cloud driver\n - because you find the argument to give easier here\n than using directly lxc.init\n\n .. warning::\n BE REALLY CAREFUL CHANGING DEFAULTS !!!\n IT'S A RETRO COMPATIBLE INTERFACE WITH\n THE SALT CLOUD DRIVER (ask kiorky).\n\n name\n name of the lxc container to create\n pub_key\n public key to preseed the minion with.\n Can be the keycontent or a filepath\n priv_key\n private key to preseed the minion with.\n Can be the keycontent or a filepath\n path\n path to the container parent directory (default: /var/lib/lxc)\n\n .. versionadded:: 2015.8.0\n\n profile\n :ref:`profile <tutorial-lxc-profiles-container>` selection\n network_profile\n :ref:`network profile <tutorial-lxc-profiles-network>` selection\n nic_opts\n per interface settings compatibles with\n network profile (ipv4/ipv6/link/gateway/mac/netmask)\n\n eg::\n\n - {'eth0': {'mac': '00:16:3e:01:29:40',\n 'gateway': None, (default)\n 'link': 'br0', (default)\n 'gateway': None, (default)\n 'netmask': '', (default)\n 'ip': '22.1.4.25'}}\n unconditional_install\n given to lxc.bootstrap (see relative doc)\n force_install\n given to lxc.bootstrap (see relative doc)\n config\n any extra argument for the salt minion config\n dnsservers\n list of DNS servers to set inside the container\n dns_via_dhcp\n do not set the dns servers, let them be set by the dhcp.\n autostart\n autostart the container at boot time\n password\n administrative password for the container\n bootstrap_delay\n delay before launching bootstrap script at Container init\n\n\n .. warning::\n\n Legacy but still supported options:\n\n from_container\n which container we use as a template\n when running lxc.clone\n image\n which template do we use when we\n are using lxc.create. This is the default\n mode unless you specify something in from_container\n backing\n which backing store to use.\n Values can be: overlayfs, dir(default), lvm, zfs, brtfs\n fstype\n When using a blockdevice level backing store,\n which filesystem to use on\n size\n When using a blockdevice level backing store,\n which size for the filesystem to use on\n snapshot\n Use snapshot when cloning the container source\n vgname\n if using LVM: vgname\n lvname\n if using LVM: lvname\n thinpool:\n if using LVM: thinpool\n ip\n ip for the primary nic\n mac\n mac address for the primary nic\n netmask\n netmask for the primary nic (24)\n = ``vm_.get('netmask', '24')``\n bridge\n bridge for the primary nic (lxcbr0)\n gateway\n network gateway for the container\n additional_ips\n additional ips which will be wired on the main bridge (br0)\n which is connected to internet.\n Be aware that you may use manual virtual mac addresses\n providen by you provider (online, ovh, etc).\n This is a list of mappings {ip: '', mac: '', netmask:''}\n Set gateway to None and an interface with a gateway\n to escape from another interface that eth0.\n eg::\n\n - {'mac': '00:16:3e:01:29:40',\n 'gateway': None, (default)\n 'link': 'br0', (default)\n 'netmask': '', (default)\n 'ip': '22.1.4.25'}\n\n users\n administrative users for the container\n default: [root] and [root, ubuntu] on ubuntu\n default_nic\n name of the first interface, you should\n really not override this\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' lxc.cloud_init_interface foo\n\n '''\n if vm_ is None:\n vm_ = {}\n vm_ = copy.deepcopy(vm_)\n vm_ = salt.utils.dictupdate.update(vm_, kwargs)\n\n profile_data = copy.deepcopy(\n vm_.get('lxc_profile',\n vm_.get('profile', {})))\n if not isinstance(profile_data, (dict, six.string_types)):\n profile_data = {}\n profile = get_container_profile(profile_data)\n\n def _cloud_get(k, default=None):\n return vm_.get(k, profile.get(k, default))\n\n if name is None:\n name = vm_['name']\n # if we are on ubuntu, default to ubuntu\n default_template = ''\n if __grains__.get('os', '') in ['Ubuntu']:\n default_template = 'ubuntu'\n image = _cloud_get('image')\n if not image:\n _cloud_get('template', default_template)\n backing = _cloud_get('backing', 'dir')\n if image:\n profile['template'] = image\n vgname = _cloud_get('vgname', None)\n if vgname:\n profile['vgname'] = vgname\n if backing:\n profile['backing'] = backing\n snapshot = _cloud_get('snapshot', False)\n autostart = bool(_cloud_get('autostart', True))\n dnsservers = _cloud_get('dnsservers', [])\n dns_via_dhcp = _cloud_get('dns_via_dhcp', True)\n password = _cloud_get('password', 's3cr3t')\n password_encrypted = _cloud_get('password_encrypted', False)\n fstype = _cloud_get('fstype', None)\n lvname = _cloud_get('lvname', None)\n thinpool = _cloud_get('thinpool', None)\n pub_key = _cloud_get('pub_key', None)\n priv_key = _cloud_get('priv_key', None)\n size = _cloud_get('size', '20G')\n script = _cloud_get('script', None)\n script_args = _cloud_get('script_args', None)\n users = _cloud_get('users', None)\n if users is None:\n users = []\n ssh_username = _cloud_get('ssh_username', None)\n if ssh_username and (ssh_username not in users):\n users.append(ssh_username)\n network_profile = _cloud_get('network_profile', None)\n nic_opts = kwargs.get('nic_opts', None)\n netmask = _cloud_get('netmask', '24')\n path = _cloud_get('path', None)\n bridge = _cloud_get('bridge', None)\n gateway = _cloud_get('gateway', None)\n unconditional_install = _cloud_get('unconditional_install', False)\n force_install = _cloud_get('force_install', True)\n config = _get_salt_config(_cloud_get('config', {}), **vm_)\n default_nic = _cloud_get('default_nic', DEFAULT_NIC)\n # do the interface with lxc.init mainly via nic_opts\n # to avoid extra and confusing extra use cases.\n if not isinstance(nic_opts, dict):\n nic_opts = salt.utils.odict.OrderedDict()\n # have a reference to the default nic\n eth0 = nic_opts.setdefault(default_nic,\n salt.utils.odict.OrderedDict())\n # lxc config is based of ifc order, be sure to use odicts.\n if not isinstance(nic_opts, salt.utils.odict.OrderedDict):\n bnic_opts = salt.utils.odict.OrderedDict()\n bnic_opts.update(nic_opts)\n nic_opts = bnic_opts\n gw = None\n # legacy salt.cloud scheme for network interfaces settings support\n bridge = _cloud_get('bridge', None)\n ip = _cloud_get('ip', None)\n mac = _cloud_get('mac', None)\n if ip:\n fullip = ip\n if netmask:\n fullip += '/{0}'.format(netmask)\n eth0['ipv4'] = fullip\n if mac is not None:\n eth0['mac'] = mac\n for ix, iopts in enumerate(_cloud_get(\"additional_ips\", [])):\n ifh = \"eth{0}\".format(ix+1)\n ethx = nic_opts.setdefault(ifh, {})\n if gw is None:\n gw = iopts.get('gateway', ethx.get('gateway', None))\n if gw:\n # only one and only one default gateway is allowed !\n eth0.pop('gateway', None)\n gateway = None\n # even if the gateway if on default \"eth0\" nic\n # and we popped it will work\n # as we reinject or set it here.\n ethx['gateway'] = gw\n elink = iopts.get('link', ethx.get('link', None))\n if elink:\n ethx['link'] = elink\n # allow dhcp\n aip = iopts.get('ipv4', iopts.get('ip', None))\n if aip:\n ethx['ipv4'] = aip\n nm = iopts.get('netmask', '')\n if nm:\n ethx['ipv4'] += '/{0}'.format(nm)\n for i in ('mac', 'hwaddr'):\n if i in iopts:\n ethx['mac'] = iopts[i]\n break\n if 'mac' not in ethx:\n ethx['mac'] = salt.utils.network.gen_mac()\n # last round checking for unique gateway and such\n gw = None\n for ethx in [a for a in nic_opts]:\n ndata = nic_opts[ethx]\n if gw:\n ndata.pop('gateway', None)\n if 'gateway' in ndata:\n gw = ndata['gateway']\n gateway = None\n # only use a default bridge / gateway if we configured them\n # via the legacy salt cloud configuration style.\n # On other cases, we should rely on settings provided by the new\n # salt lxc network profile style configuration which can\n # be also be overridden or a per interface basis via the nic_opts dict.\n if bridge:\n eth0['link'] = bridge\n if gateway:\n eth0['gateway'] = gateway\n #\n lxc_init_interface = {}\n lxc_init_interface['name'] = name\n lxc_init_interface['config'] = config\n lxc_init_interface['memory'] = _cloud_get('memory', 0) # nolimit\n lxc_init_interface['pub_key'] = pub_key\n lxc_init_interface['priv_key'] = priv_key\n lxc_init_interface['nic_opts'] = nic_opts\n for clone_from in ['clone_from', 'clone', 'from_container']:\n # clone_from should default to None if not available\n lxc_init_interface['clone_from'] = _cloud_get(clone_from, None)\n if lxc_init_interface['clone_from'] is not None:\n break\n lxc_init_interface['profile'] = profile\n lxc_init_interface['snapshot'] = snapshot\n lxc_init_interface['dnsservers'] = dnsservers\n lxc_init_interface['fstype'] = fstype\n lxc_init_interface['path'] = path\n lxc_init_interface['vgname'] = vgname\n lxc_init_interface['size'] = size\n lxc_init_interface['lvname'] = lvname\n lxc_init_interface['thinpool'] = thinpool\n lxc_init_interface['force_install'] = force_install\n lxc_init_interface['unconditional_install'] = (\n unconditional_install\n )\n lxc_init_interface['bootstrap_url'] = script\n lxc_init_interface['bootstrap_args'] = script_args\n lxc_init_interface['bootstrap_shell'] = _cloud_get('bootstrap_shell', 'sh')\n lxc_init_interface['bootstrap_delay'] = _cloud_get('bootstrap_delay', None)\n lxc_init_interface['autostart'] = autostart\n lxc_init_interface['users'] = users\n lxc_init_interface['password'] = password\n lxc_init_interface['password_encrypted'] = password_encrypted\n # be sure not to let objects goes inside the return\n # as this return will be msgpacked for use in the runner !\n lxc_init_interface['network_profile'] = network_profile\n for i in ['cpu', 'cpuset', 'cpushare']:\n if _cloud_get(i, None):\n try:\n lxc_init_interface[i] = vm_[i]\n except KeyError:\n lxc_init_interface[i] = profile[i]\n return lxc_init_interface\n"
] |
# -*- coding: utf-8 -*-
'''
Control Linux Containers via Salt
:depends: lxc package for distribution
lxc >= 1.0 (even beta alpha) is required
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import datetime
import copy
import string
import textwrap
import difflib
import logging
import tempfile
import os
import pipes
import time
import shutil
import re
import random
# Import salt libs
import salt.utils.args
import salt.utils.cloud
import salt.utils.data
import salt.utils.dictupdate
import salt.utils.files
import salt.utils.functools
import salt.utils.hashutils
import salt.utils.network
import salt.utils.odict
import salt.utils.path
import salt.utils.stringutils
from salt.exceptions import CommandExecutionError, SaltInvocationError
import salt.config
from salt.utils.versions import LooseVersion as _LooseVersion
# Import 3rd-party libs
from salt.ext import six
# pylint: disable=import-error,no-name-in-module
from salt.ext.six.moves import range # pylint: disable=redefined-builtin
from salt.ext.six.moves.urllib.parse import urlparse as _urlparse
# pylint: enable=import-error,no-name-in-module
# Set up logging
log = logging.getLogger(__name__)
# Don't shadow built-in's.
__func_alias__ = {
'list_': 'list',
'ls_': 'ls'
}
__virtualname__ = 'lxc'
DEFAULT_NIC = 'eth0'
DEFAULT_BR = 'br0'
SEED_MARKER = '/lxc.initial_seed'
EXEC_DRIVER = 'lxc-attach'
DEFAULT_PATH = '/var/lib/lxc'
_marker = object()
def __virtual__():
if salt.utils.path.which('lxc-start'):
return __virtualname__
# To speed up the whole thing, we decided to not use the
# subshell way and assume things are in place for lxc
# Discussion made by @kiorky and @thatch45
# lxc-version presence is not sufficient, in lxc1.0 alpha
# (precise backports), we have it and it is sufficient
# for the module to execute.
# elif salt.utils.path.which('lxc-version'):
# passed = False
# try:
# passed = subprocess.check_output(
# 'lxc-version').split(':')[1].strip() >= '1.0'
# except Exception:
# pass
# if not passed:
# log.warning('Support for lxc < 1.0 may be incomplete.')
# return 'lxc'
# return False
#
return (False, 'The lxc execution module cannot be loaded: the lxc-start binary is not in the path.')
def get_root_path(path):
'''
Get the configured lxc root for containers
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.get_root_path
'''
if not path:
path = __opts__.get('lxc.root_path', DEFAULT_PATH)
return path
def version():
'''
Return the actual lxc client version
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.version
'''
k = 'lxc.version'
if not __context__.get(k, None):
cversion = __salt__['cmd.run_all']('lxc-info --version')
if not cversion['retcode']:
ver = _LooseVersion(cversion['stdout'])
if ver < _LooseVersion('1.0'):
raise CommandExecutionError('LXC should be at least 1.0')
__context__[k] = "{0}".format(ver)
return __context__.get(k, None)
def _clear_context():
'''
Clear any lxc variables set in __context__
'''
for var in [x for x in __context__ if x.startswith('lxc.')]:
log.trace('Clearing __context__[\'%s\']', var)
__context__.pop(var, None)
def _ip_sort(ip):
'''Ip sorting'''
idx = '001'
if ip == '127.0.0.1':
idx = '200'
if ip == '::1':
idx = '201'
elif '::' in ip:
idx = '100'
return '{0}___{1}'.format(idx, ip)
def search_lxc_bridges():
'''
Search which bridges are potentially available as LXC bridges
CLI Example:
.. code-block:: bash
salt '*' lxc.search_lxc_bridges
'''
bridges = __context__.get('lxc.bridges', None)
# either match not yet called or no bridges were found
# to handle the case where lxc was not installed on the first
# call
if not bridges:
bridges = set()
running_bridges = set()
bridges.add(DEFAULT_BR)
try:
output = __salt__['cmd.run_all']('brctl show')
for line in output['stdout'].splitlines()[1:]:
if not line.startswith(' '):
running_bridges.add(line.split()[0].strip())
except (SaltInvocationError, CommandExecutionError):
pass
for ifc, ip in six.iteritems(
__grains__.get('ip_interfaces', {})
):
if ifc in running_bridges:
bridges.add(ifc)
elif os.path.exists(
'/sys/devices/virtual/net/{0}/bridge'.format(ifc)
):
bridges.add(ifc)
bridges = list(bridges)
# if we found interfaces that have lxc in their names
# we filter them as being the potential lxc bridges
# we also try to default on br0 on other cases
def sort_bridges(a):
pref = 'z'
if 'lxc' in a:
pref = 'a'
elif 'br0' == a:
pref = 'c'
return '{0}_{1}'.format(pref, a)
bridges.sort(key=sort_bridges)
__context__['lxc.bridges'] = bridges
return bridges
def search_lxc_bridge():
'''
Search the first bridge which is potentially available as LXC bridge
CLI Example:
.. code-block:: bash
salt '*' lxc.search_lxc_bridge
'''
return search_lxc_bridges()[0]
def _get_salt_config(config, **kwargs):
if not config:
config = kwargs.get('minion', {})
if not config:
config = {}
config.setdefault('master',
kwargs.get('master',
__opts__.get('master',
__opts__['id'])))
config.setdefault(
'master_port',
kwargs.get('master_port',
__opts__.get('master_port',
__opts__.get('ret_port',
__opts__.get('4506')))))
if not config['master']:
config = {}
return config
def cloud_init_interface(name, vm_=None, **kwargs):
'''
Interface between salt.cloud.lxc driver and lxc.init
``vm_`` is a mapping of vm opts in the salt.cloud format
as documented for the lxc driver.
This can be used either:
- from the salt cloud driver
- because you find the argument to give easier here
than using directly lxc.init
.. warning::
BE REALLY CAREFUL CHANGING DEFAULTS !!!
IT'S A RETRO COMPATIBLE INTERFACE WITH
THE SALT CLOUD DRIVER (ask kiorky).
name
name of the lxc container to create
pub_key
public key to preseed the minion with.
Can be the keycontent or a filepath
priv_key
private key to preseed the minion with.
Can be the keycontent or a filepath
path
path to the container parent directory (default: /var/lib/lxc)
.. versionadded:: 2015.8.0
profile
:ref:`profile <tutorial-lxc-profiles-container>` selection
network_profile
:ref:`network profile <tutorial-lxc-profiles-network>` selection
nic_opts
per interface settings compatibles with
network profile (ipv4/ipv6/link/gateway/mac/netmask)
eg::
- {'eth0': {'mac': '00:16:3e:01:29:40',
'gateway': None, (default)
'link': 'br0', (default)
'gateway': None, (default)
'netmask': '', (default)
'ip': '22.1.4.25'}}
unconditional_install
given to lxc.bootstrap (see relative doc)
force_install
given to lxc.bootstrap (see relative doc)
config
any extra argument for the salt minion config
dnsservers
list of DNS servers to set inside the container
dns_via_dhcp
do not set the dns servers, let them be set by the dhcp.
autostart
autostart the container at boot time
password
administrative password for the container
bootstrap_delay
delay before launching bootstrap script at Container init
.. warning::
Legacy but still supported options:
from_container
which container we use as a template
when running lxc.clone
image
which template do we use when we
are using lxc.create. This is the default
mode unless you specify something in from_container
backing
which backing store to use.
Values can be: overlayfs, dir(default), lvm, zfs, brtfs
fstype
When using a blockdevice level backing store,
which filesystem to use on
size
When using a blockdevice level backing store,
which size for the filesystem to use on
snapshot
Use snapshot when cloning the container source
vgname
if using LVM: vgname
lvname
if using LVM: lvname
thinpool:
if using LVM: thinpool
ip
ip for the primary nic
mac
mac address for the primary nic
netmask
netmask for the primary nic (24)
= ``vm_.get('netmask', '24')``
bridge
bridge for the primary nic (lxcbr0)
gateway
network gateway for the container
additional_ips
additional ips which will be wired on the main bridge (br0)
which is connected to internet.
Be aware that you may use manual virtual mac addresses
providen by you provider (online, ovh, etc).
This is a list of mappings {ip: '', mac: '', netmask:''}
Set gateway to None and an interface with a gateway
to escape from another interface that eth0.
eg::
- {'mac': '00:16:3e:01:29:40',
'gateway': None, (default)
'link': 'br0', (default)
'netmask': '', (default)
'ip': '22.1.4.25'}
users
administrative users for the container
default: [root] and [root, ubuntu] on ubuntu
default_nic
name of the first interface, you should
really not override this
CLI Example:
.. code-block:: bash
salt '*' lxc.cloud_init_interface foo
'''
if vm_ is None:
vm_ = {}
vm_ = copy.deepcopy(vm_)
vm_ = salt.utils.dictupdate.update(vm_, kwargs)
profile_data = copy.deepcopy(
vm_.get('lxc_profile',
vm_.get('profile', {})))
if not isinstance(profile_data, (dict, six.string_types)):
profile_data = {}
profile = get_container_profile(profile_data)
def _cloud_get(k, default=None):
return vm_.get(k, profile.get(k, default))
if name is None:
name = vm_['name']
# if we are on ubuntu, default to ubuntu
default_template = ''
if __grains__.get('os', '') in ['Ubuntu']:
default_template = 'ubuntu'
image = _cloud_get('image')
if not image:
_cloud_get('template', default_template)
backing = _cloud_get('backing', 'dir')
if image:
profile['template'] = image
vgname = _cloud_get('vgname', None)
if vgname:
profile['vgname'] = vgname
if backing:
profile['backing'] = backing
snapshot = _cloud_get('snapshot', False)
autostart = bool(_cloud_get('autostart', True))
dnsservers = _cloud_get('dnsservers', [])
dns_via_dhcp = _cloud_get('dns_via_dhcp', True)
password = _cloud_get('password', 's3cr3t')
password_encrypted = _cloud_get('password_encrypted', False)
fstype = _cloud_get('fstype', None)
lvname = _cloud_get('lvname', None)
thinpool = _cloud_get('thinpool', None)
pub_key = _cloud_get('pub_key', None)
priv_key = _cloud_get('priv_key', None)
size = _cloud_get('size', '20G')
script = _cloud_get('script', None)
script_args = _cloud_get('script_args', None)
users = _cloud_get('users', None)
if users is None:
users = []
ssh_username = _cloud_get('ssh_username', None)
if ssh_username and (ssh_username not in users):
users.append(ssh_username)
network_profile = _cloud_get('network_profile', None)
nic_opts = kwargs.get('nic_opts', None)
netmask = _cloud_get('netmask', '24')
path = _cloud_get('path', None)
bridge = _cloud_get('bridge', None)
gateway = _cloud_get('gateway', None)
unconditional_install = _cloud_get('unconditional_install', False)
force_install = _cloud_get('force_install', True)
config = _get_salt_config(_cloud_get('config', {}), **vm_)
default_nic = _cloud_get('default_nic', DEFAULT_NIC)
# do the interface with lxc.init mainly via nic_opts
# to avoid extra and confusing extra use cases.
if not isinstance(nic_opts, dict):
nic_opts = salt.utils.odict.OrderedDict()
# have a reference to the default nic
eth0 = nic_opts.setdefault(default_nic,
salt.utils.odict.OrderedDict())
# lxc config is based of ifc order, be sure to use odicts.
if not isinstance(nic_opts, salt.utils.odict.OrderedDict):
bnic_opts = salt.utils.odict.OrderedDict()
bnic_opts.update(nic_opts)
nic_opts = bnic_opts
gw = None
# legacy salt.cloud scheme for network interfaces settings support
bridge = _cloud_get('bridge', None)
ip = _cloud_get('ip', None)
mac = _cloud_get('mac', None)
if ip:
fullip = ip
if netmask:
fullip += '/{0}'.format(netmask)
eth0['ipv4'] = fullip
if mac is not None:
eth0['mac'] = mac
for ix, iopts in enumerate(_cloud_get("additional_ips", [])):
ifh = "eth{0}".format(ix+1)
ethx = nic_opts.setdefault(ifh, {})
if gw is None:
gw = iopts.get('gateway', ethx.get('gateway', None))
if gw:
# only one and only one default gateway is allowed !
eth0.pop('gateway', None)
gateway = None
# even if the gateway if on default "eth0" nic
# and we popped it will work
# as we reinject or set it here.
ethx['gateway'] = gw
elink = iopts.get('link', ethx.get('link', None))
if elink:
ethx['link'] = elink
# allow dhcp
aip = iopts.get('ipv4', iopts.get('ip', None))
if aip:
ethx['ipv4'] = aip
nm = iopts.get('netmask', '')
if nm:
ethx['ipv4'] += '/{0}'.format(nm)
for i in ('mac', 'hwaddr'):
if i in iopts:
ethx['mac'] = iopts[i]
break
if 'mac' not in ethx:
ethx['mac'] = salt.utils.network.gen_mac()
# last round checking for unique gateway and such
gw = None
for ethx in [a for a in nic_opts]:
ndata = nic_opts[ethx]
if gw:
ndata.pop('gateway', None)
if 'gateway' in ndata:
gw = ndata['gateway']
gateway = None
# only use a default bridge / gateway if we configured them
# via the legacy salt cloud configuration style.
# On other cases, we should rely on settings provided by the new
# salt lxc network profile style configuration which can
# be also be overridden or a per interface basis via the nic_opts dict.
if bridge:
eth0['link'] = bridge
if gateway:
eth0['gateway'] = gateway
#
lxc_init_interface = {}
lxc_init_interface['name'] = name
lxc_init_interface['config'] = config
lxc_init_interface['memory'] = _cloud_get('memory', 0) # nolimit
lxc_init_interface['pub_key'] = pub_key
lxc_init_interface['priv_key'] = priv_key
lxc_init_interface['nic_opts'] = nic_opts
for clone_from in ['clone_from', 'clone', 'from_container']:
# clone_from should default to None if not available
lxc_init_interface['clone_from'] = _cloud_get(clone_from, None)
if lxc_init_interface['clone_from'] is not None:
break
lxc_init_interface['profile'] = profile
lxc_init_interface['snapshot'] = snapshot
lxc_init_interface['dnsservers'] = dnsservers
lxc_init_interface['fstype'] = fstype
lxc_init_interface['path'] = path
lxc_init_interface['vgname'] = vgname
lxc_init_interface['size'] = size
lxc_init_interface['lvname'] = lvname
lxc_init_interface['thinpool'] = thinpool
lxc_init_interface['force_install'] = force_install
lxc_init_interface['unconditional_install'] = (
unconditional_install
)
lxc_init_interface['bootstrap_url'] = script
lxc_init_interface['bootstrap_args'] = script_args
lxc_init_interface['bootstrap_shell'] = _cloud_get('bootstrap_shell', 'sh')
lxc_init_interface['bootstrap_delay'] = _cloud_get('bootstrap_delay', None)
lxc_init_interface['autostart'] = autostart
lxc_init_interface['users'] = users
lxc_init_interface['password'] = password
lxc_init_interface['password_encrypted'] = password_encrypted
# be sure not to let objects goes inside the return
# as this return will be msgpacked for use in the runner !
lxc_init_interface['network_profile'] = network_profile
for i in ['cpu', 'cpuset', 'cpushare']:
if _cloud_get(i, None):
try:
lxc_init_interface[i] = vm_[i]
except KeyError:
lxc_init_interface[i] = profile[i]
return lxc_init_interface
def _get_profile(key, name, **kwargs):
if isinstance(name, dict):
profilename = name.pop('name', None)
return _get_profile(key, profilename, **name)
if name is None:
profile_match = {}
else:
profile_match = \
__salt__['config.get'](
'lxc.{1}:{0}'.format(name, key),
default=None,
merge='recurse'
)
if profile_match is None:
# No matching profile, make the profile an empty dict so that
# overrides can be applied below.
profile_match = {}
if not isinstance(profile_match, dict):
raise CommandExecutionError('lxc.{0} must be a dictionary'.format(key))
# Overlay the kwargs to override matched profile data
overrides = salt.utils.args.clean_kwargs(**copy.deepcopy(kwargs))
profile_match = salt.utils.dictupdate.update(
copy.deepcopy(profile_match),
overrides
)
return profile_match
def get_container_profile(name=None, **kwargs):
'''
.. versionadded:: 2015.5.0
Gather a pre-configured set of container configuration parameters. If no
arguments are passed, an empty profile is returned.
Profiles can be defined in the minion or master config files, or in pillar
or grains, and are loaded using :mod:`config.get
<salt.modules.config.get>`. The key under which LXC profiles must be
configured is ``lxc.container_profile.profile_name``. An example container
profile would be as follows:
.. code-block:: yaml
lxc.container_profile:
ubuntu:
template: ubuntu
backing: lvm
vgname: lxc
size: 1G
Parameters set in a profile can be overridden by passing additional
container creation arguments (such as the ones passed to :mod:`lxc.create
<salt.modules.lxc.create>`) to this function.
A profile can be defined either as the name of the profile, or a dictionary
of variable names and values. See the :ref:`LXC Tutorial
<tutorial-lxc-profiles>` for more information on how to use LXC profiles.
CLI Example:
.. code-block:: bash
salt-call lxc.get_container_profile centos
salt-call lxc.get_container_profile ubuntu template=ubuntu backing=overlayfs
'''
profile = _get_profile('container_profile', name, **kwargs)
return profile
def get_network_profile(name=None, **kwargs):
'''
.. versionadded:: 2015.5.0
Gather a pre-configured set of network configuration parameters. If no
arguments are passed, the following default profile is returned:
.. code-block:: python
{'eth0': {'link': 'br0', 'type': 'veth', 'flags': 'up'}}
Profiles can be defined in the minion or master config files, or in pillar
or grains, and are loaded using :mod:`config.get
<salt.modules.config.get>`. The key under which LXC profiles must be
configured is ``lxc.network_profile``. An example network profile would be
as follows:
.. code-block:: yaml
lxc.network_profile.centos:
eth0:
link: br0
type: veth
flags: up
To disable networking entirely:
.. code-block:: yaml
lxc.network_profile.centos:
eth0:
disable: true
Parameters set in a profile can be overridden by passing additional
arguments to this function.
A profile can be passed either as the name of the profile, or a
dictionary of variable names and values. See the :ref:`LXC Tutorial
<tutorial-lxc-profiles>` for more information on how to use network
profiles.
.. warning::
The ``ipv4``, ``ipv6``, ``gateway``, and ``link`` (bridge) settings in
network profiles will only work if the container doesn't redefine the
network configuration (for example in
``/etc/sysconfig/network-scripts/ifcfg-<interface_name>`` on
RHEL/CentOS, or ``/etc/network/interfaces`` on Debian/Ubuntu/etc.)
CLI Example:
.. code-block:: bash
salt-call lxc.get_network_profile default
'''
profile = _get_profile('network_profile', name, **kwargs)
return profile
def _rand_cpu_str(cpu):
'''
Return a random subset of cpus for the cpuset config
'''
cpu = int(cpu)
avail = __salt__['status.nproc']()
if cpu < avail:
return '0-{0}'.format(avail)
to_set = set()
while len(to_set) < cpu:
choice = random.randint(0, avail - 1)
if choice not in to_set:
to_set.add(six.text_type(choice))
return ','.join(sorted(to_set))
def _network_conf(conf_tuples=None, **kwargs):
'''
Network configuration defaults
network_profile
as for containers, we can either call this function
either with a network_profile dict or network profile name
in the kwargs
nic_opts
overrides or extra nics in the form {nic_name: {set: tings}
'''
nic = kwargs.get('network_profile', None)
ret = []
nic_opts = kwargs.get('nic_opts', {})
if nic_opts is None:
# coming from elsewhere
nic_opts = {}
if not conf_tuples:
conf_tuples = []
old = _get_veths(conf_tuples)
if not old:
old = {}
# if we have a profile name, get the profile and load the network settings
# this will obviously by default look for a profile called "eth0"
# or by what is defined in nic_opts
# and complete each nic settings by sane defaults
if nic and isinstance(nic, (six.string_types, dict)):
nicp = get_network_profile(nic)
else:
nicp = {}
if DEFAULT_NIC not in nicp:
nicp[DEFAULT_NIC] = {}
kwargs = copy.deepcopy(kwargs)
gateway = kwargs.pop('gateway', None)
bridge = kwargs.get('bridge', None)
if nic_opts:
for dev, args in six.iteritems(nic_opts):
ethx = nicp.setdefault(dev, {})
try:
ethx = salt.utils.dictupdate.update(ethx, args)
except AttributeError:
raise SaltInvocationError('Invalid nic_opts configuration')
ifs = [a for a in nicp]
ifs += [a for a in old if a not in nicp]
ifs.sort()
gateway_set = False
for dev in ifs:
args = nicp.get(dev, {})
opts = nic_opts.get(dev, {}) if nic_opts else {}
old_if = old.get(dev, {})
disable = opts.get('disable', args.get('disable', False))
if disable:
continue
mac = opts.get('mac',
opts.get('hwaddr',
args.get('mac',
args.get('hwaddr', ''))))
type_ = opts.get('type', args.get('type', ''))
flags = opts.get('flags', args.get('flags', ''))
link = opts.get('link', args.get('link', ''))
ipv4 = opts.get('ipv4', args.get('ipv4', ''))
ipv6 = opts.get('ipv6', args.get('ipv6', ''))
infos = salt.utils.odict.OrderedDict([
('lxc.network.type', {
'test': not type_,
'value': type_,
'old': old_if.get('lxc.network.type'),
'default': 'veth'}),
('lxc.network.name', {
'test': False,
'value': dev,
'old': dev,
'default': dev}),
('lxc.network.flags', {
'test': not flags,
'value': flags,
'old': old_if.get('lxc.network.flags'),
'default': 'up'}),
('lxc.network.link', {
'test': not link,
'value': link,
'old': old_if.get('lxc.network.link'),
'default': search_lxc_bridge()}),
('lxc.network.hwaddr', {
'test': not mac,
'value': mac,
'old': old_if.get('lxc.network.hwaddr'),
'default': salt.utils.network.gen_mac()}),
('lxc.network.ipv4', {
'test': not ipv4,
'value': ipv4,
'old': old_if.get('lxc.network.ipv4', ''),
'default': None}),
('lxc.network.ipv6', {
'test': not ipv6,
'value': ipv6,
'old': old_if.get('lxc.network.ipv6', ''),
'default': None})])
# for each parameter, if not explicitly set, the
# config value present in the LXC configuration should
# take precedence over the profile configuration
for info in list(infos.keys()):
bundle = infos[info]
if bundle['test']:
if bundle['old']:
bundle['value'] = bundle['old']
elif bundle['default']:
bundle['value'] = bundle['default']
for info, data in six.iteritems(infos):
if data['value']:
ret.append({info: data['value']})
for key, val in six.iteritems(args):
if key == 'link' and bridge:
val = bridge
val = opts.get(key, val)
if key in [
'type', 'flags', 'name',
'gateway', 'mac', 'link', 'ipv4', 'ipv6'
]:
continue
ret.append({'lxc.network.{0}'.format(key): val})
# gateway (in automode) must be appended following network conf !
if not gateway:
gateway = args.get('gateway', None)
if gateway is not None and not gateway_set:
ret.append({'lxc.network.ipv4.gateway': gateway})
# only one network gateway ;)
gateway_set = True
# normally, this won't happen
# set the gateway if specified even if we did
# not managed the network underlying
if gateway is not None and not gateway_set:
ret.append({'lxc.network.ipv4.gateway': gateway})
# only one network gateway ;)
gateway_set = True
new = _get_veths(ret)
# verify that we did not loose the mac settings
for iface in [a for a in new]:
ndata = new[iface]
nmac = ndata.get('lxc.network.hwaddr', '')
ntype = ndata.get('lxc.network.type', '')
omac, otype = '', ''
if iface in old:
odata = old[iface]
omac = odata.get('lxc.network.hwaddr', '')
otype = odata.get('lxc.network.type', '')
# default for network type is setted here
# attention not to change the network type
# without a good and explicit reason to.
if otype and not ntype:
ntype = otype
if not ntype:
ntype = 'veth'
new[iface]['lxc.network.type'] = ntype
if omac and not nmac:
new[iface]['lxc.network.hwaddr'] = omac
ret = []
for val in six.itervalues(new):
for row in val:
ret.append(salt.utils.odict.OrderedDict([(row, val[row])]))
# on old versions of lxc, still support the gateway auto mode
# if we didn't explicitly say no to
# (lxc.network.ipv4.gateway: auto)
if _LooseVersion(version()) <= _LooseVersion('1.0.7') and \
True not in ['lxc.network.ipv4.gateway' in a for a in ret] and \
True in ['lxc.network.ipv4' in a for a in ret]:
ret.append({'lxc.network.ipv4.gateway': 'auto'})
return ret
def _get_lxc_default_data(**kwargs):
kwargs = copy.deepcopy(kwargs)
ret = {}
for k in ['utsname', 'rootfs']:
val = kwargs.get(k, None)
if val is not None:
ret['lxc.{0}'.format(k)] = val
autostart = kwargs.get('autostart')
# autostart can have made in kwargs, but with the None
# value which is invalid, we need an explicit boolean
# autostart = on is the default.
if autostart is None:
autostart = True
# we will set the regular lxc marker to restart container at
# machine (re)boot only if we did not explicitly ask
# not to touch to the autostart settings via
# autostart == 'keep'
if autostart != 'keep':
if autostart:
ret['lxc.start.auto'] = '1'
else:
ret['lxc.start.auto'] = '0'
memory = kwargs.get('memory')
if memory is not None:
# converting the config value from MB to bytes
ret['lxc.cgroup.memory.limit_in_bytes'] = memory * 1024 * 1024
cpuset = kwargs.get('cpuset')
if cpuset:
ret['lxc.cgroup.cpuset.cpus'] = cpuset
cpushare = kwargs.get('cpushare')
cpu = kwargs.get('cpu')
if cpushare:
ret['lxc.cgroup.cpu.shares'] = cpushare
if cpu and not cpuset:
ret['lxc.cgroup.cpuset.cpus'] = _rand_cpu_str(cpu)
return ret
def _config_list(conf_tuples=None, only_net=False, **kwargs):
'''
Return a list of dicts from the salt level configurations
conf_tuples
_LXCConfig compatible list of entries which can contain
- string line
- tuple (lxc config param,value)
- dict of one entry: {lxc config param: value)
only_net
by default we add to the tuples a reflection of both
the real config if avalaible and a certain amount of
default values like the cpu parameters, the memory
and etc.
On the other hand, we also no matter the case reflect
the network configuration computed from the actual config if
available and given values.
if no_default_loads is set, we will only
reflect the network configuration back to the conf tuples
list
'''
# explicit cast
only_net = bool(only_net)
if not conf_tuples:
conf_tuples = []
kwargs = copy.deepcopy(kwargs)
ret = []
if not only_net:
default_data = _get_lxc_default_data(**kwargs)
for k, val in six.iteritems(default_data):
ret.append({k: val})
net_datas = _network_conf(conf_tuples=conf_tuples, **kwargs)
ret.extend(net_datas)
return ret
def _get_veths(net_data):
'''
Parse the nic setup inside lxc conf tuples back to a dictionary indexed by
network interface
'''
if isinstance(net_data, dict):
net_data = list(net_data.items())
nics = salt.utils.odict.OrderedDict()
current_nic = salt.utils.odict.OrderedDict()
no_names = True
for item in net_data:
if item and isinstance(item, dict):
item = list(item.items())[0]
# skip LXC configuration comment lines, and play only with tuples conf
elif isinstance(item, six.string_types):
# deal with reflection of commented lxc configs
sitem = item.strip()
if sitem.startswith('#') or not sitem:
continue
elif '=' in item:
item = tuple([a.strip() for a in item.split('=', 1)])
if item[0] == 'lxc.network.type':
current_nic = salt.utils.odict.OrderedDict()
if item[0] == 'lxc.network.name':
no_names = False
nics[item[1].strip()] = current_nic
current_nic[item[0].strip()] = item[1].strip()
# if not ethernet card name has been collected, assuming we collected
# data for eth0
if no_names and current_nic:
nics[DEFAULT_NIC] = current_nic
return nics
class _LXCConfig(object):
'''
LXC configuration data
'''
pattern = re.compile(r'^(\S+)(\s*)(=)(\s*)(.*)')
non_interpretable_pattern = re.compile(r'^((#.*)|(\s*))$')
def __init__(self, **kwargs):
kwargs = copy.deepcopy(kwargs)
self.name = kwargs.pop('name', None)
path = get_root_path(kwargs.get('path', None))
self.data = []
if self.name:
self.path = os.path.join(path, self.name, 'config')
if os.path.isfile(self.path):
with salt.utils.files.fopen(self.path) as fhr:
for line in salt.utils.data.decode(fhr.readlines()):
match = self.pattern.findall((line.strip()))
if match:
self.data.append((match[0][0], match[0][-1]))
match = self.non_interpretable_pattern.findall(
(line.strip()))
if match:
self.data.append(('', match[0][0]))
else:
self.path = None
def _replace(key, val):
if val:
self._filter_data(key)
self.data.append((key, val))
default_data = _get_lxc_default_data(**kwargs)
for key, val in six.iteritems(default_data):
_replace(key, val)
old_net = self._filter_data('lxc.network')
net_datas = _network_conf(conf_tuples=old_net, **kwargs)
if net_datas:
for row in net_datas:
self.data.extend(list(row.items()))
# be sure to reset harmful settings
for idx in ['lxc.cgroup.memory.limit_in_bytes']:
if not default_data.get(idx):
self._filter_data(idx)
def as_string(self):
chunks = ('{0[0]}{1}{0[1]}'.format(item, (' = ' if item[0] else '')) for item in self.data)
return '\n'.join(chunks) + '\n'
def write(self):
if self.path:
content = self.as_string()
# 2 step rendering to be sure not to open/wipe the config
# before as_string succeeds.
with salt.utils.files.fopen(self.path, 'w') as fic:
fic.write(salt.utils.stringutils.to_str(content))
fic.flush()
def tempfile(self):
# this might look like the function name is shadowing the
# module, but it's not since the method belongs to the class
ntf = tempfile.NamedTemporaryFile()
ntf.write(self.as_string())
ntf.flush()
return ntf
def _filter_data(self, pattern):
'''
Removes parameters which match the pattern from the config data
'''
removed = []
filtered = []
for param in self.data:
if not param[0].startswith(pattern):
filtered.append(param)
else:
removed.append(param)
self.data = filtered
return removed
def _get_base(**kwargs):
'''
If the needed base does not exist, then create it, if it does exist
create nothing and return the name of the base lxc container so
it can be cloned.
'''
profile = get_container_profile(copy.deepcopy(kwargs.get('profile')))
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, _marker)
profile_match = profile.pop(key, default)
# let kwarg overrides be the preferred choice
if kw_overrides_match is _marker:
return profile_match
return kw_overrides_match
template = select('template')
image = select('image')
vgname = select('vgname')
path = kwargs.get('path', None)
# remove the above three variables from kwargs, if they exist, to avoid
# duplicates if create() is invoked below.
for param in ('path', 'image', 'vgname', 'template'):
kwargs.pop(param, None)
if image:
proto = _urlparse(image).scheme
img_tar = __salt__['cp.cache_file'](image)
img_name = os.path.basename(img_tar)
hash_ = salt.utils.hashutils.get_hash(
img_tar,
__salt__['config.get']('hash_type'))
name = '__base_{0}_{1}_{2}'.format(proto, img_name, hash_)
if not exists(name, path=path):
create(name, template=template, image=image,
path=path, vgname=vgname, **kwargs)
if vgname:
rootfs = os.path.join('/dev', vgname, name)
edit_conf(info(name, path=path)['config'],
out_format='commented', **{'lxc.rootfs': rootfs})
return name
elif template:
name = '__base_{0}'.format(template)
if not exists(name, path=path):
create(name, template=template, image=image, path=path,
vgname=vgname, **kwargs)
if vgname:
rootfs = os.path.join('/dev', vgname, name)
edit_conf(info(name, path=path)['config'],
out_format='commented', **{'lxc.rootfs': rootfs})
return name
return ''
def init(name,
config=None,
cpuset=None,
cpushare=None,
memory=None,
profile=None,
network_profile=None,
nic_opts=None,
cpu=None,
autostart=True,
password=None,
password_encrypted=None,
users=None,
dnsservers=None,
searchdomains=None,
bridge=None,
gateway=None,
pub_key=None,
priv_key=None,
force_install=False,
unconditional_install=False,
bootstrap_delay=None,
bootstrap_args=None,
bootstrap_shell=None,
bootstrap_url=None,
**kwargs):
'''
Initialize a new container.
This is a partial idempotent function as if it is already provisioned, we
will reset a bit the lxc configuration file but much of the hard work will
be escaped as markers will prevent re-execution of harmful tasks.
name
Name of the container
image
A tar archive to use as the rootfs for the container. Conflicts with
the ``template`` argument.
cpus
Select a random number of cpu cores and assign it to the cpuset, if the
cpuset option is set then this option will be ignored
cpuset
Explicitly define the cpus this container will be bound to
cpushare
cgroups cpu shares
autostart
autostart container on reboot
memory
cgroups memory limit, in MB
.. versionchanged:: 2015.5.0
If no value is passed, no limit is set. In earlier Salt versions,
not passing this value causes a 1024MB memory limit to be set, and
it was necessary to pass ``memory=0`` to set no limit.
gateway
the ipv4 gateway to use
the default does nothing more than lxcutils does
bridge
the bridge to use
the default does nothing more than lxcutils does
network_profile
Network profile to use for the container
.. versionadded:: 2015.5.0
nic_opts
Extra options for network interfaces, will override
``{"eth0": {"hwaddr": "aa:bb:cc:dd:ee:ff", "ipv4": "10.1.1.1", "ipv6": "2001:db8::ff00:42:8329"}}``
or
``{"eth0": {"hwaddr": "aa:bb:cc:dd:ee:ff", "ipv4": "10.1.1.1/24", "ipv6": "2001:db8::ff00:42:8329"}}``
users
Users for which the password defined in the ``password`` param should
be set. Can be passed as a comma separated list or a python list.
Defaults to just the ``root`` user.
password
Set the initial password for the users defined in the ``users``
parameter
password_encrypted : False
Set to ``True`` to denote a password hash instead of a plaintext
password
.. versionadded:: 2015.5.0
profile
A LXC profile (defined in config or pillar).
This can be either a real profile mapping or a string
to retrieve it in configuration
start
Start the newly-created container
dnsservers
list of dns servers to set in the container, default [] (no setting)
seed
Seed the container with the minion config. Default: ``True``
install
If salt-minion is not already installed, install it. Default: ``True``
config
Optional config parameters. By default, the id is set to
the name of the container.
master
salt master (default to minion's master)
master_port
salt master port (default to minion's master port)
pub_key
Explicit public key to preseed the minion with (optional).
This can be either a filepath or a string representing the key
priv_key
Explicit private key to preseed the minion with (optional).
This can be either a filepath or a string representing the key
approve_key
If explicit preseeding is not used;
Attempt to request key approval from the master. Default: ``True``
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
clone_from
Original from which to use a clone operation to create the container.
Default: ``None``
bootstrap_delay
Delay in seconds between end of container creation and bootstrapping.
Useful when waiting for container to obtain a DHCP lease.
.. versionadded:: 2015.5.0
bootstrap_url
See lxc.bootstrap
bootstrap_shell
See lxc.bootstrap
bootstrap_args
See lxc.bootstrap
force_install
Force installation even if salt-minion is detected,
this is the way to run vendor bootstrap scripts even
if a salt minion is already present in the container
unconditional_install
Run the script even if the container seems seeded
CLI Example:
.. code-block:: bash
salt 'minion' lxc.init name [cpuset=cgroups_cpuset] \\
[cpushare=cgroups_cpushare] [memory=cgroups_memory] \\
[nic=nic_profile] [profile=lxc_profile] \\
[nic_opts=nic_opts] [start=(True|False)] \\
[seed=(True|False)] [install=(True|False)] \\
[config=minion_config] [approve_key=(True|False) \\
[clone_from=original] [autostart=True] \\
[priv_key=/path_or_content] [pub_key=/path_or_content] \\
[bridge=lxcbr0] [gateway=10.0.3.1] \\
[dnsservers[dns1,dns2]] \\
[users=[foo]] [password='secret'] \\
[password_encrypted=(True|False)]
'''
ret = {'name': name,
'changes': {}}
profile = get_container_profile(copy.deepcopy(profile))
if not network_profile:
network_profile = profile.get('network_profile')
if not network_profile:
network_profile = DEFAULT_NIC
# Changes is a pointer to changes_dict['init']. This method is used so that
# we can have a list of changes as they are made, providing an ordered list
# of things that were changed.
changes_dict = {'init': []}
changes = changes_dict.get('init')
if users is None:
users = []
dusers = ['root']
for user in dusers:
if user not in users:
users.append(user)
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, _marker)
profile_match = profile.pop(key, default)
# let kwarg overrides be the preferred choice
if kw_overrides_match is _marker:
return profile_match
return kw_overrides_match
path = select('path')
bpath = get_root_path(path)
state_pre = state(name, path=path)
tvg = select('vgname')
vgname = tvg if tvg else __salt__['config.get']('lxc.vgname')
start_ = select('start', True)
autostart = select('autostart', autostart)
seed = select('seed', True)
install = select('install', True)
seed_cmd = select('seed_cmd')
salt_config = _get_salt_config(config, **kwargs)
approve_key = select('approve_key', True)
clone_from = select('clone_from')
# If using a volume group then set up to make snapshot cow clones
if vgname and not clone_from:
try:
kwargs['vgname'] = vgname
clone_from = _get_base(profile=profile, **kwargs)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = exc.strerror
if changes:
ret['changes'] = changes_dict
return ret
if not kwargs.get('snapshot') is False:
kwargs['snapshot'] = True
does_exist = exists(name, path=path)
to_reboot = False
remove_seed_marker = False
if does_exist:
pass
elif clone_from:
remove_seed_marker = True
try:
clone(name, clone_from, profile=profile, **kwargs)
changes.append({'create': 'Container cloned'})
except (SaltInvocationError, CommandExecutionError) as exc:
if 'already exists' in exc.strerror:
changes.append({'create': 'Container already exists'})
else:
ret['result'] = False
ret['comment'] = exc.strerror
if changes:
ret['changes'] = changes_dict
return ret
cfg = _LXCConfig(name=name, network_profile=network_profile,
nic_opts=nic_opts, bridge=bridge, path=path,
gateway=gateway, autostart=autostart,
cpuset=cpuset, cpushare=cpushare, memory=memory)
old_chunks = read_conf(cfg.path, out_format='commented')
cfg.write()
chunks = read_conf(cfg.path, out_format='commented')
if old_chunks != chunks:
to_reboot = True
else:
remove_seed_marker = True
cfg = _LXCConfig(network_profile=network_profile,
nic_opts=nic_opts, cpuset=cpuset, path=path,
bridge=bridge, gateway=gateway,
autostart=autostart,
cpushare=cpushare, memory=memory)
with cfg.tempfile() as cfile:
try:
create(name, config=cfile.name, profile=profile, **kwargs)
changes.append({'create': 'Container created'})
except (SaltInvocationError, CommandExecutionError) as exc:
if 'already exists' in exc.strerror:
changes.append({'create': 'Container already exists'})
else:
ret['comment'] = exc.strerror
if changes:
ret['changes'] = changes_dict
return ret
cpath = os.path.join(bpath, name, 'config')
old_chunks = []
if os.path.exists(cpath):
old_chunks = read_conf(cpath, out_format='commented')
new_cfg = _config_list(conf_tuples=old_chunks,
cpu=cpu,
network_profile=network_profile,
nic_opts=nic_opts, bridge=bridge,
cpuset=cpuset, cpushare=cpushare,
memory=memory)
if new_cfg:
edit_conf(cpath, out_format='commented', lxc_config=new_cfg)
chunks = read_conf(cpath, out_format='commented')
if old_chunks != chunks:
to_reboot = True
# last time to be sure any of our property is correctly applied
cfg = _LXCConfig(name=name, network_profile=network_profile,
nic_opts=nic_opts, bridge=bridge, path=path,
gateway=gateway, autostart=autostart,
cpuset=cpuset, cpushare=cpushare, memory=memory)
old_chunks = []
if os.path.exists(cfg.path):
old_chunks = read_conf(cfg.path, out_format='commented')
cfg.write()
chunks = read_conf(cfg.path, out_format='commented')
if old_chunks != chunks:
changes.append({'config': 'Container configuration updated'})
to_reboot = True
if to_reboot:
try:
stop(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
if changes:
ret['changes'] = changes_dict
return ret
if not does_exist or (does_exist and state(name, path=path) != 'running'):
try:
start(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
if changes:
ret['changes'] = changes_dict
return ret
if remove_seed_marker:
run(name,
'rm -f \'{0}\''.format(SEED_MARKER),
path=path,
chroot_fallback=False,
python_shell=False)
# set the default user/password, only the first time
if ret.get('result', True) and password:
gid = '/.lxc.initial_pass'
gids = [gid,
'/lxc.initial_pass',
'/.lxc.{0}.initial_pass'.format(name)]
if not any(retcode(name,
'test -e "{0}"'.format(x),
chroot_fallback=True,
path=path,
ignore_retcode=True) == 0
for x in gids):
# think to touch the default user generated by default templates
# which has a really unsecure passwords...
# root is defined as a member earlier in the code
for default_user in ['ubuntu']:
if (
default_user not in users and
retcode(name,
'id {0}'.format(default_user),
python_shell=False,
path=path,
chroot_fallback=True,
ignore_retcode=True) == 0
):
users.append(default_user)
for user in users:
try:
cret = set_password(name,
users=[user],
path=path,
password=password,
encrypted=password_encrypted)
except (SaltInvocationError, CommandExecutionError) as exc:
msg = '{0}: Failed to set password'.format(
user) + exc.strerror
# only hardfail in unrecoverable situation:
# root cannot be setted up
if user == 'root':
ret['comment'] = msg
ret['result'] = False
else:
log.debug(msg)
if ret.get('result', True):
changes.append({'password': 'Password(s) updated'})
if retcode(name,
('sh -c \'touch "{0}"; test -e "{0}"\''
.format(gid)),
path=path,
chroot_fallback=True,
ignore_retcode=True) != 0:
ret['comment'] = 'Failed to set password marker'
changes[-1]['password'] += '. ' + ret['comment'] + '.'
ret['result'] = False
# set dns servers if any, only the first time
if ret.get('result', True) and dnsservers:
# retro compatibility, test also old markers
gid = '/.lxc.initial_dns'
gids = [gid,
'/lxc.initial_dns',
'/lxc.{0}.initial_dns'.format(name)]
if not any(retcode(name,
'test -e "{0}"'.format(x),
chroot_fallback=True,
path=path,
ignore_retcode=True) == 0
for x in gids):
try:
set_dns(name,
path=path,
dnsservers=dnsservers,
searchdomains=searchdomains)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Failed to set DNS: ' + exc.strerror
ret['result'] = False
else:
changes.append({'dns': 'DNS updated'})
if retcode(name,
('sh -c \'touch "{0}"; test -e "{0}"\''
.format(gid)),
chroot_fallback=True,
path=path,
ignore_retcode=True) != 0:
ret['comment'] = 'Failed to set DNS marker'
changes[-1]['dns'] += '. ' + ret['comment'] + '.'
ret['result'] = False
# retro compatibility, test also old markers
if remove_seed_marker:
run(name,
'rm -f \'{0}\''.format(SEED_MARKER),
path=path,
python_shell=False)
gid = '/.lxc.initial_seed'
gids = [gid, '/lxc.initial_seed']
if (
any(retcode(name,
'test -e {0}'.format(x),
path=path,
chroot_fallback=True,
ignore_retcode=True) == 0
for x in gids) or not ret.get('result', True)
):
pass
elif seed or seed_cmd:
if seed:
try:
result = bootstrap(
name, config=salt_config, path=path,
approve_key=approve_key,
pub_key=pub_key, priv_key=priv_key,
install=install,
force_install=force_install,
unconditional_install=unconditional_install,
bootstrap_delay=bootstrap_delay,
bootstrap_url=bootstrap_url,
bootstrap_shell=bootstrap_shell,
bootstrap_args=bootstrap_args)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Bootstrap failed: ' + exc.strerror
ret['result'] = False
else:
if not result:
ret['comment'] = ('Bootstrap failed, see minion log for '
'more information')
ret['result'] = False
else:
changes.append(
{'bootstrap': 'Container successfully bootstrapped'}
)
elif seed_cmd:
try:
result = __salt__[seed_cmd](info(name, path=path)['rootfs'],
name,
salt_config)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = ('Bootstrap via seed_cmd \'{0}\' failed: {1}'
.format(seed_cmd, exc.strerror))
ret['result'] = False
else:
if not result:
ret['comment'] = ('Bootstrap via seed_cmd \'{0}\' failed, '
'see minion log for more information '
.format(seed_cmd))
ret['result'] = False
else:
changes.append(
{'bootstrap': 'Container successfully bootstrapped '
'using seed_cmd \'{0}\''
.format(seed_cmd)}
)
if ret.get('result', True) and not start_:
try:
stop(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
ret['result'] = False
state_post = state(name, path=path)
if state_pre != state_post:
changes.append({'state': {'old': state_pre, 'new': state_post}})
if ret.get('result', True):
ret['comment'] = ('Container \'{0}\' successfully initialized'
.format(name))
ret['result'] = True
if changes:
ret['changes'] = changes_dict
return ret
def images(dist=None):
'''
.. versionadded:: 2015.5.0
List the available images for LXC's ``download`` template.
dist : None
Filter results to a single Linux distribution
CLI Examples:
.. code-block:: bash
salt myminion lxc.images
salt myminion lxc.images dist=centos
'''
out = __salt__['cmd.run_stdout'](
'lxc-create -n __imgcheck -t download -- --list',
ignore_retcode=True
)
if 'DIST' not in out:
raise CommandExecutionError(
'Unable to run the \'download\' template script. Is it installed?'
)
ret = {}
passed_header = False
for line in out.splitlines():
try:
distro, release, arch, variant, build_time = line.split()
except ValueError:
continue
if not passed_header:
if distro == 'DIST':
passed_header = True
continue
dist_list = ret.setdefault(distro, [])
dist_list.append({
'release': release,
'arch': arch,
'variant': variant,
'build_time': build_time,
})
if dist is not None:
return dict([(dist, ret.get(dist, []))])
return ret
def templates():
'''
.. versionadded:: 2015.5.0
List the available LXC template scripts installed on the minion
CLI Examples:
.. code-block:: bash
salt myminion lxc.templates
'''
try:
template_scripts = os.listdir('/usr/share/lxc/templates')
except OSError:
return []
else:
return [x[4:] for x in template_scripts if x.startswith('lxc-')]
def _after_ignition_network_profile(cmd,
ret,
name,
network_profile,
path,
nic_opts):
_clear_context()
if ret['retcode'] == 0 and exists(name, path=path):
if network_profile:
network_changes = apply_network_profile(name,
network_profile,
path=path,
nic_opts=nic_opts)
if network_changes:
log.info(
'Network changes from applying network profile \'%s\' '
'to newly-created container \'%s\':\n%s',
network_profile, name, network_changes
)
c_state = state(name, path=path)
return {'result': True,
'state': {'old': None, 'new': c_state}}
else:
if exists(name, path=path):
# destroy the container if it was partially created
cmd = 'lxc-destroy'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0}'.format(name)
__salt__['cmd.retcode'](cmd, python_shell=False)
raise CommandExecutionError(
'Container could not be created with cmd \'{0}\': {1}'
.format(cmd, ret['stderr'])
)
def create(name,
config=None,
profile=None,
network_profile=None,
nic_opts=None,
**kwargs):
'''
Create a new container.
name
Name of the container
config
The config file to use for the container. Defaults to system-wide
config (usually in /etc/lxc/lxc.conf).
profile
Profile to use in container creation (see
:mod:`lxc.get_container_profile
<salt.modules.lxc.get_container_profile>`). Values in a profile will be
overridden by the **Container Creation Arguments** listed below.
network_profile
Network profile to use for container
.. versionadded:: 2015.5.0
**Container Creation Arguments**
template
The template to use. For example, ``ubuntu`` or ``fedora``.
For a full list of available templates, check out
the :mod:`lxc.templates <salt.modules.lxc.templates>` function.
Conflicts with the ``image`` argument.
.. note::
The ``download`` template requires the following three parameters
to be defined in ``options``:
* **dist** - The name of the distribution
* **release** - Release name/version
* **arch** - Architecture of the container
The available images can be listed using the :mod:`lxc.images
<salt.modules.lxc.images>` function.
options
Template-specific options to pass to the lxc-create command. These
correspond to the long options (ones beginning with two dashes) that
the template script accepts. For example:
.. code-block:: bash
options='{"dist": "centos", "release": "6", "arch": "amd64"}'
For available template options, refer to the lxc template scripts
which are ususally located under ``/usr/share/lxc/templates``,
or run ``lxc-create -t <template> -h``.
image
A tar archive to use as the rootfs for the container. Conflicts with
the ``template`` argument.
backing
The type of storage to use. Set to ``lvm`` to use an LVM group.
Defaults to filesystem within /var/lib/lxc.
fstype
Filesystem type to use on LVM logical volume
size : 1G
Size of the volume to create. Only applicable if ``backing=lvm``.
vgname : lxc
Name of the LVM volume group in which to create the volume for this
container. Only applicable if ``backing=lvm``.
lvname
Name of the LVM logical volume in which to create the volume for this
container. Only applicable if ``backing=lvm``.
thinpool
Name of a pool volume that will be used for thin-provisioning this
container. Only applicable if ``backing=lvm``.
nic_opts
give extra opts overriding network profile values
path
parent path for the container creation (default: /var/lib/lxc)
zfsroot
Name of the ZFS root in which to create the volume for this container.
Only applicable if ``backing=zfs``. (default: tank/lxc)
.. versionadded:: 2015.8.0
'''
# Required params for 'download' template
download_template_deps = ('dist', 'release', 'arch')
cmd = 'lxc-create -n {0}'.format(name)
profile = get_container_profile(copy.deepcopy(profile))
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, None)
profile_match = profile.pop(key, default)
# Return the profile match if the the kwarg match was None, as the
# lxc.present state will pass these kwargs set to None by default.
if kw_overrides_match is None:
return profile_match
return kw_overrides_match
path = select('path')
if exists(name, path=path):
raise CommandExecutionError(
'Container \'{0}\' already exists'.format(name)
)
tvg = select('vgname')
vgname = tvg if tvg else __salt__['config.get']('lxc.vgname')
# The 'template' and 'image' params conflict
template = select('template')
image = select('image')
if template and image:
raise SaltInvocationError(
'Only one of \'template\' and \'image\' is permitted'
)
elif not any((template, image, profile)):
raise SaltInvocationError(
'At least one of \'template\', \'image\', and \'profile\' is '
'required'
)
options = select('options') or {}
backing = select('backing')
if vgname and not backing:
backing = 'lvm'
lvname = select('lvname')
thinpool = select('thinpool')
fstype = select('fstype')
size = select('size', '1G')
zfsroot = select('zfsroot')
if backing in ('dir', 'overlayfs', 'btrfs', 'zfs'):
fstype = None
size = None
# some backends won't support some parameters
if backing in ('aufs', 'dir', 'overlayfs', 'btrfs'):
lvname = vgname = thinpool = None
if image:
img_tar = __salt__['cp.cache_file'](image)
template = os.path.join(
os.path.dirname(salt.__file__),
'templates',
'lxc',
'salt_tarball')
options['imgtar'] = img_tar
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
if not os.path.exists(path):
os.makedirs(path)
if config:
cmd += ' -f {0}'.format(config)
if template:
cmd += ' -t {0}'.format(template)
if backing:
backing = backing.lower()
cmd += ' -B {0}'.format(backing)
if backing in ('zfs',):
if zfsroot:
cmd += ' --zfsroot {0}'.format(zfsroot)
if backing in ('lvm',):
if lvname:
cmd += ' --lvname {0}'.format(lvname)
if vgname:
cmd += ' --vgname {0}'.format(vgname)
if thinpool:
cmd += ' --thinpool {0}'.format(thinpool)
if backing not in ('dir', 'overlayfs'):
if fstype:
cmd += ' --fstype {0}'.format(fstype)
if size:
cmd += ' --fssize {0}'.format(size)
if options:
if template == 'download':
missing_deps = [x for x in download_template_deps
if x not in options]
if missing_deps:
raise SaltInvocationError(
'Missing params in \'options\' dict: {0}'
.format(', '.join(missing_deps))
)
cmd += ' --'
for key, val in six.iteritems(options):
cmd += ' --{0} {1}'.format(key, val)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
# please do not merge extra conflicting stuff
# inside those two line (ret =, return)
return _after_ignition_network_profile(cmd,
ret,
name,
network_profile,
path,
nic_opts)
def clone(name,
orig,
profile=None,
network_profile=None,
nic_opts=None,
**kwargs):
'''
Create a new container as a clone of another container
name
Name of the container
orig
Name of the original container to be cloned
profile
Profile to use in container cloning (see
:mod:`lxc.get_container_profile
<salt.modules.lxc.get_container_profile>`). Values in a profile will be
overridden by the **Container Cloning Arguments** listed below.
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
**Container Cloning Arguments**
snapshot
Use Copy On Write snapshots (LVM)
size : 1G
Size of the volume to create. Only applicable if ``backing=lvm``.
backing
The type of storage to use. Set to ``lvm`` to use an LVM group.
Defaults to filesystem within /var/lib/lxc.
network_profile
Network profile to use for container
.. versionadded:: 2015.8.0
nic_opts
give extra opts overriding network profile values
.. versionadded:: 2015.8.0
CLI Examples:
.. code-block:: bash
salt '*' lxc.clone myclone orig=orig_container
salt '*' lxc.clone myclone orig=orig_container snapshot=True
'''
profile = get_container_profile(copy.deepcopy(profile))
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, None)
profile_match = profile.pop(key, default)
# let kwarg overrides be the preferred choice
if kw_overrides_match is None:
return profile_match
return kw_overrides_match
path = select('path')
if exists(name, path=path):
raise CommandExecutionError(
'Container \'{0}\' already exists'.format(name)
)
_ensure_exists(orig, path=path)
if state(orig, path=path) != 'stopped':
raise CommandExecutionError(
'Container \'{0}\' must be stopped to be cloned'.format(orig)
)
backing = select('backing')
snapshot = select('snapshot')
if backing in ('dir',):
snapshot = False
if not snapshot:
snapshot = ''
else:
snapshot = '-s'
size = select('size', '1G')
if backing in ('dir', 'overlayfs', 'btrfs'):
size = None
# LXC commands and options changed in 2.0 - CF issue #34086 for details
if _LooseVersion(version()) >= _LooseVersion('2.0'):
# https://linuxcontainers.org/lxc/manpages//man1/lxc-copy.1.html
cmd = 'lxc-copy'
cmd += ' {0} -n {1} -N {2}'.format(snapshot, orig, name)
else:
# https://linuxcontainers.org/lxc/manpages//man1/lxc-clone.1.html
cmd = 'lxc-clone'
cmd += ' {0} -o {1} -n {2}'.format(snapshot, orig, name)
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
if not os.path.exists(path):
os.makedirs(path)
if backing:
backing = backing.lower()
cmd += ' -B {0}'.format(backing)
if backing not in ('dir', 'overlayfs'):
if size:
cmd += ' -L {0}'.format(size)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
# please do not merge extra conflicting stuff
# inside those two line (ret =, return)
return _after_ignition_network_profile(cmd,
ret,
name,
network_profile,
path,
nic_opts)
def ls_(active=None, cache=True, path=None):
'''
Return a list of the containers available on the minion
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
active
If ``True``, return only active (i.e. running) containers
.. versionadded:: 2015.5.0
CLI Example:
.. code-block:: bash
salt '*' lxc.ls
salt '*' lxc.ls active=True
'''
contextvar = 'lxc.ls{0}'.format(path)
if active:
contextvar += '.active'
if cache and (contextvar in __context__):
return __context__[contextvar]
else:
ret = []
cmd = 'lxc-ls'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
if active:
cmd += ' --active'
output = __salt__['cmd.run_stdout'](cmd, python_shell=False)
for line in output.splitlines():
ret.extend(line.split())
__context__[contextvar] = ret
return ret
def list_(extra=False, limit=None, path=None):
'''
List containers classified by state
extra
Also get per-container specific info. This will change the return data.
Instead of returning a list of containers, a dictionary of containers
and each container's output from :mod:`lxc.info
<salt.modules.lxc.info>`.
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
limit
Return output matching a specific state (**frozen**, **running**, or
**stopped**).
.. versionadded:: 2015.5.0
CLI Examples:
.. code-block:: bash
salt '*' lxc.list
salt '*' lxc.list extra=True
salt '*' lxc.list limit=running
'''
ctnrs = ls_(path=path)
if extra:
stopped = {}
frozen = {}
running = {}
else:
stopped = []
frozen = []
running = []
ret = {'running': running,
'stopped': stopped,
'frozen': frozen}
for container in ctnrs:
cmd = 'lxc-info'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0}'.format(container)
c_info = __salt__['cmd.run'](
cmd,
python_shell=False,
output_loglevel='debug'
)
c_state = None
for line in c_info.splitlines():
stat = line.split(':')
if stat[0] in ('State', 'state'):
c_state = stat[1].strip()
break
if not c_state or (limit is not None and c_state.lower() != limit):
continue
if extra:
infos = info(container, path=path)
method = 'update'
value = {container: infos}
else:
method = 'append'
value = container
if c_state == 'STOPPED':
getattr(stopped, method)(value)
continue
if c_state == 'FROZEN':
getattr(frozen, method)(value)
continue
if c_state == 'RUNNING':
getattr(running, method)(value)
continue
if limit is not None:
return ret.get(limit, {} if extra else [])
return ret
def _change_state(cmd,
name,
expected,
stdin=_marker,
stdout=_marker,
stderr=_marker,
with_communicate=_marker,
use_vt=_marker,
path=None):
pre = state(name, path=path)
if pre == expected:
return {'result': True,
'state': {'old': expected, 'new': expected},
'comment': 'Container \'{0}\' already {1}'
.format(name, expected)}
if cmd == 'lxc-destroy':
# Kill the container first
scmd = 'lxc-stop'
if path:
scmd += ' -P {0}'.format(pipes.quote(path))
scmd += ' -k -n {0}'.format(name)
__salt__['cmd.run'](scmd,
python_shell=False)
if path and ' -P ' not in cmd:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0}'.format(name)
# certain lxc commands need to be taken with care (lxc-start)
# as te command itself mess with double forks; we must not
# communicate with it, but just wait for the exit status
pkwargs = {'python_shell': False,
'redirect_stderr': True,
'with_communicate': with_communicate,
'use_vt': use_vt,
'stdin': stdin,
'stdout': stdout}
for i in [a for a in pkwargs]:
val = pkwargs[i]
if val is _marker:
pkwargs.pop(i, None)
_cmdout = __salt__['cmd.run_all'](cmd, **pkwargs)
if _cmdout['retcode'] != 0:
raise CommandExecutionError(
'Error changing state for container \'{0}\' using command '
'\'{1}\': {2}'.format(name, cmd, _cmdout['stdout'])
)
if expected is not None:
# some commands do not wait, so we will
rcmd = 'lxc-wait'
if path:
rcmd += ' -P {0}'.format(pipes.quote(path))
rcmd += ' -n {0} -s {1}'.format(name, expected.upper())
__salt__['cmd.run'](rcmd, python_shell=False, timeout=30)
_clear_context()
post = state(name, path=path)
ret = {'result': post == expected,
'state': {'old': pre, 'new': post}}
return ret
def _ensure_exists(name, path=None):
'''
Raise an exception if the container does not exist
'''
if not exists(name, path=path):
raise CommandExecutionError(
'Container \'{0}\' does not exist'.format(name)
)
def _ensure_running(name, no_start=False, path=None):
'''
If the container is not currently running, start it. This function returns
the state that the container was in before changing
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
'''
_ensure_exists(name, path=path)
pre = state(name, path=path)
if pre == 'running':
# This will be a no-op but running the function will give us a pretty
# return dict.
return start(name, path=path)
elif pre == 'stopped':
if no_start:
raise CommandExecutionError(
'Container \'{0}\' is not running'.format(name)
)
return start(name, path=path)
elif pre == 'frozen':
if no_start:
raise CommandExecutionError(
'Container \'{0}\' is not running'.format(name)
)
return unfreeze(name, path=path)
def restart(name, path=None, lxc_config=None, force=False):
'''
.. versionadded:: 2015.5.0
Restart the named container. If the container was not running, the
container will merely be started.
name
The name of the container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
lxc_config
path to a lxc config file
config file will be guessed from container name otherwise
.. versionadded:: 2015.8.0
force : False
If ``True``, the container will be force-stopped instead of gracefully
shut down
CLI Example:
.. code-block:: bash
salt myminion lxc.restart name
'''
_ensure_exists(name, path=path)
orig_state = state(name, path=path)
if orig_state != 'stopped':
stop(name, kill=force, path=path)
ret = start(name, path=path, lxc_config=lxc_config)
ret['state']['old'] = orig_state
if orig_state != 'stopped':
ret['restarted'] = True
return ret
def start(name, **kwargs):
'''
Start the named container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
lxc_config
path to a lxc config file
config file will be guessed from container name otherwise
.. versionadded:: 2015.8.0
use_vt
run the command through VT
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.start name
'''
path = kwargs.get('path', None)
cpath = get_root_path(path)
lxc_config = kwargs.get('lxc_config', None)
cmd = 'lxc-start'
if not lxc_config:
lxc_config = os.path.join(cpath, name, 'config')
# we try to start, even without config, if global opts are there
if os.path.exists(lxc_config):
cmd += ' -f {0}'.format(pipes.quote(lxc_config))
cmd += ' -d'
_ensure_exists(name, path=path)
if state(name, path=path) == 'frozen':
raise CommandExecutionError(
'Container \'{0}\' is frozen, use lxc.unfreeze'.format(name)
)
# lxc-start daemonize itself violently, we must not communicate with it
use_vt = kwargs.get('use_vt', None)
with_communicate = kwargs.get('with_communicate', False)
return _change_state(cmd, name, 'running',
stdout=None,
stderr=None,
stdin=None,
with_communicate=with_communicate,
path=path,
use_vt=use_vt)
def stop(name, kill=False, path=None, use_vt=None):
'''
Stop the named container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
kill: False
Do not wait for the container to stop, kill all tasks in the container.
Older LXC versions will stop containers like this irrespective of this
argument.
.. versionchanged:: 2015.5.0
Default value changed to ``False``
use_vt
run the command through VT
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.stop name
'''
_ensure_exists(name, path=path)
orig_state = state(name, path=path)
if orig_state == 'frozen' and not kill:
# Gracefully stopping a frozen container is slower than unfreezing and
# then stopping it (at least in my testing), so if we're not
# force-stopping the container, unfreeze it first.
unfreeze(name, path=path)
cmd = 'lxc-stop'
if kill:
cmd += ' -k'
ret = _change_state(cmd, name, 'stopped', use_vt=use_vt, path=path)
ret['state']['old'] = orig_state
return ret
def freeze(name, **kwargs):
'''
Freeze the named container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
start : False
If ``True`` and the container is stopped, the container will be started
before attempting to freeze.
.. versionadded:: 2015.5.0
use_vt
run the command through VT
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.freeze name
'''
use_vt = kwargs.get('use_vt', None)
path = kwargs.get('path', None)
_ensure_exists(name, path=path)
orig_state = state(name, path=path)
start_ = kwargs.get('start', False)
if orig_state == 'stopped':
if not start_:
raise CommandExecutionError(
'Container \'{0}\' is stopped'.format(name)
)
start(name, path=path)
cmd = 'lxc-freeze'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
ret = _change_state(cmd, name, 'frozen', use_vt=use_vt, path=path)
if orig_state == 'stopped' and start_:
ret['state']['old'] = orig_state
ret['started'] = True
ret['state']['new'] = state(name, path=path)
return ret
def unfreeze(name, path=None, use_vt=None):
'''
Unfreeze the named container.
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
use_vt
run the command through VT
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.unfreeze name
'''
_ensure_exists(name, path=path)
if state(name, path=path) == 'stopped':
raise CommandExecutionError(
'Container \'{0}\' is stopped'.format(name)
)
cmd = 'lxc-unfreeze'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
return _change_state(cmd, name, 'running', path=path, use_vt=use_vt)
def destroy(name, stop=False, path=None):
'''
Destroy the named container.
.. warning::
Destroys all data associated with the container.
path
path to the container parent directory (default: /var/lib/lxc)
.. versionadded:: 2015.8.0
stop : False
If ``True``, the container will be destroyed even if it is
running/frozen.
.. versionchanged:: 2015.5.0
Default value changed to ``False``. This more closely matches the
behavior of ``lxc-destroy(1)``, and also makes it less likely that
an accidental command will destroy a running container that was
being used for important things.
CLI Examples:
.. code-block:: bash
salt '*' lxc.destroy foo
salt '*' lxc.destroy foo stop=True
'''
_ensure_exists(name, path=path)
if not stop and state(name, path=path) != 'stopped':
raise CommandExecutionError(
'Container \'{0}\' is not stopped'.format(name)
)
return _change_state('lxc-destroy', name, None, path=path)
# Compatibility between LXC and nspawn
remove = salt.utils.functools.alias_function(destroy, 'remove')
def exists(name, path=None):
'''
Returns whether the named container exists.
path
path to the container parent directory (default: /var/lib/lxc)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.exists name
'''
_exists = name in ls_(path=path)
# container may be just created but we did cached earlier the
# lxc-ls results
if not _exists:
_exists = name in ls_(cache=False, path=path)
return _exists
def state(name, path=None):
'''
Returns the state of a container.
path
path to the container parent directory (default: /var/lib/lxc)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.state name
'''
# Don't use _ensure_exists() here, it will mess with _change_state()
cachekey = 'lxc.state.{0}{1}'.format(name, path)
try:
return __context__[cachekey]
except KeyError:
if not exists(name, path=path):
__context__[cachekey] = None
else:
cmd = 'lxc-info'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0}'.format(name)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
if ret['retcode'] != 0:
_clear_context()
raise CommandExecutionError(
'Unable to get state of container \'{0}\''.format(name)
)
c_infos = ret['stdout'].splitlines()
c_state = None
for c_info in c_infos:
stat = c_info.split(':')
if stat[0].lower() == 'state':
c_state = stat[1].strip().lower()
break
__context__[cachekey] = c_state
return __context__[cachekey]
def get_parameter(name, parameter, path=None):
'''
Returns the value of a cgroup parameter for a container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.get_parameter container_name memory.limit_in_bytes
'''
_ensure_exists(name, path=path)
cmd = 'lxc-cgroup'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0} {1}'.format(name, parameter)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
if ret['retcode'] != 0:
raise CommandExecutionError(
'Unable to retrieve value for \'{0}\''.format(parameter)
)
return ret['stdout'].strip()
def set_parameter(name, parameter, value, path=None):
'''
Set the value of a cgroup parameter for a container.
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.set_parameter name parameter value
'''
if not exists(name, path=path):
return None
cmd = 'lxc-cgroup'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0} {1} {2}'.format(name, parameter, value)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
if ret['retcode'] != 0:
return False
else:
return True
def info(name, path=None):
'''
Returns information about a container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.info name
'''
cachekey = 'lxc.info.{0}{1}'.format(name, path)
try:
return __context__[cachekey]
except KeyError:
_ensure_exists(name, path=path)
cpath = get_root_path(path)
try:
conf_file = os.path.join(cpath, name, 'config')
except AttributeError:
conf_file = os.path.join(cpath, six.text_type(name), 'config')
if not os.path.isfile(conf_file):
raise CommandExecutionError(
'LXC config file {0} does not exist'.format(conf_file)
)
ret = {}
config = []
with salt.utils.files.fopen(conf_file) as fp_:
for line in fp_:
line = salt.utils.stringutils.to_unicode(line)
comps = [x.strip() for x in
line.split('#', 1)[0].strip().split('=', 1)]
if len(comps) == 2:
config.append(tuple(comps))
ifaces = []
current = None
for key, val in config:
if key == 'lxc.network.type':
current = {'type': val}
ifaces.append(current)
elif not current:
continue
elif key.startswith('lxc.network.'):
current[key.replace('lxc.network.', '', 1)] = val
if ifaces:
ret['nics'] = ifaces
ret['rootfs'] = next(
(x[1] for x in config if x[0] == 'lxc.rootfs'),
None
)
ret['state'] = state(name, path=path)
ret['ips'] = []
ret['public_ips'] = []
ret['private_ips'] = []
ret['public_ipv4_ips'] = []
ret['public_ipv6_ips'] = []
ret['private_ipv4_ips'] = []
ret['private_ipv6_ips'] = []
ret['ipv4_ips'] = []
ret['ipv6_ips'] = []
ret['size'] = None
ret['config'] = conf_file
if ret['state'] == 'running':
try:
limit = int(get_parameter(name, 'memory.limit_in_bytes'))
except (CommandExecutionError, TypeError, ValueError):
limit = 0
try:
usage = int(get_parameter(name, 'memory.usage_in_bytes'))
except (CommandExecutionError, TypeError, ValueError):
usage = 0
free = limit - usage
ret['memory_limit'] = limit
ret['memory_free'] = free
size = run_stdout(name, 'df /', path=path, python_shell=False)
# The size is the 2nd column of the last line
ret['size'] = size.splitlines()[-1].split()[1]
# First try iproute2
ip_cmd = run_all(
name, 'ip link show', path=path, python_shell=False)
if ip_cmd['retcode'] == 0:
ip_data = ip_cmd['stdout']
ip_cmd = run_all(
name, 'ip addr show', path=path, python_shell=False)
ip_data += '\n' + ip_cmd['stdout']
ip_data = salt.utils.network._interfaces_ip(ip_data)
else:
# That didn't work, try ifconfig
ip_cmd = run_all(
name, 'ifconfig', path=path, python_shell=False)
if ip_cmd['retcode'] == 0:
ip_data = \
salt.utils.network._interfaces_ifconfig(
ip_cmd['stdout'])
else:
# Neither was successful, give up
log.warning(
'Unable to run ip or ifconfig in container \'%s\'', name
)
ip_data = {}
ret['ipv4_ips'] = salt.utils.network.ip_addrs(
include_loopback=True,
interface_data=ip_data
)
ret['ipv6_ips'] = salt.utils.network.ip_addrs6(
include_loopback=True,
interface_data=ip_data
)
ret['ips'] = ret['ipv4_ips'] + ret['ipv6_ips']
for address in ret['ipv4_ips']:
if address == '127.0.0.1':
ret['private_ips'].append(address)
ret['private_ipv4_ips'].append(address)
elif salt.utils.cloud.is_public_ip(address):
ret['public_ips'].append(address)
ret['public_ipv4_ips'].append(address)
else:
ret['private_ips'].append(address)
ret['private_ipv4_ips'].append(address)
for address in ret['ipv6_ips']:
if address == '::1' or address.startswith('fe80'):
ret['private_ips'].append(address)
ret['private_ipv6_ips'].append(address)
else:
ret['public_ips'].append(address)
ret['public_ipv6_ips'].append(address)
for key in [x for x in ret if x == 'ips' or x.endswith('ips')]:
ret[key].sort(key=_ip_sort)
__context__[cachekey] = ret
return __context__[cachekey]
def set_password(name, users, password, encrypted=True, path=None):
'''
.. versionchanged:: 2015.5.0
Function renamed from ``set_pass`` to ``set_password``. Additionally,
this function now supports (and defaults to using) a password hash
instead of a plaintext password.
Set the password of one or more system users inside containers
users
Comma-separated list (or python list) of users to change password
password
Password to set for the specified user(s)
encrypted : True
If true, ``password`` must be a password hash. Set to ``False`` to set
a plaintext password (not recommended).
.. versionadded:: 2015.5.0
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.set_pass container-name root '$6$uJ2uAyLU$KoI67t8As/0fXtJOPcHKGXmUpcoYUcVR2K6x93walnShTCQvjRwq25yIkiCBOqgbfdKQSFnAo28/ek6716vEV1'
salt '*' lxc.set_pass container-name root foo encrypted=False
'''
def _bad_user_input():
raise SaltInvocationError('Invalid input for \'users\' parameter')
if not isinstance(users, list):
try:
users = users.split(',')
except AttributeError:
_bad_user_input()
if not users:
_bad_user_input()
failed_users = []
for user in users:
result = retcode(name,
'chpasswd{0}'.format(' -e' if encrypted else ''),
stdin=':'.join((user, password)),
python_shell=False,
path=path,
chroot_fallback=True,
output_loglevel='quiet')
if result != 0:
failed_users.append(user)
if failed_users:
raise CommandExecutionError(
'Password change failed for the following user(s): {0}'
.format(', '.join(failed_users))
)
return True
set_pass = salt.utils.functools.alias_function(set_password, 'set_pass')
def update_lxc_conf(name, lxc_conf, lxc_conf_unset, path=None):
'''
Edit LXC configuration options
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.update_lxc_conf ubuntu \\
lxc_conf="[{'network.ipv4.ip':'10.0.3.5'}]" \\
lxc_conf_unset="['lxc.utsname']"
'''
_ensure_exists(name, path=path)
cpath = get_root_path(path)
lxc_conf_p = os.path.join(cpath, name, 'config')
if not os.path.exists(lxc_conf_p):
raise SaltInvocationError(
'Configuration file {0} does not exist'.format(lxc_conf_p)
)
changes = {'edited': [], 'added': [], 'removed': []}
ret = {'changes': changes, 'result': True, 'comment': ''}
# do not use salt.utils.files.fopen !
with salt.utils.files.fopen(lxc_conf_p, 'r') as fic:
filtered_lxc_conf = []
for row in lxc_conf:
if not row:
continue
for conf in row:
filtered_lxc_conf.append((conf.strip(),
row[conf].strip()))
ret['comment'] = 'lxc.conf is up to date'
lines = []
orig_config = salt.utils.stringutils.to_unicode(fic.read())
for line in orig_config.splitlines():
if line.startswith('#') or not line.strip():
lines.append([line, ''])
else:
line = line.split('=')
index = line.pop(0)
val = (index.strip(), '='.join(line).strip())
if val not in lines:
lines.append(val)
for key, item in filtered_lxc_conf:
matched = False
for idx, line in enumerate(lines[:]):
if line[0] == key:
matched = True
lines[idx] = (key, item)
if '='.join(line[1:]).strip() != item.strip():
changes['edited'].append(
({line[0]: line[1:]}, {key: item}))
break
if not matched:
if (key, item) not in lines:
lines.append((key, item))
changes['added'].append({key: item})
dest_lxc_conf = []
# filter unset
if lxc_conf_unset:
for line in lines:
for opt in lxc_conf_unset:
if (
not line[0].startswith(opt) and
line not in dest_lxc_conf
):
dest_lxc_conf.append(line)
else:
changes['removed'].append(opt)
else:
dest_lxc_conf = lines
conf = ''
for key, val in dest_lxc_conf:
if not val:
conf += '{0}\n'.format(key)
else:
conf += '{0} = {1}\n'.format(key.strip(), val.strip())
conf_changed = conf != orig_config
chrono = datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S')
if conf_changed:
# DO NOT USE salt.utils.files.fopen here, i got (kiorky)
# problems with lxc configs which were wiped !
with salt.utils.files.fopen('{0}.{1}'.format(lxc_conf_p, chrono), 'w') as wfic:
wfic.write(salt.utils.stringutils.to_str(conf))
with salt.utils.files.fopen(lxc_conf_p, 'w') as wfic:
wfic.write(salt.utils.stringutils.to_str(conf))
ret['comment'] = 'Updated'
ret['result'] = True
if not any(changes[x] for x in changes):
# Ensure an empty changes dict if nothing was modified
ret['changes'] = {}
return ret
def set_dns(name, dnsservers=None, searchdomains=None, path=None):
'''
.. versionchanged:: 2015.5.0
The ``dnsservers`` and ``searchdomains`` parameters can now be passed
as a comma-separated list.
Update /etc/resolv.confo
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.set_dns ubuntu "['8.8.8.8', '4.4.4.4']"
'''
if dnsservers is None:
dnsservers = ['8.8.8.8', '4.4.4.4']
elif not isinstance(dnsservers, list):
try:
dnsservers = dnsservers.split(',')
except AttributeError:
raise SaltInvocationError(
'Invalid input for \'dnsservers\' parameter'
)
if searchdomains is None:
searchdomains = []
elif not isinstance(searchdomains, list):
try:
searchdomains = searchdomains.split(',')
except AttributeError:
raise SaltInvocationError(
'Invalid input for \'searchdomains\' parameter'
)
dns = ['nameserver {0}'.format(x) for x in dnsservers]
dns.extend(['search {0}'.format(x) for x in searchdomains])
dns = '\n'.join(dns) + '\n'
# we may be using resolvconf in the container
# We need to handle that case with care:
# - we create the resolv.conf runtime directory (the
# linked directory) as anyway it will be shadowed when the real
# runned tmpfs mountpoint will be mounted.
# ( /etc/resolv.conf -> ../run/resolvconf/resolv.conf)
# Indeed, it can save us in any other case (running, eg, in a
# bare chroot when repairing or preparing the container for
# operation.
# - We also teach resolvconf to use the aforementioned dns.
# - We finally also set /etc/resolv.conf in all cases
rstr = __salt__['test.random_hash']()
# no tmp here, apparmor won't let us execute !
script = '/sbin/{0}_dns.sh'.format(rstr)
DNS_SCRIPT = "\n".join([
# 'set -x',
'#!/usr/bin/env bash',
'if [ -h /etc/resolv.conf ];then',
' if [ "x$(readlink /etc/resolv.conf)"'
' = "x../run/resolvconf/resolv.conf" ];then',
' if [ ! -d /run/resolvconf/ ];then',
' mkdir -p /run/resolvconf',
' fi',
' cat > /etc/resolvconf/resolv.conf.d/head <<EOF',
dns,
'EOF',
'',
' fi',
'fi',
'cat > /etc/resolv.conf <<EOF',
dns,
'EOF',
''])
result = run_all(
name, 'tee {0}'.format(script), path=path,
stdin=DNS_SCRIPT, python_shell=True)
if result['retcode'] == 0:
result = run_all(
name, 'sh -c "chmod +x {0};{0}"'.format(script),
path=path, python_shell=True)
# blindly delete the setter file
run_all(name,
'sh -c \'if [ -f "{0}" ];then rm -f "{0}";fi\''.format(script),
path=path, python_shell=True)
if result['retcode'] != 0:
error = ('Unable to write to /etc/resolv.conf in container \'{0}\''
.format(name))
if result['stderr']:
error += ': {0}'.format(result['stderr'])
raise CommandExecutionError(error)
return True
def running_systemd(name, cache=True, path=None):
'''
Determine if systemD is running
path
path to the container parent
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.running_systemd ubuntu
'''
k = 'lxc.systemd.test.{0}{1}'.format(name, path)
ret = __context__.get(k, None)
if ret is None or not cache:
rstr = __salt__['test.random_hash']()
# no tmp here, apparmor won't let us execute !
script = '/sbin/{0}_testsystemd.sh'.format(rstr)
# ubuntu already had since trusty some bits of systemd but was
# still using upstart ...
# we need to be a bit more careful that just testing that systemd
# is present
_script = textwrap.dedent(
'''\
#!/usr/bin/env bash
set -x
if ! command -v systemctl 1>/dev/null 2>/dev/null;then exit 2;fi
for i in \\
/run/systemd/journal/dev-log\\
/run/systemd/journal/flushed\\
/run/systemd/journal/kernel-seqnum\\
/run/systemd/journal/socket\\
/run/systemd/journal/stdout\\
/var/run/systemd/journal/dev-log\\
/var/run/systemd/journal/flushed\\
/var/run/systemd/journal/kernel-seqnum\\
/var/run/systemd/journal/socket\\
/var/run/systemd/journal/stdout\\
;do\\
if test -e ${i};then exit 0;fi
done
if test -d /var/systemd/system;then exit 0;fi
exit 2
''')
result = run_all(
name, 'tee {0}'.format(script), path=path,
stdin=_script, python_shell=True)
if result['retcode'] == 0:
result = run_all(name,
'sh -c "chmod +x {0};{0}"'''.format(script),
path=path,
python_shell=True)
else:
raise CommandExecutionError(
'lxc {0} failed to copy initd tester'.format(name))
run_all(name,
'sh -c \'if [ -f "{0}" ];then rm -f "{0}";fi\''
''.format(script),
path=path,
ignore_retcode=True,
python_shell=True)
if result['retcode'] != 0:
error = ('Unable to determine if the container \'{0}\''
' was running systemd, assmuming it is not.'
''.format(name))
if result['stderr']:
error += ': {0}'.format(result['stderr'])
# only cache result if we got a known exit code
if result['retcode'] in (0, 2):
__context__[k] = ret = not result['retcode']
return ret
def systemd_running_state(name, path=None):
'''
Get the operational state of a systemd based container
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.systemd_running_state ubuntu
'''
try:
ret = run_all(name,
'systemctl is-system-running',
path=path,
ignore_retcode=True)['stdout']
except CommandExecutionError:
ret = ''
return ret
def test_sd_started_state(name, path=None):
'''
Test if a systemd container is fully started
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.test_sd_started_state ubuntu
'''
qstate = systemd_running_state(name, path=path)
if qstate in ('initializing', 'starting'):
return False
elif qstate == '':
return None
else:
return True
def test_bare_started_state(name, path=None):
'''
Test if a non systemd container is fully started
For now, it consists only to test if the container is attachable
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.test_bare_started_state ubuntu
'''
try:
ret = run_all(
name, 'ls', path=path, ignore_retcode=True
)['retcode'] == 0
except (CommandExecutionError,):
ret = None
return ret
def wait_started(name, path=None, timeout=300):
'''
Check that the system has fully inited
This is actually very important for systemD based containers
see https://github.com/saltstack/salt/issues/23847
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.wait_started ubuntu
'''
if not exists(name, path=path):
raise CommandExecutionError(
'Container {0} does does exists'.format(name))
if not state(name, path=path) == 'running':
raise CommandExecutionError(
'Container {0} is not running'.format(name))
ret = False
if running_systemd(name, path=path):
test_started = test_sd_started_state
logger = log.error
else:
test_started = test_bare_started_state
logger = log.debug
now = time.time()
expire = now + timeout
now = time.time()
started = test_started(name, path=path)
while time.time() < expire and not started:
time.sleep(0.3)
started = test_started(name, path=path)
if started is None:
logger(
'Assuming %s is started, although we failed to detect that'
' is fully started correctly', name)
ret = True
else:
ret = started
return ret
def _needs_install(name, path=None):
ret = 0
has_minion = retcode(name,
'which salt-minion',
path=path,
ignore_retcode=True)
# we assume that installing is when no minion is running
# but testing the executable presence is not enougth for custom
# installs where the bootstrap can do much more than installing
# the bare salt binaries.
if has_minion:
processes = run_stdout(name, "ps aux", path=path)
if 'salt-minion' not in processes:
ret = 1
else:
retcode(name, 'salt-call --local service.stop salt-minion')
else:
ret = 1
return ret
def bootstrap(name,
config=None,
approve_key=True,
install=True,
pub_key=None,
priv_key=None,
bootstrap_url=None,
force_install=False,
unconditional_install=False,
path=None,
bootstrap_delay=None,
bootstrap_args=None,
bootstrap_shell=None):
'''
Install and configure salt in a container.
config
Minion configuration options. By default, the ``master`` option is set
to the target host's master.
approve_key
Request a pre-approval of the generated minion key. Requires
that the salt-master be configured to either auto-accept all keys or
expect a signing request from the target host. Default: ``True``
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
pub_key
Explicit public key to pressed the minion with (optional).
This can be either a filepath or a string representing the key
priv_key
Explicit private key to pressed the minion with (optional).
This can be either a filepath or a string representing the key
bootstrap_delay
Delay in seconds between end of container creation and bootstrapping.
Useful when waiting for container to obtain a DHCP lease.
.. versionadded:: 2015.5.0
bootstrap_url
url, content or filepath to the salt bootstrap script
bootstrap_args
salt bootstrap script arguments
bootstrap_shell
shell to execute the script into
install
Whether to attempt a full installation of salt-minion if needed.
force_install
Force installation even if salt-minion is detected,
this is the way to run vendor bootstrap scripts even
if a salt minion is already present in the container
unconditional_install
Run the script even if the container seems seeded
CLI Examples:
.. code-block:: bash
salt 'minion' lxc.bootstrap container_name [config=config_data] \\
[approve_key=(True|False)] [install=(True|False)]
'''
wait_started(name, path=path)
if bootstrap_delay is not None:
try:
log.info('LXC %s: bootstrap_delay: %s', name, bootstrap_delay)
time.sleep(bootstrap_delay)
except TypeError:
# Bad input, but assume since a value was passed that
# a delay was desired, and sleep for 5 seconds
time.sleep(5)
c_info = info(name, path=path)
if not c_info:
return None
# default set here as we cannot set them
# in def as it can come from a chain of procedures.
if bootstrap_args:
# custom bootstrap args can be totally customized, and user could
# have inserted the placeholder for the config directory.
# For example, some salt bootstrap script do not use at all -c
if '{0}' not in bootstrap_args:
bootstrap_args += ' -c {0}'
else:
bootstrap_args = '-c {0}'
if not bootstrap_shell:
bootstrap_shell = 'sh'
orig_state = _ensure_running(name, path=path)
if not orig_state:
return orig_state
if not force_install:
needs_install = _needs_install(name, path=path)
else:
needs_install = True
seeded = retcode(name,
'test -e \'{0}\''.format(SEED_MARKER),
path=path,
chroot_fallback=True,
ignore_retcode=True) == 0
tmp = tempfile.mkdtemp()
if seeded and not unconditional_install:
ret = True
else:
ret = False
cfg_files = __salt__['seed.mkconfig'](
config, tmp=tmp, id_=name, approve_key=approve_key,
pub_key=pub_key, priv_key=priv_key)
if needs_install or force_install or unconditional_install:
if install:
rstr = __salt__['test.random_hash']()
configdir = '/var/tmp/.c_{0}'.format(rstr)
cmd = 'install -m 0700 -d {0}'.format(configdir)
if run_all(
name, cmd, path=path, python_shell=False
)['retcode'] != 0:
log.error('tmpdir %s creation failed %s', configdir, cmd)
return False
bs_ = __salt__['config.gather_bootstrap_script'](
bootstrap=bootstrap_url)
script = '/sbin/{0}_bootstrap.sh'.format(rstr)
copy_to(name, bs_, script, path=path)
result = run_all(name,
'sh -c "chmod +x {0}"'.format(script),
path=path,
python_shell=True)
copy_to(name, cfg_files['config'],
os.path.join(configdir, 'minion'),
path=path)
copy_to(name, cfg_files['privkey'],
os.path.join(configdir, 'minion.pem'),
path=path)
copy_to(name, cfg_files['pubkey'],
os.path.join(configdir, 'minion.pub'),
path=path)
bootstrap_args = bootstrap_args.format(configdir)
cmd = ('{0} {2} {1}'
.format(bootstrap_shell,
bootstrap_args.replace("'", "''"),
script))
# log ASAP the forged bootstrap command which can be wrapped
# out of the output in case of unexpected problem
log.info('Running %s in LXC container \'%s\'', cmd, name)
ret = retcode(name, cmd, output_loglevel='info',
path=path, use_vt=True) == 0
run_all(name,
'sh -c \'if [ -f "{0}" ];then rm -f "{0}";fi\''
''.format(script),
path=path,
ignore_retcode=True,
python_shell=True)
else:
ret = False
else:
minion_config = salt.config.minion_config(cfg_files['config'])
pki_dir = minion_config['pki_dir']
copy_to(name,
cfg_files['config'],
'/etc/salt/minion',
path=path)
copy_to(name,
cfg_files['privkey'],
os.path.join(pki_dir, 'minion.pem'),
path=path)
copy_to(name,
cfg_files['pubkey'],
os.path.join(pki_dir, 'minion.pub'),
path=path)
run(name,
'salt-call --local service.enable salt-minion',
path=path,
python_shell=False)
ret = True
shutil.rmtree(tmp)
if orig_state == 'stopped':
stop(name, path=path)
elif orig_state == 'frozen':
freeze(name, path=path)
# mark seeded upon successful install
if ret:
run(name,
'touch \'{0}\''.format(SEED_MARKER),
path=path,
python_shell=False)
return ret
def attachable(name, path=None):
'''
Return True if the named container can be attached to via the lxc-attach
command
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt 'minion' lxc.attachable ubuntu
'''
cachekey = 'lxc.attachable{0}{1}'.format(name, path)
try:
return __context__[cachekey]
except KeyError:
_ensure_exists(name, path=path)
# Can't use run() here because it uses attachable() and would
# endlessly recurse, resulting in a traceback
log.debug('Checking if LXC container %s is attachable', name)
cmd = 'lxc-attach'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' --clear-env -n {0} -- /usr/bin/env'.format(name)
result = __salt__['cmd.retcode'](cmd,
python_shell=False,
output_loglevel='quiet',
ignore_retcode=True) == 0
__context__[cachekey] = result
return __context__[cachekey]
def _run(name,
cmd,
output=None,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=None,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
Common logic for lxc.run functions
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
'''
orig_state = state(name, path=path)
try:
if attachable(name, path=path):
ret = __salt__['container_resource.run'](
name,
cmd,
path=path,
container_type=__virtualname__,
exec_driver=EXEC_DRIVER,
output=output,
no_start=no_start,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
ignore_retcode=ignore_retcode,
use_vt=use_vt,
keep_env=keep_env)
else:
if not chroot_fallback:
raise CommandExecutionError(
'{0} is not attachable.'.format(name))
rootfs = info(name, path=path).get('rootfs')
# Set context var to make cmd.run_chroot run cmd.run instead of
# cmd.run_all.
__context__['cmd.run_chroot.func'] = __salt__['cmd.run']
ret = __salt__['cmd.run_chroot'](rootfs,
cmd,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
ignore_retcode=ignore_retcode)
except Exception:
raise
finally:
# Make sure we honor preserve_state, even if there was an exception
new_state = state(name, path=path)
if preserve_state:
if orig_state == 'stopped' and new_state != 'stopped':
stop(name, path=path)
elif orig_state == 'frozen' and new_state != 'frozen':
freeze(name, start=True, path=path)
if output in (None, 'all'):
return ret
else:
return ret[output]
def run(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.8.0
Run :mod:`cmd.run <salt.modules.cmdmod.run>` within a container
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed in stderr if the command being run
does not exist. If no output is returned using this function, try using
:mod:`lxc.run_stderr <salt.modules.lxc.run_stderr>` or
:mod:`lxc.run_all <salt.modules.lxc.run_all>`.
name
Name of the container in which to run the command
cmd
Command to run
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console. Assumes
``output=all``.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
CLI Example:
.. code-block:: bash
salt myminion lxc.run mycontainer 'ifconfig -a'
'''
return _run(name,
cmd,
path=path,
output=None,
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def run_stdout(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.5.0
Run :mod:`cmd.run_stdout <salt.modules.cmdmod.run_stdout>` within a container
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed in stderr if the command being run
does not exist. If no output is returned using this function, try using
:mod:`lxc.run_stderr <salt.modules.lxc.run_stderr>` or
:mod:`lxc.run_all <salt.modules.lxc.run_all>`.
name
Name of the container in which to run the command
cmd
Command to run
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console
``output=all``.
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
CLI Example:
.. code-block:: bash
salt myminion lxc.run_stdout mycontainer 'ifconfig -a'
'''
return _run(name,
cmd,
path=path,
output='stdout',
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def run_stderr(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.5.0
Run :mod:`cmd.run_stderr <salt.modules.cmdmod.run_stderr>` within a container
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed if the command being run does not
exist.
name
Name of the container in which to run the command
cmd
Command to run
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console
``output=all``.
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
CLI Example:
.. code-block:: bash
salt myminion lxc.run_stderr mycontainer 'ip addr show'
'''
return _run(name,
cmd,
path=path,
output='stderr',
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def retcode(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.5.0
Run :mod:`cmd.retcode <salt.modules.cmdmod.retcode>` within a container
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed in stderr if the command being run
does not exist. If the retcode is nonzero and not what was expected,
try using :mod:`lxc.run_stderr <salt.modules.lxc.run_stderr>`
or :mod:`lxc.run_all <salt.modules.lxc.run_all>`.
name
Name of the container in which to run the command
cmd
Command to run
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console
``output=all``.
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
CLI Example:
.. code-block:: bash
salt myminion lxc.retcode mycontainer 'ip addr show'
'''
return _run(name,
cmd,
output='retcode',
path=path,
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def run_all(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.5.0
Run :mod:`cmd.run_all <salt.modules.cmdmod.run_all>` within a container
.. note::
While the command is run within the container, it is initiated from the
host. Therefore, the PID in the return dict is from the host, not from
the container.
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed in stderr if the command being run
does not exist.
name
Name of the container in which to run the command
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
cmd
Command to run
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console
``output=all``.
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
CLI Example:
.. code-block:: bash
salt myminion lxc.run_all mycontainer 'ip addr show'
'''
return _run(name,
cmd,
output='all',
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
path=path,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def _get_md5(name, path):
'''
Get the MD5 checksum of a file from a container
'''
output = run_stdout(name, 'md5sum "{0}"'.format(path),
chroot_fallback=True,
ignore_retcode=True)
try:
return output.split()[0]
except IndexError:
# Destination file does not exist or could not be accessed
return None
def copy_to(name, source, dest, overwrite=False, makedirs=False, path=None):
'''
.. versionchanged:: 2015.8.0
Function renamed from ``lxc.cp`` to ``lxc.copy_to`` for consistency
with other container types. ``lxc.cp`` will continue to work, however.
For versions 2015.2.x and earlier, use ``lxc.cp``.
Copy a file or directory from the host into a container
name
Container name
source
File to be copied to the container
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
dest
Destination on the container. Must be an absolute path.
.. versionchanged:: 2015.5.0
If the destination is a directory, the file will be copied into
that directory.
overwrite : False
Unless this option is set to ``True``, then if a file exists at the
location specified by the ``dest`` argument, an error will be raised.
.. versionadded:: 2015.8.0
makedirs : False
Create the parent directory on the container if it does not already
exist.
.. versionadded:: 2015.5.0
CLI Example:
.. code-block:: bash
salt 'minion' lxc.copy_to /tmp/foo /root/foo
salt 'minion' lxc.cp /tmp/foo /root/foo
'''
_ensure_running(name, no_start=True, path=path)
return __salt__['container_resource.copy_to'](
name,
source,
dest,
container_type=__virtualname__,
path=path,
exec_driver=EXEC_DRIVER,
overwrite=overwrite,
makedirs=makedirs)
cp = salt.utils.functools.alias_function(copy_to, 'cp')
def read_conf(conf_file, out_format='simple'):
'''
Read in an LXC configuration file. By default returns a simple, unsorted
dict, but can also return a more detailed structure including blank lines
and comments.
out_format:
set to 'simple' if you need the old and unsupported behavior.
This won't support the multiple lxc values (eg: multiple network nics)
CLI Examples:
.. code-block:: bash
salt 'minion' lxc.read_conf /etc/lxc/mycontainer.conf
salt 'minion' lxc.read_conf /etc/lxc/mycontainer.conf out_format=commented
'''
ret_commented = []
ret_simple = {}
with salt.utils.files.fopen(conf_file, 'r') as fp_:
for line in salt.utils.data.decode(fp_.readlines()):
if '=' not in line:
ret_commented.append(line)
continue
comps = line.split('=')
value = '='.join(comps[1:]).strip()
comment = None
if value.strip().startswith('#'):
vcomps = value.strip().split('#')
value = vcomps[1].strip()
comment = '#'.join(vcomps[1:]).strip()
ret_commented.append({comps[0].strip(): {
'value': value,
'comment': comment,
}})
else:
ret_commented.append({comps[0].strip(): value})
ret_simple[comps[0].strip()] = value
if out_format == 'simple':
return ret_simple
return ret_commented
def write_conf(conf_file, conf):
'''
Write out an LXC configuration file
This is normally only used internally. The format of the data structure
must match that which is returned from ``lxc.read_conf()``, with
``out_format`` set to ``commented``.
An example might look like:
.. code-block:: python
[
{'lxc.utsname': '$CONTAINER_NAME'},
'# This is a commented line\\n',
'\\n',
{'lxc.mount': '$CONTAINER_FSTAB'},
{'lxc.rootfs': {'comment': 'This is another test',
'value': 'This is another test'}},
'\\n',
{'lxc.network.type': 'veth'},
{'lxc.network.flags': 'up'},
{'lxc.network.link': 'br0'},
{'lxc.network.mac': '$CONTAINER_MACADDR'},
{'lxc.network.ipv4': '$CONTAINER_IPADDR'},
{'lxc.network.name': '$CONTAINER_DEVICENAME'},
]
CLI Example:
.. code-block:: bash
salt 'minion' lxc.write_conf /etc/lxc/mycontainer.conf \\
out_format=commented
'''
if not isinstance(conf, list):
raise SaltInvocationError('Configuration must be passed as a list')
# construct the content prior to write to the file
# to avoid half written configs
content = ''
for line in conf:
if isinstance(line, (six.text_type, six.string_types)):
content += line
elif isinstance(line, dict):
for key in list(line.keys()):
out_line = None
if isinstance(
line[key],
(six.text_type, six.string_types, six.integer_types, float)
):
out_line = ' = '.join((key, "{0}".format(line[key])))
elif isinstance(line[key], dict):
out_line = ' = '.join((key, line[key]['value']))
if 'comment' in line[key]:
out_line = ' # '.join((out_line, line[key]['comment']))
if out_line:
content += out_line
content += '\n'
with salt.utils.files.fopen(conf_file, 'w') as fp_:
fp_.write(salt.utils.stringutils.to_str(content))
return {}
def edit_conf(conf_file,
out_format='simple',
read_only=False,
lxc_config=None,
**kwargs):
'''
Edit an LXC configuration file. If a setting is already present inside the
file, its value will be replaced. If it does not exist, it will be appended
to the end of the file. Comments and blank lines will be kept in-tact if
they already exist in the file.
out_format:
Set to simple if you need backward compatibility (multiple items for a
simple key is not supported)
read_only:
return only the edited configuration without applying it
to the underlying lxc configuration file
lxc_config:
List of dict containning lxc configuration items
For network configuration, you also need to add the device it belongs
to, otherwise it will default to eth0.
Also, any change to a network parameter will result in the whole
network reconfiguration to avoid mismatchs, be aware of that !
After the file is edited, its contents will be returned. By default, it
will be returned in ``simple`` format, meaning an unordered dict (which
may not represent the actual file order). Passing in an ``out_format`` of
``commented`` will return a data structure which accurately represents the
order and content of the file.
CLI Example:
.. code-block:: bash
salt 'minion' lxc.edit_conf /etc/lxc/mycontainer.conf \\
out_format=commented lxc.network.type=veth
salt 'minion' lxc.edit_conf /etc/lxc/mycontainer.conf \\
out_format=commented \\
lxc_config="[{'lxc.network.name': 'eth0', \\
'lxc.network.ipv4': '1.2.3.4'},
{'lxc.network.name': 'eth2', \\
'lxc.network.ipv4': '1.2.3.5',\\
'lxc.network.gateway': '1.2.3.1'}]"
'''
data = []
try:
conf = read_conf(conf_file, out_format=out_format)
except Exception:
conf = []
if not lxc_config:
lxc_config = []
lxc_config = copy.deepcopy(lxc_config)
# search if we want to access net config
# in that case, we will replace all the net configuration
net_config = []
for lxc_kws in lxc_config + [kwargs]:
net_params = {}
for kwarg in [a for a in lxc_kws]:
if kwarg.startswith('__'):
continue
if kwarg.startswith('lxc.network.'):
net_params[kwarg] = lxc_kws[kwarg]
lxc_kws.pop(kwarg, None)
if net_params:
net_config.append(net_params)
nic_opts = salt.utils.odict.OrderedDict()
for params in net_config:
dev = params.get('lxc.network.name', DEFAULT_NIC)
dev_opts = nic_opts.setdefault(dev, salt.utils.odict.OrderedDict())
for param in params:
opt = param.replace('lxc.network.', '')
opt = {'hwaddr': 'mac'}.get(opt, opt)
dev_opts[opt] = params[param]
net_changes = []
if nic_opts:
net_changes = _config_list(conf, only_net=True,
**{'network_profile': DEFAULT_NIC,
'nic_opts': nic_opts})
if net_changes:
lxc_config.extend(net_changes)
for line in conf:
if not isinstance(line, dict):
data.append(line)
continue
else:
for key in list(line.keys()):
val = line[key]
if net_changes and key.startswith('lxc.network.'):
continue
found = False
for ix in range(len(lxc_config)):
kw = lxc_config[ix]
if key in kw:
found = True
data.append({key: kw[key]})
del kw[key]
if not found:
data.append({key: val})
for lxc_kws in lxc_config:
for kwarg in lxc_kws:
data.append({kwarg: lxc_kws[kwarg]})
if read_only:
return data
write_conf(conf_file, data)
return read_conf(conf_file, out_format)
def reboot(name, path=None):
'''
Reboot a container.
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Examples:
.. code-block:: bash
salt 'minion' lxc.reboot myvm
'''
ret = {'result': True,
'changes': {},
'comment': '{0} rebooted'.format(name)}
does_exist = exists(name, path=path)
if does_exist and (state(name, path=path) == 'running'):
try:
stop(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
ret['result'] = False
return ret
if does_exist and (state(name, path=path) != 'running'):
try:
start(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
ret['result'] = False
return ret
ret['changes'][name] = 'rebooted'
return ret
def reconfigure(name,
cpu=None,
cpuset=None,
cpushare=None,
memory=None,
profile=None,
network_profile=None,
nic_opts=None,
bridge=None,
gateway=None,
autostart=None,
utsname=None,
rootfs=None,
path=None,
**kwargs):
'''
Reconfigure a container.
This only applies to a few property
name
Name of the container.
utsname
utsname of the container.
.. versionadded:: 2016.3.0
rootfs
rootfs of the container.
.. versionadded:: 2016.3.0
cpu
Select a random number of cpu cores and assign it to the cpuset, if the
cpuset option is set then this option will be ignored
cpuset
Explicitly define the cpus this container will be bound to
cpushare
cgroups cpu shares.
autostart
autostart container on reboot
memory
cgroups memory limit, in MB.
(0 for nolimit, None for old default 1024MB)
gateway
the ipv4 gateway to use
the default does nothing more than lxcutils does
bridge
the bridge to use
the default does nothing more than lxcutils does
nic
Network interfaces profile (defined in config or pillar).
nic_opts
Extra options for network interfaces, will override
``{"eth0": {"mac": "aa:bb:cc:dd:ee:ff", "ipv4": "10.1.1.1", "ipv6": "2001:db8::ff00:42:8329"}}``
or
``{"eth0": {"mac": "aa:bb:cc:dd:ee:ff", "ipv4": "10.1.1.1/24", "ipv6": "2001:db8::ff00:42:8329"}}``
path
path to the container parent
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt-call -lall mc_lxc_fork.reconfigure foobar nic_opts="{'eth1': {'mac': '00:16:3e:dd:ee:44'}}" memory=4
'''
changes = {}
cpath = get_root_path(path)
path = os.path.join(cpath, name, 'config')
ret = {'name': name,
'comment': 'config for {0} up to date'.format(name),
'result': True,
'changes': changes}
profile = get_container_profile(copy.deepcopy(profile))
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, _marker)
profile_match = profile.pop(key, default)
# let kwarg overrides be the preferred choice
if kw_overrides_match is _marker:
return profile_match
return kw_overrides_match
if nic_opts is not None and not network_profile:
network_profile = DEFAULT_NIC
if autostart is not None:
autostart = select('autostart', autostart)
else:
autostart = 'keep'
if not utsname:
utsname = select('utsname', utsname)
if os.path.exists(path):
old_chunks = read_conf(path, out_format='commented')
make_kw = salt.utils.odict.OrderedDict([
('utsname', utsname),
('rootfs', rootfs),
('autostart', autostart),
('cpu', cpu),
('gateway', gateway),
('cpuset', cpuset),
('cpushare', cpushare),
('network_profile', network_profile),
('nic_opts', nic_opts),
('bridge', bridge)])
# match 0 and none as memory = 0 in lxc config is harmful
if memory:
make_kw['memory'] = memory
kw = salt.utils.odict.OrderedDict()
for key, val in six.iteritems(make_kw):
if val is not None:
kw[key] = val
new_cfg = _config_list(conf_tuples=old_chunks, **kw)
if new_cfg:
edit_conf(path, out_format='commented', lxc_config=new_cfg)
chunks = read_conf(path, out_format='commented')
if old_chunks != chunks:
ret['comment'] = '{0} lxc config updated'.format(name)
if state(name, path=path) == 'running':
cret = reboot(name, path=path)
ret['result'] = cret['result']
return ret
def apply_network_profile(name, network_profile, nic_opts=None, path=None):
'''
.. versionadded:: 2015.5.0
Apply a network profile to a container
network_profile
profile name or default values (dict)
nic_opts
values to override in defaults (dict)
indexed by nic card names
path
path to the container parent
.. versionadded:: 2015.8.0
CLI Examples:
.. code-block:: bash
salt 'minion' lxc.apply_network_profile web1 centos
salt 'minion' lxc.apply_network_profile web1 centos \\
nic_opts="{'eth0': {'mac': 'xx:xx:xx:xx:xx:xx'}}"
salt 'minion' lxc.apply_network_profile web1 \\
"{'eth0': {'mac': 'xx:xx:xx:xx:xx:yy'}}"
nic_opts="{'eth0': {'mac': 'xx:xx:xx:xx:xx:xx'}}"
The special case to disable use of ethernet nics:
.. code-block:: bash
salt 'minion' lxc.apply_network_profile web1 centos \\
"{eth0: {disable: true}}"
'''
cpath = get_root_path(path)
cfgpath = os.path.join(cpath, name, 'config')
before = []
with salt.utils.files.fopen(cfgpath, 'r') as fp_:
for line in fp_:
before.append(line)
lxcconfig = _LXCConfig(name=name, path=path)
old_net = lxcconfig._filter_data('lxc.network')
network_params = {}
for param in _network_conf(
conf_tuples=old_net,
network_profile=network_profile, nic_opts=nic_opts
):
network_params.update(param)
if network_params:
edit_conf(cfgpath, out_format='commented', **network_params)
after = []
with salt.utils.files.fopen(cfgpath, 'r') as fp_:
for line in fp_:
after.append(line)
diff = ''
for line in difflib.unified_diff(before,
after,
fromfile='before',
tofile='after'):
diff += line
return diff
def get_pid(name, path=None):
'''
Returns a container pid.
Throw an exception if the container isn't running.
CLI Example:
.. code-block:: bash
salt '*' lxc.get_pid name
'''
if name not in list_(limit='running', path=path):
raise CommandExecutionError('Container {0} is not running, can\'t determine PID'.format(name))
info = __salt__['cmd.run']('lxc-info -n {0}'.format(name)).split("\n")
pid = [line.split(':')[1].strip() for line in info if re.match(r'\s*PID', line)][0]
return pid
def add_veth(name, interface_name, bridge=None, path=None):
'''
Add a veth to a container.
Note : this function doesn't update the container config, just add the interface at runtime
name
Name of the container
interface_name
Name of the interface in the container
bridge
Name of the bridge to attach the interface to (facultative)
CLI Examples:
.. code-block:: bash
salt '*' lxc.add_veth container_name eth1 br1
salt '*' lxc.add_veth container_name eth1
'''
# Get container init PID
pid = get_pid(name, path=path)
# Generate a ramdom string for veth and ensure that is isn't present on the system
while True:
random_veth = 'veth'+''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(6))
if random_veth not in __salt__['network.interfaces']().keys():
break
# Check prerequisites
if not __salt__['file.directory_exists']('/var/run/'):
raise CommandExecutionError('Directory /var/run required for lxc.add_veth doesn\'t exists')
if not __salt__['file.file_exists']('/proc/{0}/ns/net'.format(pid)):
raise CommandExecutionError('Proc file for container {0} network namespace doesn\'t exists'.format(name))
if not __salt__['file.directory_exists']('/var/run/netns'):
__salt__['file.mkdir']('/var/run/netns')
# Ensure that the symlink is up to date (change on container restart)
if __salt__['file.is_link']('/var/run/netns/{0}'.format(name)):
__salt__['file.remove']('/var/run/netns/{0}'.format(name))
__salt__['file.symlink']('/proc/{0}/ns/net'.format(pid), '/var/run/netns/{0}'.format(name))
# Ensure that interface doesn't exists
interface_exists = 0 == __salt__['cmd.retcode']('ip netns exec {netns} ip address list {interface}'.format(
netns=name,
interface=interface_name
))
if interface_exists:
raise CommandExecutionError('Interface {interface} already exists in {container}'.format(
interface=interface_name,
container=name
))
# Create veth and bring it up
if __salt__['cmd.retcode']('ip link add name {veth} type veth peer name {veth}_c'.format(veth=random_veth)) != 0:
raise CommandExecutionError('Error while creating the veth pair {0}'.format(random_veth))
if __salt__['cmd.retcode']('ip link set dev {0} up'.format(random_veth)) != 0:
raise CommandExecutionError('Error while bringing up host-side veth {0}'.format(random_veth))
# Attach it to the container
attached = 0 == __salt__['cmd.retcode']('ip link set dev {veth}_c netns {container} name {interface_name}'.format(
veth=random_veth,
container=name,
interface_name=interface_name
))
if not attached:
raise CommandExecutionError('Error while attaching the veth {veth} to container {container}'.format(
veth=random_veth,
container=name
))
__salt__['file.remove']('/var/run/netns/{0}'.format(name))
if bridge is not None:
__salt__['bridge.addif'](bridge, random_veth)
|
saltstack/salt
|
salt/modules/lxc.py
|
images
|
python
|
def images(dist=None):
'''
.. versionadded:: 2015.5.0
List the available images for LXC's ``download`` template.
dist : None
Filter results to a single Linux distribution
CLI Examples:
.. code-block:: bash
salt myminion lxc.images
salt myminion lxc.images dist=centos
'''
out = __salt__['cmd.run_stdout'](
'lxc-create -n __imgcheck -t download -- --list',
ignore_retcode=True
)
if 'DIST' not in out:
raise CommandExecutionError(
'Unable to run the \'download\' template script. Is it installed?'
)
ret = {}
passed_header = False
for line in out.splitlines():
try:
distro, release, arch, variant, build_time = line.split()
except ValueError:
continue
if not passed_header:
if distro == 'DIST':
passed_header = True
continue
dist_list = ret.setdefault(distro, [])
dist_list.append({
'release': release,
'arch': arch,
'variant': variant,
'build_time': build_time,
})
if dist is not None:
return dict([(dist, ret.get(dist, []))])
return ret
|
.. versionadded:: 2015.5.0
List the available images for LXC's ``download`` template.
dist : None
Filter results to a single Linux distribution
CLI Examples:
.. code-block:: bash
salt myminion lxc.images
salt myminion lxc.images dist=centos
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/lxc.py#L1666-L1714
| null |
# -*- coding: utf-8 -*-
'''
Control Linux Containers via Salt
:depends: lxc package for distribution
lxc >= 1.0 (even beta alpha) is required
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import datetime
import copy
import string
import textwrap
import difflib
import logging
import tempfile
import os
import pipes
import time
import shutil
import re
import random
# Import salt libs
import salt.utils.args
import salt.utils.cloud
import salt.utils.data
import salt.utils.dictupdate
import salt.utils.files
import salt.utils.functools
import salt.utils.hashutils
import salt.utils.network
import salt.utils.odict
import salt.utils.path
import salt.utils.stringutils
from salt.exceptions import CommandExecutionError, SaltInvocationError
import salt.config
from salt.utils.versions import LooseVersion as _LooseVersion
# Import 3rd-party libs
from salt.ext import six
# pylint: disable=import-error,no-name-in-module
from salt.ext.six.moves import range # pylint: disable=redefined-builtin
from salt.ext.six.moves.urllib.parse import urlparse as _urlparse
# pylint: enable=import-error,no-name-in-module
# Set up logging
log = logging.getLogger(__name__)
# Don't shadow built-in's.
__func_alias__ = {
'list_': 'list',
'ls_': 'ls'
}
__virtualname__ = 'lxc'
DEFAULT_NIC = 'eth0'
DEFAULT_BR = 'br0'
SEED_MARKER = '/lxc.initial_seed'
EXEC_DRIVER = 'lxc-attach'
DEFAULT_PATH = '/var/lib/lxc'
_marker = object()
def __virtual__():
if salt.utils.path.which('lxc-start'):
return __virtualname__
# To speed up the whole thing, we decided to not use the
# subshell way and assume things are in place for lxc
# Discussion made by @kiorky and @thatch45
# lxc-version presence is not sufficient, in lxc1.0 alpha
# (precise backports), we have it and it is sufficient
# for the module to execute.
# elif salt.utils.path.which('lxc-version'):
# passed = False
# try:
# passed = subprocess.check_output(
# 'lxc-version').split(':')[1].strip() >= '1.0'
# except Exception:
# pass
# if not passed:
# log.warning('Support for lxc < 1.0 may be incomplete.')
# return 'lxc'
# return False
#
return (False, 'The lxc execution module cannot be loaded: the lxc-start binary is not in the path.')
def get_root_path(path):
'''
Get the configured lxc root for containers
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.get_root_path
'''
if not path:
path = __opts__.get('lxc.root_path', DEFAULT_PATH)
return path
def version():
'''
Return the actual lxc client version
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.version
'''
k = 'lxc.version'
if not __context__.get(k, None):
cversion = __salt__['cmd.run_all']('lxc-info --version')
if not cversion['retcode']:
ver = _LooseVersion(cversion['stdout'])
if ver < _LooseVersion('1.0'):
raise CommandExecutionError('LXC should be at least 1.0')
__context__[k] = "{0}".format(ver)
return __context__.get(k, None)
def _clear_context():
'''
Clear any lxc variables set in __context__
'''
for var in [x for x in __context__ if x.startswith('lxc.')]:
log.trace('Clearing __context__[\'%s\']', var)
__context__.pop(var, None)
def _ip_sort(ip):
'''Ip sorting'''
idx = '001'
if ip == '127.0.0.1':
idx = '200'
if ip == '::1':
idx = '201'
elif '::' in ip:
idx = '100'
return '{0}___{1}'.format(idx, ip)
def search_lxc_bridges():
'''
Search which bridges are potentially available as LXC bridges
CLI Example:
.. code-block:: bash
salt '*' lxc.search_lxc_bridges
'''
bridges = __context__.get('lxc.bridges', None)
# either match not yet called or no bridges were found
# to handle the case where lxc was not installed on the first
# call
if not bridges:
bridges = set()
running_bridges = set()
bridges.add(DEFAULT_BR)
try:
output = __salt__['cmd.run_all']('brctl show')
for line in output['stdout'].splitlines()[1:]:
if not line.startswith(' '):
running_bridges.add(line.split()[0].strip())
except (SaltInvocationError, CommandExecutionError):
pass
for ifc, ip in six.iteritems(
__grains__.get('ip_interfaces', {})
):
if ifc in running_bridges:
bridges.add(ifc)
elif os.path.exists(
'/sys/devices/virtual/net/{0}/bridge'.format(ifc)
):
bridges.add(ifc)
bridges = list(bridges)
# if we found interfaces that have lxc in their names
# we filter them as being the potential lxc bridges
# we also try to default on br0 on other cases
def sort_bridges(a):
pref = 'z'
if 'lxc' in a:
pref = 'a'
elif 'br0' == a:
pref = 'c'
return '{0}_{1}'.format(pref, a)
bridges.sort(key=sort_bridges)
__context__['lxc.bridges'] = bridges
return bridges
def search_lxc_bridge():
'''
Search the first bridge which is potentially available as LXC bridge
CLI Example:
.. code-block:: bash
salt '*' lxc.search_lxc_bridge
'''
return search_lxc_bridges()[0]
def _get_salt_config(config, **kwargs):
if not config:
config = kwargs.get('minion', {})
if not config:
config = {}
config.setdefault('master',
kwargs.get('master',
__opts__.get('master',
__opts__['id'])))
config.setdefault(
'master_port',
kwargs.get('master_port',
__opts__.get('master_port',
__opts__.get('ret_port',
__opts__.get('4506')))))
if not config['master']:
config = {}
return config
def cloud_init_interface(name, vm_=None, **kwargs):
'''
Interface between salt.cloud.lxc driver and lxc.init
``vm_`` is a mapping of vm opts in the salt.cloud format
as documented for the lxc driver.
This can be used either:
- from the salt cloud driver
- because you find the argument to give easier here
than using directly lxc.init
.. warning::
BE REALLY CAREFUL CHANGING DEFAULTS !!!
IT'S A RETRO COMPATIBLE INTERFACE WITH
THE SALT CLOUD DRIVER (ask kiorky).
name
name of the lxc container to create
pub_key
public key to preseed the minion with.
Can be the keycontent or a filepath
priv_key
private key to preseed the minion with.
Can be the keycontent or a filepath
path
path to the container parent directory (default: /var/lib/lxc)
.. versionadded:: 2015.8.0
profile
:ref:`profile <tutorial-lxc-profiles-container>` selection
network_profile
:ref:`network profile <tutorial-lxc-profiles-network>` selection
nic_opts
per interface settings compatibles with
network profile (ipv4/ipv6/link/gateway/mac/netmask)
eg::
- {'eth0': {'mac': '00:16:3e:01:29:40',
'gateway': None, (default)
'link': 'br0', (default)
'gateway': None, (default)
'netmask': '', (default)
'ip': '22.1.4.25'}}
unconditional_install
given to lxc.bootstrap (see relative doc)
force_install
given to lxc.bootstrap (see relative doc)
config
any extra argument for the salt minion config
dnsservers
list of DNS servers to set inside the container
dns_via_dhcp
do not set the dns servers, let them be set by the dhcp.
autostart
autostart the container at boot time
password
administrative password for the container
bootstrap_delay
delay before launching bootstrap script at Container init
.. warning::
Legacy but still supported options:
from_container
which container we use as a template
when running lxc.clone
image
which template do we use when we
are using lxc.create. This is the default
mode unless you specify something in from_container
backing
which backing store to use.
Values can be: overlayfs, dir(default), lvm, zfs, brtfs
fstype
When using a blockdevice level backing store,
which filesystem to use on
size
When using a blockdevice level backing store,
which size for the filesystem to use on
snapshot
Use snapshot when cloning the container source
vgname
if using LVM: vgname
lvname
if using LVM: lvname
thinpool:
if using LVM: thinpool
ip
ip for the primary nic
mac
mac address for the primary nic
netmask
netmask for the primary nic (24)
= ``vm_.get('netmask', '24')``
bridge
bridge for the primary nic (lxcbr0)
gateway
network gateway for the container
additional_ips
additional ips which will be wired on the main bridge (br0)
which is connected to internet.
Be aware that you may use manual virtual mac addresses
providen by you provider (online, ovh, etc).
This is a list of mappings {ip: '', mac: '', netmask:''}
Set gateway to None and an interface with a gateway
to escape from another interface that eth0.
eg::
- {'mac': '00:16:3e:01:29:40',
'gateway': None, (default)
'link': 'br0', (default)
'netmask': '', (default)
'ip': '22.1.4.25'}
users
administrative users for the container
default: [root] and [root, ubuntu] on ubuntu
default_nic
name of the first interface, you should
really not override this
CLI Example:
.. code-block:: bash
salt '*' lxc.cloud_init_interface foo
'''
if vm_ is None:
vm_ = {}
vm_ = copy.deepcopy(vm_)
vm_ = salt.utils.dictupdate.update(vm_, kwargs)
profile_data = copy.deepcopy(
vm_.get('lxc_profile',
vm_.get('profile', {})))
if not isinstance(profile_data, (dict, six.string_types)):
profile_data = {}
profile = get_container_profile(profile_data)
def _cloud_get(k, default=None):
return vm_.get(k, profile.get(k, default))
if name is None:
name = vm_['name']
# if we are on ubuntu, default to ubuntu
default_template = ''
if __grains__.get('os', '') in ['Ubuntu']:
default_template = 'ubuntu'
image = _cloud_get('image')
if not image:
_cloud_get('template', default_template)
backing = _cloud_get('backing', 'dir')
if image:
profile['template'] = image
vgname = _cloud_get('vgname', None)
if vgname:
profile['vgname'] = vgname
if backing:
profile['backing'] = backing
snapshot = _cloud_get('snapshot', False)
autostart = bool(_cloud_get('autostart', True))
dnsservers = _cloud_get('dnsservers', [])
dns_via_dhcp = _cloud_get('dns_via_dhcp', True)
password = _cloud_get('password', 's3cr3t')
password_encrypted = _cloud_get('password_encrypted', False)
fstype = _cloud_get('fstype', None)
lvname = _cloud_get('lvname', None)
thinpool = _cloud_get('thinpool', None)
pub_key = _cloud_get('pub_key', None)
priv_key = _cloud_get('priv_key', None)
size = _cloud_get('size', '20G')
script = _cloud_get('script', None)
script_args = _cloud_get('script_args', None)
users = _cloud_get('users', None)
if users is None:
users = []
ssh_username = _cloud_get('ssh_username', None)
if ssh_username and (ssh_username not in users):
users.append(ssh_username)
network_profile = _cloud_get('network_profile', None)
nic_opts = kwargs.get('nic_opts', None)
netmask = _cloud_get('netmask', '24')
path = _cloud_get('path', None)
bridge = _cloud_get('bridge', None)
gateway = _cloud_get('gateway', None)
unconditional_install = _cloud_get('unconditional_install', False)
force_install = _cloud_get('force_install', True)
config = _get_salt_config(_cloud_get('config', {}), **vm_)
default_nic = _cloud_get('default_nic', DEFAULT_NIC)
# do the interface with lxc.init mainly via nic_opts
# to avoid extra and confusing extra use cases.
if not isinstance(nic_opts, dict):
nic_opts = salt.utils.odict.OrderedDict()
# have a reference to the default nic
eth0 = nic_opts.setdefault(default_nic,
salt.utils.odict.OrderedDict())
# lxc config is based of ifc order, be sure to use odicts.
if not isinstance(nic_opts, salt.utils.odict.OrderedDict):
bnic_opts = salt.utils.odict.OrderedDict()
bnic_opts.update(nic_opts)
nic_opts = bnic_opts
gw = None
# legacy salt.cloud scheme for network interfaces settings support
bridge = _cloud_get('bridge', None)
ip = _cloud_get('ip', None)
mac = _cloud_get('mac', None)
if ip:
fullip = ip
if netmask:
fullip += '/{0}'.format(netmask)
eth0['ipv4'] = fullip
if mac is not None:
eth0['mac'] = mac
for ix, iopts in enumerate(_cloud_get("additional_ips", [])):
ifh = "eth{0}".format(ix+1)
ethx = nic_opts.setdefault(ifh, {})
if gw is None:
gw = iopts.get('gateway', ethx.get('gateway', None))
if gw:
# only one and only one default gateway is allowed !
eth0.pop('gateway', None)
gateway = None
# even if the gateway if on default "eth0" nic
# and we popped it will work
# as we reinject or set it here.
ethx['gateway'] = gw
elink = iopts.get('link', ethx.get('link', None))
if elink:
ethx['link'] = elink
# allow dhcp
aip = iopts.get('ipv4', iopts.get('ip', None))
if aip:
ethx['ipv4'] = aip
nm = iopts.get('netmask', '')
if nm:
ethx['ipv4'] += '/{0}'.format(nm)
for i in ('mac', 'hwaddr'):
if i in iopts:
ethx['mac'] = iopts[i]
break
if 'mac' not in ethx:
ethx['mac'] = salt.utils.network.gen_mac()
# last round checking for unique gateway and such
gw = None
for ethx in [a for a in nic_opts]:
ndata = nic_opts[ethx]
if gw:
ndata.pop('gateway', None)
if 'gateway' in ndata:
gw = ndata['gateway']
gateway = None
# only use a default bridge / gateway if we configured them
# via the legacy salt cloud configuration style.
# On other cases, we should rely on settings provided by the new
# salt lxc network profile style configuration which can
# be also be overridden or a per interface basis via the nic_opts dict.
if bridge:
eth0['link'] = bridge
if gateway:
eth0['gateway'] = gateway
#
lxc_init_interface = {}
lxc_init_interface['name'] = name
lxc_init_interface['config'] = config
lxc_init_interface['memory'] = _cloud_get('memory', 0) # nolimit
lxc_init_interface['pub_key'] = pub_key
lxc_init_interface['priv_key'] = priv_key
lxc_init_interface['nic_opts'] = nic_opts
for clone_from in ['clone_from', 'clone', 'from_container']:
# clone_from should default to None if not available
lxc_init_interface['clone_from'] = _cloud_get(clone_from, None)
if lxc_init_interface['clone_from'] is not None:
break
lxc_init_interface['profile'] = profile
lxc_init_interface['snapshot'] = snapshot
lxc_init_interface['dnsservers'] = dnsservers
lxc_init_interface['fstype'] = fstype
lxc_init_interface['path'] = path
lxc_init_interface['vgname'] = vgname
lxc_init_interface['size'] = size
lxc_init_interface['lvname'] = lvname
lxc_init_interface['thinpool'] = thinpool
lxc_init_interface['force_install'] = force_install
lxc_init_interface['unconditional_install'] = (
unconditional_install
)
lxc_init_interface['bootstrap_url'] = script
lxc_init_interface['bootstrap_args'] = script_args
lxc_init_interface['bootstrap_shell'] = _cloud_get('bootstrap_shell', 'sh')
lxc_init_interface['bootstrap_delay'] = _cloud_get('bootstrap_delay', None)
lxc_init_interface['autostart'] = autostart
lxc_init_interface['users'] = users
lxc_init_interface['password'] = password
lxc_init_interface['password_encrypted'] = password_encrypted
# be sure not to let objects goes inside the return
# as this return will be msgpacked for use in the runner !
lxc_init_interface['network_profile'] = network_profile
for i in ['cpu', 'cpuset', 'cpushare']:
if _cloud_get(i, None):
try:
lxc_init_interface[i] = vm_[i]
except KeyError:
lxc_init_interface[i] = profile[i]
return lxc_init_interface
def _get_profile(key, name, **kwargs):
if isinstance(name, dict):
profilename = name.pop('name', None)
return _get_profile(key, profilename, **name)
if name is None:
profile_match = {}
else:
profile_match = \
__salt__['config.get'](
'lxc.{1}:{0}'.format(name, key),
default=None,
merge='recurse'
)
if profile_match is None:
# No matching profile, make the profile an empty dict so that
# overrides can be applied below.
profile_match = {}
if not isinstance(profile_match, dict):
raise CommandExecutionError('lxc.{0} must be a dictionary'.format(key))
# Overlay the kwargs to override matched profile data
overrides = salt.utils.args.clean_kwargs(**copy.deepcopy(kwargs))
profile_match = salt.utils.dictupdate.update(
copy.deepcopy(profile_match),
overrides
)
return profile_match
def get_container_profile(name=None, **kwargs):
'''
.. versionadded:: 2015.5.0
Gather a pre-configured set of container configuration parameters. If no
arguments are passed, an empty profile is returned.
Profiles can be defined in the minion or master config files, or in pillar
or grains, and are loaded using :mod:`config.get
<salt.modules.config.get>`. The key under which LXC profiles must be
configured is ``lxc.container_profile.profile_name``. An example container
profile would be as follows:
.. code-block:: yaml
lxc.container_profile:
ubuntu:
template: ubuntu
backing: lvm
vgname: lxc
size: 1G
Parameters set in a profile can be overridden by passing additional
container creation arguments (such as the ones passed to :mod:`lxc.create
<salt.modules.lxc.create>`) to this function.
A profile can be defined either as the name of the profile, or a dictionary
of variable names and values. See the :ref:`LXC Tutorial
<tutorial-lxc-profiles>` for more information on how to use LXC profiles.
CLI Example:
.. code-block:: bash
salt-call lxc.get_container_profile centos
salt-call lxc.get_container_profile ubuntu template=ubuntu backing=overlayfs
'''
profile = _get_profile('container_profile', name, **kwargs)
return profile
def get_network_profile(name=None, **kwargs):
'''
.. versionadded:: 2015.5.0
Gather a pre-configured set of network configuration parameters. If no
arguments are passed, the following default profile is returned:
.. code-block:: python
{'eth0': {'link': 'br0', 'type': 'veth', 'flags': 'up'}}
Profiles can be defined in the minion or master config files, or in pillar
or grains, and are loaded using :mod:`config.get
<salt.modules.config.get>`. The key under which LXC profiles must be
configured is ``lxc.network_profile``. An example network profile would be
as follows:
.. code-block:: yaml
lxc.network_profile.centos:
eth0:
link: br0
type: veth
flags: up
To disable networking entirely:
.. code-block:: yaml
lxc.network_profile.centos:
eth0:
disable: true
Parameters set in a profile can be overridden by passing additional
arguments to this function.
A profile can be passed either as the name of the profile, or a
dictionary of variable names and values. See the :ref:`LXC Tutorial
<tutorial-lxc-profiles>` for more information on how to use network
profiles.
.. warning::
The ``ipv4``, ``ipv6``, ``gateway``, and ``link`` (bridge) settings in
network profiles will only work if the container doesn't redefine the
network configuration (for example in
``/etc/sysconfig/network-scripts/ifcfg-<interface_name>`` on
RHEL/CentOS, or ``/etc/network/interfaces`` on Debian/Ubuntu/etc.)
CLI Example:
.. code-block:: bash
salt-call lxc.get_network_profile default
'''
profile = _get_profile('network_profile', name, **kwargs)
return profile
def _rand_cpu_str(cpu):
'''
Return a random subset of cpus for the cpuset config
'''
cpu = int(cpu)
avail = __salt__['status.nproc']()
if cpu < avail:
return '0-{0}'.format(avail)
to_set = set()
while len(to_set) < cpu:
choice = random.randint(0, avail - 1)
if choice not in to_set:
to_set.add(six.text_type(choice))
return ','.join(sorted(to_set))
def _network_conf(conf_tuples=None, **kwargs):
'''
Network configuration defaults
network_profile
as for containers, we can either call this function
either with a network_profile dict or network profile name
in the kwargs
nic_opts
overrides or extra nics in the form {nic_name: {set: tings}
'''
nic = kwargs.get('network_profile', None)
ret = []
nic_opts = kwargs.get('nic_opts', {})
if nic_opts is None:
# coming from elsewhere
nic_opts = {}
if not conf_tuples:
conf_tuples = []
old = _get_veths(conf_tuples)
if not old:
old = {}
# if we have a profile name, get the profile and load the network settings
# this will obviously by default look for a profile called "eth0"
# or by what is defined in nic_opts
# and complete each nic settings by sane defaults
if nic and isinstance(nic, (six.string_types, dict)):
nicp = get_network_profile(nic)
else:
nicp = {}
if DEFAULT_NIC not in nicp:
nicp[DEFAULT_NIC] = {}
kwargs = copy.deepcopy(kwargs)
gateway = kwargs.pop('gateway', None)
bridge = kwargs.get('bridge', None)
if nic_opts:
for dev, args in six.iteritems(nic_opts):
ethx = nicp.setdefault(dev, {})
try:
ethx = salt.utils.dictupdate.update(ethx, args)
except AttributeError:
raise SaltInvocationError('Invalid nic_opts configuration')
ifs = [a for a in nicp]
ifs += [a for a in old if a not in nicp]
ifs.sort()
gateway_set = False
for dev in ifs:
args = nicp.get(dev, {})
opts = nic_opts.get(dev, {}) if nic_opts else {}
old_if = old.get(dev, {})
disable = opts.get('disable', args.get('disable', False))
if disable:
continue
mac = opts.get('mac',
opts.get('hwaddr',
args.get('mac',
args.get('hwaddr', ''))))
type_ = opts.get('type', args.get('type', ''))
flags = opts.get('flags', args.get('flags', ''))
link = opts.get('link', args.get('link', ''))
ipv4 = opts.get('ipv4', args.get('ipv4', ''))
ipv6 = opts.get('ipv6', args.get('ipv6', ''))
infos = salt.utils.odict.OrderedDict([
('lxc.network.type', {
'test': not type_,
'value': type_,
'old': old_if.get('lxc.network.type'),
'default': 'veth'}),
('lxc.network.name', {
'test': False,
'value': dev,
'old': dev,
'default': dev}),
('lxc.network.flags', {
'test': not flags,
'value': flags,
'old': old_if.get('lxc.network.flags'),
'default': 'up'}),
('lxc.network.link', {
'test': not link,
'value': link,
'old': old_if.get('lxc.network.link'),
'default': search_lxc_bridge()}),
('lxc.network.hwaddr', {
'test': not mac,
'value': mac,
'old': old_if.get('lxc.network.hwaddr'),
'default': salt.utils.network.gen_mac()}),
('lxc.network.ipv4', {
'test': not ipv4,
'value': ipv4,
'old': old_if.get('lxc.network.ipv4', ''),
'default': None}),
('lxc.network.ipv6', {
'test': not ipv6,
'value': ipv6,
'old': old_if.get('lxc.network.ipv6', ''),
'default': None})])
# for each parameter, if not explicitly set, the
# config value present in the LXC configuration should
# take precedence over the profile configuration
for info in list(infos.keys()):
bundle = infos[info]
if bundle['test']:
if bundle['old']:
bundle['value'] = bundle['old']
elif bundle['default']:
bundle['value'] = bundle['default']
for info, data in six.iteritems(infos):
if data['value']:
ret.append({info: data['value']})
for key, val in six.iteritems(args):
if key == 'link' and bridge:
val = bridge
val = opts.get(key, val)
if key in [
'type', 'flags', 'name',
'gateway', 'mac', 'link', 'ipv4', 'ipv6'
]:
continue
ret.append({'lxc.network.{0}'.format(key): val})
# gateway (in automode) must be appended following network conf !
if not gateway:
gateway = args.get('gateway', None)
if gateway is not None and not gateway_set:
ret.append({'lxc.network.ipv4.gateway': gateway})
# only one network gateway ;)
gateway_set = True
# normally, this won't happen
# set the gateway if specified even if we did
# not managed the network underlying
if gateway is not None and not gateway_set:
ret.append({'lxc.network.ipv4.gateway': gateway})
# only one network gateway ;)
gateway_set = True
new = _get_veths(ret)
# verify that we did not loose the mac settings
for iface in [a for a in new]:
ndata = new[iface]
nmac = ndata.get('lxc.network.hwaddr', '')
ntype = ndata.get('lxc.network.type', '')
omac, otype = '', ''
if iface in old:
odata = old[iface]
omac = odata.get('lxc.network.hwaddr', '')
otype = odata.get('lxc.network.type', '')
# default for network type is setted here
# attention not to change the network type
# without a good and explicit reason to.
if otype and not ntype:
ntype = otype
if not ntype:
ntype = 'veth'
new[iface]['lxc.network.type'] = ntype
if omac and not nmac:
new[iface]['lxc.network.hwaddr'] = omac
ret = []
for val in six.itervalues(new):
for row in val:
ret.append(salt.utils.odict.OrderedDict([(row, val[row])]))
# on old versions of lxc, still support the gateway auto mode
# if we didn't explicitly say no to
# (lxc.network.ipv4.gateway: auto)
if _LooseVersion(version()) <= _LooseVersion('1.0.7') and \
True not in ['lxc.network.ipv4.gateway' in a for a in ret] and \
True in ['lxc.network.ipv4' in a for a in ret]:
ret.append({'lxc.network.ipv4.gateway': 'auto'})
return ret
def _get_lxc_default_data(**kwargs):
kwargs = copy.deepcopy(kwargs)
ret = {}
for k in ['utsname', 'rootfs']:
val = kwargs.get(k, None)
if val is not None:
ret['lxc.{0}'.format(k)] = val
autostart = kwargs.get('autostart')
# autostart can have made in kwargs, but with the None
# value which is invalid, we need an explicit boolean
# autostart = on is the default.
if autostart is None:
autostart = True
# we will set the regular lxc marker to restart container at
# machine (re)boot only if we did not explicitly ask
# not to touch to the autostart settings via
# autostart == 'keep'
if autostart != 'keep':
if autostart:
ret['lxc.start.auto'] = '1'
else:
ret['lxc.start.auto'] = '0'
memory = kwargs.get('memory')
if memory is not None:
# converting the config value from MB to bytes
ret['lxc.cgroup.memory.limit_in_bytes'] = memory * 1024 * 1024
cpuset = kwargs.get('cpuset')
if cpuset:
ret['lxc.cgroup.cpuset.cpus'] = cpuset
cpushare = kwargs.get('cpushare')
cpu = kwargs.get('cpu')
if cpushare:
ret['lxc.cgroup.cpu.shares'] = cpushare
if cpu and not cpuset:
ret['lxc.cgroup.cpuset.cpus'] = _rand_cpu_str(cpu)
return ret
def _config_list(conf_tuples=None, only_net=False, **kwargs):
'''
Return a list of dicts from the salt level configurations
conf_tuples
_LXCConfig compatible list of entries which can contain
- string line
- tuple (lxc config param,value)
- dict of one entry: {lxc config param: value)
only_net
by default we add to the tuples a reflection of both
the real config if avalaible and a certain amount of
default values like the cpu parameters, the memory
and etc.
On the other hand, we also no matter the case reflect
the network configuration computed from the actual config if
available and given values.
if no_default_loads is set, we will only
reflect the network configuration back to the conf tuples
list
'''
# explicit cast
only_net = bool(only_net)
if not conf_tuples:
conf_tuples = []
kwargs = copy.deepcopy(kwargs)
ret = []
if not only_net:
default_data = _get_lxc_default_data(**kwargs)
for k, val in six.iteritems(default_data):
ret.append({k: val})
net_datas = _network_conf(conf_tuples=conf_tuples, **kwargs)
ret.extend(net_datas)
return ret
def _get_veths(net_data):
'''
Parse the nic setup inside lxc conf tuples back to a dictionary indexed by
network interface
'''
if isinstance(net_data, dict):
net_data = list(net_data.items())
nics = salt.utils.odict.OrderedDict()
current_nic = salt.utils.odict.OrderedDict()
no_names = True
for item in net_data:
if item and isinstance(item, dict):
item = list(item.items())[0]
# skip LXC configuration comment lines, and play only with tuples conf
elif isinstance(item, six.string_types):
# deal with reflection of commented lxc configs
sitem = item.strip()
if sitem.startswith('#') or not sitem:
continue
elif '=' in item:
item = tuple([a.strip() for a in item.split('=', 1)])
if item[0] == 'lxc.network.type':
current_nic = salt.utils.odict.OrderedDict()
if item[0] == 'lxc.network.name':
no_names = False
nics[item[1].strip()] = current_nic
current_nic[item[0].strip()] = item[1].strip()
# if not ethernet card name has been collected, assuming we collected
# data for eth0
if no_names and current_nic:
nics[DEFAULT_NIC] = current_nic
return nics
class _LXCConfig(object):
'''
LXC configuration data
'''
pattern = re.compile(r'^(\S+)(\s*)(=)(\s*)(.*)')
non_interpretable_pattern = re.compile(r'^((#.*)|(\s*))$')
def __init__(self, **kwargs):
kwargs = copy.deepcopy(kwargs)
self.name = kwargs.pop('name', None)
path = get_root_path(kwargs.get('path', None))
self.data = []
if self.name:
self.path = os.path.join(path, self.name, 'config')
if os.path.isfile(self.path):
with salt.utils.files.fopen(self.path) as fhr:
for line in salt.utils.data.decode(fhr.readlines()):
match = self.pattern.findall((line.strip()))
if match:
self.data.append((match[0][0], match[0][-1]))
match = self.non_interpretable_pattern.findall(
(line.strip()))
if match:
self.data.append(('', match[0][0]))
else:
self.path = None
def _replace(key, val):
if val:
self._filter_data(key)
self.data.append((key, val))
default_data = _get_lxc_default_data(**kwargs)
for key, val in six.iteritems(default_data):
_replace(key, val)
old_net = self._filter_data('lxc.network')
net_datas = _network_conf(conf_tuples=old_net, **kwargs)
if net_datas:
for row in net_datas:
self.data.extend(list(row.items()))
# be sure to reset harmful settings
for idx in ['lxc.cgroup.memory.limit_in_bytes']:
if not default_data.get(idx):
self._filter_data(idx)
def as_string(self):
chunks = ('{0[0]}{1}{0[1]}'.format(item, (' = ' if item[0] else '')) for item in self.data)
return '\n'.join(chunks) + '\n'
def write(self):
if self.path:
content = self.as_string()
# 2 step rendering to be sure not to open/wipe the config
# before as_string succeeds.
with salt.utils.files.fopen(self.path, 'w') as fic:
fic.write(salt.utils.stringutils.to_str(content))
fic.flush()
def tempfile(self):
# this might look like the function name is shadowing the
# module, but it's not since the method belongs to the class
ntf = tempfile.NamedTemporaryFile()
ntf.write(self.as_string())
ntf.flush()
return ntf
def _filter_data(self, pattern):
'''
Removes parameters which match the pattern from the config data
'''
removed = []
filtered = []
for param in self.data:
if not param[0].startswith(pattern):
filtered.append(param)
else:
removed.append(param)
self.data = filtered
return removed
def _get_base(**kwargs):
'''
If the needed base does not exist, then create it, if it does exist
create nothing and return the name of the base lxc container so
it can be cloned.
'''
profile = get_container_profile(copy.deepcopy(kwargs.get('profile')))
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, _marker)
profile_match = profile.pop(key, default)
# let kwarg overrides be the preferred choice
if kw_overrides_match is _marker:
return profile_match
return kw_overrides_match
template = select('template')
image = select('image')
vgname = select('vgname')
path = kwargs.get('path', None)
# remove the above three variables from kwargs, if they exist, to avoid
# duplicates if create() is invoked below.
for param in ('path', 'image', 'vgname', 'template'):
kwargs.pop(param, None)
if image:
proto = _urlparse(image).scheme
img_tar = __salt__['cp.cache_file'](image)
img_name = os.path.basename(img_tar)
hash_ = salt.utils.hashutils.get_hash(
img_tar,
__salt__['config.get']('hash_type'))
name = '__base_{0}_{1}_{2}'.format(proto, img_name, hash_)
if not exists(name, path=path):
create(name, template=template, image=image,
path=path, vgname=vgname, **kwargs)
if vgname:
rootfs = os.path.join('/dev', vgname, name)
edit_conf(info(name, path=path)['config'],
out_format='commented', **{'lxc.rootfs': rootfs})
return name
elif template:
name = '__base_{0}'.format(template)
if not exists(name, path=path):
create(name, template=template, image=image, path=path,
vgname=vgname, **kwargs)
if vgname:
rootfs = os.path.join('/dev', vgname, name)
edit_conf(info(name, path=path)['config'],
out_format='commented', **{'lxc.rootfs': rootfs})
return name
return ''
def init(name,
config=None,
cpuset=None,
cpushare=None,
memory=None,
profile=None,
network_profile=None,
nic_opts=None,
cpu=None,
autostart=True,
password=None,
password_encrypted=None,
users=None,
dnsservers=None,
searchdomains=None,
bridge=None,
gateway=None,
pub_key=None,
priv_key=None,
force_install=False,
unconditional_install=False,
bootstrap_delay=None,
bootstrap_args=None,
bootstrap_shell=None,
bootstrap_url=None,
**kwargs):
'''
Initialize a new container.
This is a partial idempotent function as if it is already provisioned, we
will reset a bit the lxc configuration file but much of the hard work will
be escaped as markers will prevent re-execution of harmful tasks.
name
Name of the container
image
A tar archive to use as the rootfs for the container. Conflicts with
the ``template`` argument.
cpus
Select a random number of cpu cores and assign it to the cpuset, if the
cpuset option is set then this option will be ignored
cpuset
Explicitly define the cpus this container will be bound to
cpushare
cgroups cpu shares
autostart
autostart container on reboot
memory
cgroups memory limit, in MB
.. versionchanged:: 2015.5.0
If no value is passed, no limit is set. In earlier Salt versions,
not passing this value causes a 1024MB memory limit to be set, and
it was necessary to pass ``memory=0`` to set no limit.
gateway
the ipv4 gateway to use
the default does nothing more than lxcutils does
bridge
the bridge to use
the default does nothing more than lxcutils does
network_profile
Network profile to use for the container
.. versionadded:: 2015.5.0
nic_opts
Extra options for network interfaces, will override
``{"eth0": {"hwaddr": "aa:bb:cc:dd:ee:ff", "ipv4": "10.1.1.1", "ipv6": "2001:db8::ff00:42:8329"}}``
or
``{"eth0": {"hwaddr": "aa:bb:cc:dd:ee:ff", "ipv4": "10.1.1.1/24", "ipv6": "2001:db8::ff00:42:8329"}}``
users
Users for which the password defined in the ``password`` param should
be set. Can be passed as a comma separated list or a python list.
Defaults to just the ``root`` user.
password
Set the initial password for the users defined in the ``users``
parameter
password_encrypted : False
Set to ``True`` to denote a password hash instead of a plaintext
password
.. versionadded:: 2015.5.0
profile
A LXC profile (defined in config or pillar).
This can be either a real profile mapping or a string
to retrieve it in configuration
start
Start the newly-created container
dnsservers
list of dns servers to set in the container, default [] (no setting)
seed
Seed the container with the minion config. Default: ``True``
install
If salt-minion is not already installed, install it. Default: ``True``
config
Optional config parameters. By default, the id is set to
the name of the container.
master
salt master (default to minion's master)
master_port
salt master port (default to minion's master port)
pub_key
Explicit public key to preseed the minion with (optional).
This can be either a filepath or a string representing the key
priv_key
Explicit private key to preseed the minion with (optional).
This can be either a filepath or a string representing the key
approve_key
If explicit preseeding is not used;
Attempt to request key approval from the master. Default: ``True``
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
clone_from
Original from which to use a clone operation to create the container.
Default: ``None``
bootstrap_delay
Delay in seconds between end of container creation and bootstrapping.
Useful when waiting for container to obtain a DHCP lease.
.. versionadded:: 2015.5.0
bootstrap_url
See lxc.bootstrap
bootstrap_shell
See lxc.bootstrap
bootstrap_args
See lxc.bootstrap
force_install
Force installation even if salt-minion is detected,
this is the way to run vendor bootstrap scripts even
if a salt minion is already present in the container
unconditional_install
Run the script even if the container seems seeded
CLI Example:
.. code-block:: bash
salt 'minion' lxc.init name [cpuset=cgroups_cpuset] \\
[cpushare=cgroups_cpushare] [memory=cgroups_memory] \\
[nic=nic_profile] [profile=lxc_profile] \\
[nic_opts=nic_opts] [start=(True|False)] \\
[seed=(True|False)] [install=(True|False)] \\
[config=minion_config] [approve_key=(True|False) \\
[clone_from=original] [autostart=True] \\
[priv_key=/path_or_content] [pub_key=/path_or_content] \\
[bridge=lxcbr0] [gateway=10.0.3.1] \\
[dnsservers[dns1,dns2]] \\
[users=[foo]] [password='secret'] \\
[password_encrypted=(True|False)]
'''
ret = {'name': name,
'changes': {}}
profile = get_container_profile(copy.deepcopy(profile))
if not network_profile:
network_profile = profile.get('network_profile')
if not network_profile:
network_profile = DEFAULT_NIC
# Changes is a pointer to changes_dict['init']. This method is used so that
# we can have a list of changes as they are made, providing an ordered list
# of things that were changed.
changes_dict = {'init': []}
changes = changes_dict.get('init')
if users is None:
users = []
dusers = ['root']
for user in dusers:
if user not in users:
users.append(user)
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, _marker)
profile_match = profile.pop(key, default)
# let kwarg overrides be the preferred choice
if kw_overrides_match is _marker:
return profile_match
return kw_overrides_match
path = select('path')
bpath = get_root_path(path)
state_pre = state(name, path=path)
tvg = select('vgname')
vgname = tvg if tvg else __salt__['config.get']('lxc.vgname')
start_ = select('start', True)
autostart = select('autostart', autostart)
seed = select('seed', True)
install = select('install', True)
seed_cmd = select('seed_cmd')
salt_config = _get_salt_config(config, **kwargs)
approve_key = select('approve_key', True)
clone_from = select('clone_from')
# If using a volume group then set up to make snapshot cow clones
if vgname and not clone_from:
try:
kwargs['vgname'] = vgname
clone_from = _get_base(profile=profile, **kwargs)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = exc.strerror
if changes:
ret['changes'] = changes_dict
return ret
if not kwargs.get('snapshot') is False:
kwargs['snapshot'] = True
does_exist = exists(name, path=path)
to_reboot = False
remove_seed_marker = False
if does_exist:
pass
elif clone_from:
remove_seed_marker = True
try:
clone(name, clone_from, profile=profile, **kwargs)
changes.append({'create': 'Container cloned'})
except (SaltInvocationError, CommandExecutionError) as exc:
if 'already exists' in exc.strerror:
changes.append({'create': 'Container already exists'})
else:
ret['result'] = False
ret['comment'] = exc.strerror
if changes:
ret['changes'] = changes_dict
return ret
cfg = _LXCConfig(name=name, network_profile=network_profile,
nic_opts=nic_opts, bridge=bridge, path=path,
gateway=gateway, autostart=autostart,
cpuset=cpuset, cpushare=cpushare, memory=memory)
old_chunks = read_conf(cfg.path, out_format='commented')
cfg.write()
chunks = read_conf(cfg.path, out_format='commented')
if old_chunks != chunks:
to_reboot = True
else:
remove_seed_marker = True
cfg = _LXCConfig(network_profile=network_profile,
nic_opts=nic_opts, cpuset=cpuset, path=path,
bridge=bridge, gateway=gateway,
autostart=autostart,
cpushare=cpushare, memory=memory)
with cfg.tempfile() as cfile:
try:
create(name, config=cfile.name, profile=profile, **kwargs)
changes.append({'create': 'Container created'})
except (SaltInvocationError, CommandExecutionError) as exc:
if 'already exists' in exc.strerror:
changes.append({'create': 'Container already exists'})
else:
ret['comment'] = exc.strerror
if changes:
ret['changes'] = changes_dict
return ret
cpath = os.path.join(bpath, name, 'config')
old_chunks = []
if os.path.exists(cpath):
old_chunks = read_conf(cpath, out_format='commented')
new_cfg = _config_list(conf_tuples=old_chunks,
cpu=cpu,
network_profile=network_profile,
nic_opts=nic_opts, bridge=bridge,
cpuset=cpuset, cpushare=cpushare,
memory=memory)
if new_cfg:
edit_conf(cpath, out_format='commented', lxc_config=new_cfg)
chunks = read_conf(cpath, out_format='commented')
if old_chunks != chunks:
to_reboot = True
# last time to be sure any of our property is correctly applied
cfg = _LXCConfig(name=name, network_profile=network_profile,
nic_opts=nic_opts, bridge=bridge, path=path,
gateway=gateway, autostart=autostart,
cpuset=cpuset, cpushare=cpushare, memory=memory)
old_chunks = []
if os.path.exists(cfg.path):
old_chunks = read_conf(cfg.path, out_format='commented')
cfg.write()
chunks = read_conf(cfg.path, out_format='commented')
if old_chunks != chunks:
changes.append({'config': 'Container configuration updated'})
to_reboot = True
if to_reboot:
try:
stop(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
if changes:
ret['changes'] = changes_dict
return ret
if not does_exist or (does_exist and state(name, path=path) != 'running'):
try:
start(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
if changes:
ret['changes'] = changes_dict
return ret
if remove_seed_marker:
run(name,
'rm -f \'{0}\''.format(SEED_MARKER),
path=path,
chroot_fallback=False,
python_shell=False)
# set the default user/password, only the first time
if ret.get('result', True) and password:
gid = '/.lxc.initial_pass'
gids = [gid,
'/lxc.initial_pass',
'/.lxc.{0}.initial_pass'.format(name)]
if not any(retcode(name,
'test -e "{0}"'.format(x),
chroot_fallback=True,
path=path,
ignore_retcode=True) == 0
for x in gids):
# think to touch the default user generated by default templates
# which has a really unsecure passwords...
# root is defined as a member earlier in the code
for default_user in ['ubuntu']:
if (
default_user not in users and
retcode(name,
'id {0}'.format(default_user),
python_shell=False,
path=path,
chroot_fallback=True,
ignore_retcode=True) == 0
):
users.append(default_user)
for user in users:
try:
cret = set_password(name,
users=[user],
path=path,
password=password,
encrypted=password_encrypted)
except (SaltInvocationError, CommandExecutionError) as exc:
msg = '{0}: Failed to set password'.format(
user) + exc.strerror
# only hardfail in unrecoverable situation:
# root cannot be setted up
if user == 'root':
ret['comment'] = msg
ret['result'] = False
else:
log.debug(msg)
if ret.get('result', True):
changes.append({'password': 'Password(s) updated'})
if retcode(name,
('sh -c \'touch "{0}"; test -e "{0}"\''
.format(gid)),
path=path,
chroot_fallback=True,
ignore_retcode=True) != 0:
ret['comment'] = 'Failed to set password marker'
changes[-1]['password'] += '. ' + ret['comment'] + '.'
ret['result'] = False
# set dns servers if any, only the first time
if ret.get('result', True) and dnsservers:
# retro compatibility, test also old markers
gid = '/.lxc.initial_dns'
gids = [gid,
'/lxc.initial_dns',
'/lxc.{0}.initial_dns'.format(name)]
if not any(retcode(name,
'test -e "{0}"'.format(x),
chroot_fallback=True,
path=path,
ignore_retcode=True) == 0
for x in gids):
try:
set_dns(name,
path=path,
dnsservers=dnsservers,
searchdomains=searchdomains)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Failed to set DNS: ' + exc.strerror
ret['result'] = False
else:
changes.append({'dns': 'DNS updated'})
if retcode(name,
('sh -c \'touch "{0}"; test -e "{0}"\''
.format(gid)),
chroot_fallback=True,
path=path,
ignore_retcode=True) != 0:
ret['comment'] = 'Failed to set DNS marker'
changes[-1]['dns'] += '. ' + ret['comment'] + '.'
ret['result'] = False
# retro compatibility, test also old markers
if remove_seed_marker:
run(name,
'rm -f \'{0}\''.format(SEED_MARKER),
path=path,
python_shell=False)
gid = '/.lxc.initial_seed'
gids = [gid, '/lxc.initial_seed']
if (
any(retcode(name,
'test -e {0}'.format(x),
path=path,
chroot_fallback=True,
ignore_retcode=True) == 0
for x in gids) or not ret.get('result', True)
):
pass
elif seed or seed_cmd:
if seed:
try:
result = bootstrap(
name, config=salt_config, path=path,
approve_key=approve_key,
pub_key=pub_key, priv_key=priv_key,
install=install,
force_install=force_install,
unconditional_install=unconditional_install,
bootstrap_delay=bootstrap_delay,
bootstrap_url=bootstrap_url,
bootstrap_shell=bootstrap_shell,
bootstrap_args=bootstrap_args)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Bootstrap failed: ' + exc.strerror
ret['result'] = False
else:
if not result:
ret['comment'] = ('Bootstrap failed, see minion log for '
'more information')
ret['result'] = False
else:
changes.append(
{'bootstrap': 'Container successfully bootstrapped'}
)
elif seed_cmd:
try:
result = __salt__[seed_cmd](info(name, path=path)['rootfs'],
name,
salt_config)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = ('Bootstrap via seed_cmd \'{0}\' failed: {1}'
.format(seed_cmd, exc.strerror))
ret['result'] = False
else:
if not result:
ret['comment'] = ('Bootstrap via seed_cmd \'{0}\' failed, '
'see minion log for more information '
.format(seed_cmd))
ret['result'] = False
else:
changes.append(
{'bootstrap': 'Container successfully bootstrapped '
'using seed_cmd \'{0}\''
.format(seed_cmd)}
)
if ret.get('result', True) and not start_:
try:
stop(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
ret['result'] = False
state_post = state(name, path=path)
if state_pre != state_post:
changes.append({'state': {'old': state_pre, 'new': state_post}})
if ret.get('result', True):
ret['comment'] = ('Container \'{0}\' successfully initialized'
.format(name))
ret['result'] = True
if changes:
ret['changes'] = changes_dict
return ret
def cloud_init(name, vm_=None, **kwargs):
'''
Thin wrapper to lxc.init to be used from the saltcloud lxc driver
name
Name of the container
may be None and then guessed from saltcloud mapping
`vm_`
saltcloud mapping defaults for the vm
CLI Example:
.. code-block:: bash
salt '*' lxc.cloud_init foo
'''
init_interface = cloud_init_interface(name, vm_, **kwargs)
name = init_interface.pop('name', name)
return init(name, **init_interface)
def templates():
'''
.. versionadded:: 2015.5.0
List the available LXC template scripts installed on the minion
CLI Examples:
.. code-block:: bash
salt myminion lxc.templates
'''
try:
template_scripts = os.listdir('/usr/share/lxc/templates')
except OSError:
return []
else:
return [x[4:] for x in template_scripts if x.startswith('lxc-')]
def _after_ignition_network_profile(cmd,
ret,
name,
network_profile,
path,
nic_opts):
_clear_context()
if ret['retcode'] == 0 and exists(name, path=path):
if network_profile:
network_changes = apply_network_profile(name,
network_profile,
path=path,
nic_opts=nic_opts)
if network_changes:
log.info(
'Network changes from applying network profile \'%s\' '
'to newly-created container \'%s\':\n%s',
network_profile, name, network_changes
)
c_state = state(name, path=path)
return {'result': True,
'state': {'old': None, 'new': c_state}}
else:
if exists(name, path=path):
# destroy the container if it was partially created
cmd = 'lxc-destroy'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0}'.format(name)
__salt__['cmd.retcode'](cmd, python_shell=False)
raise CommandExecutionError(
'Container could not be created with cmd \'{0}\': {1}'
.format(cmd, ret['stderr'])
)
def create(name,
config=None,
profile=None,
network_profile=None,
nic_opts=None,
**kwargs):
'''
Create a new container.
name
Name of the container
config
The config file to use for the container. Defaults to system-wide
config (usually in /etc/lxc/lxc.conf).
profile
Profile to use in container creation (see
:mod:`lxc.get_container_profile
<salt.modules.lxc.get_container_profile>`). Values in a profile will be
overridden by the **Container Creation Arguments** listed below.
network_profile
Network profile to use for container
.. versionadded:: 2015.5.0
**Container Creation Arguments**
template
The template to use. For example, ``ubuntu`` or ``fedora``.
For a full list of available templates, check out
the :mod:`lxc.templates <salt.modules.lxc.templates>` function.
Conflicts with the ``image`` argument.
.. note::
The ``download`` template requires the following three parameters
to be defined in ``options``:
* **dist** - The name of the distribution
* **release** - Release name/version
* **arch** - Architecture of the container
The available images can be listed using the :mod:`lxc.images
<salt.modules.lxc.images>` function.
options
Template-specific options to pass to the lxc-create command. These
correspond to the long options (ones beginning with two dashes) that
the template script accepts. For example:
.. code-block:: bash
options='{"dist": "centos", "release": "6", "arch": "amd64"}'
For available template options, refer to the lxc template scripts
which are ususally located under ``/usr/share/lxc/templates``,
or run ``lxc-create -t <template> -h``.
image
A tar archive to use as the rootfs for the container. Conflicts with
the ``template`` argument.
backing
The type of storage to use. Set to ``lvm`` to use an LVM group.
Defaults to filesystem within /var/lib/lxc.
fstype
Filesystem type to use on LVM logical volume
size : 1G
Size of the volume to create. Only applicable if ``backing=lvm``.
vgname : lxc
Name of the LVM volume group in which to create the volume for this
container. Only applicable if ``backing=lvm``.
lvname
Name of the LVM logical volume in which to create the volume for this
container. Only applicable if ``backing=lvm``.
thinpool
Name of a pool volume that will be used for thin-provisioning this
container. Only applicable if ``backing=lvm``.
nic_opts
give extra opts overriding network profile values
path
parent path for the container creation (default: /var/lib/lxc)
zfsroot
Name of the ZFS root in which to create the volume for this container.
Only applicable if ``backing=zfs``. (default: tank/lxc)
.. versionadded:: 2015.8.0
'''
# Required params for 'download' template
download_template_deps = ('dist', 'release', 'arch')
cmd = 'lxc-create -n {0}'.format(name)
profile = get_container_profile(copy.deepcopy(profile))
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, None)
profile_match = profile.pop(key, default)
# Return the profile match if the the kwarg match was None, as the
# lxc.present state will pass these kwargs set to None by default.
if kw_overrides_match is None:
return profile_match
return kw_overrides_match
path = select('path')
if exists(name, path=path):
raise CommandExecutionError(
'Container \'{0}\' already exists'.format(name)
)
tvg = select('vgname')
vgname = tvg if tvg else __salt__['config.get']('lxc.vgname')
# The 'template' and 'image' params conflict
template = select('template')
image = select('image')
if template and image:
raise SaltInvocationError(
'Only one of \'template\' and \'image\' is permitted'
)
elif not any((template, image, profile)):
raise SaltInvocationError(
'At least one of \'template\', \'image\', and \'profile\' is '
'required'
)
options = select('options') or {}
backing = select('backing')
if vgname and not backing:
backing = 'lvm'
lvname = select('lvname')
thinpool = select('thinpool')
fstype = select('fstype')
size = select('size', '1G')
zfsroot = select('zfsroot')
if backing in ('dir', 'overlayfs', 'btrfs', 'zfs'):
fstype = None
size = None
# some backends won't support some parameters
if backing in ('aufs', 'dir', 'overlayfs', 'btrfs'):
lvname = vgname = thinpool = None
if image:
img_tar = __salt__['cp.cache_file'](image)
template = os.path.join(
os.path.dirname(salt.__file__),
'templates',
'lxc',
'salt_tarball')
options['imgtar'] = img_tar
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
if not os.path.exists(path):
os.makedirs(path)
if config:
cmd += ' -f {0}'.format(config)
if template:
cmd += ' -t {0}'.format(template)
if backing:
backing = backing.lower()
cmd += ' -B {0}'.format(backing)
if backing in ('zfs',):
if zfsroot:
cmd += ' --zfsroot {0}'.format(zfsroot)
if backing in ('lvm',):
if lvname:
cmd += ' --lvname {0}'.format(lvname)
if vgname:
cmd += ' --vgname {0}'.format(vgname)
if thinpool:
cmd += ' --thinpool {0}'.format(thinpool)
if backing not in ('dir', 'overlayfs'):
if fstype:
cmd += ' --fstype {0}'.format(fstype)
if size:
cmd += ' --fssize {0}'.format(size)
if options:
if template == 'download':
missing_deps = [x for x in download_template_deps
if x not in options]
if missing_deps:
raise SaltInvocationError(
'Missing params in \'options\' dict: {0}'
.format(', '.join(missing_deps))
)
cmd += ' --'
for key, val in six.iteritems(options):
cmd += ' --{0} {1}'.format(key, val)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
# please do not merge extra conflicting stuff
# inside those two line (ret =, return)
return _after_ignition_network_profile(cmd,
ret,
name,
network_profile,
path,
nic_opts)
def clone(name,
orig,
profile=None,
network_profile=None,
nic_opts=None,
**kwargs):
'''
Create a new container as a clone of another container
name
Name of the container
orig
Name of the original container to be cloned
profile
Profile to use in container cloning (see
:mod:`lxc.get_container_profile
<salt.modules.lxc.get_container_profile>`). Values in a profile will be
overridden by the **Container Cloning Arguments** listed below.
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
**Container Cloning Arguments**
snapshot
Use Copy On Write snapshots (LVM)
size : 1G
Size of the volume to create. Only applicable if ``backing=lvm``.
backing
The type of storage to use. Set to ``lvm`` to use an LVM group.
Defaults to filesystem within /var/lib/lxc.
network_profile
Network profile to use for container
.. versionadded:: 2015.8.0
nic_opts
give extra opts overriding network profile values
.. versionadded:: 2015.8.0
CLI Examples:
.. code-block:: bash
salt '*' lxc.clone myclone orig=orig_container
salt '*' lxc.clone myclone orig=orig_container snapshot=True
'''
profile = get_container_profile(copy.deepcopy(profile))
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, None)
profile_match = profile.pop(key, default)
# let kwarg overrides be the preferred choice
if kw_overrides_match is None:
return profile_match
return kw_overrides_match
path = select('path')
if exists(name, path=path):
raise CommandExecutionError(
'Container \'{0}\' already exists'.format(name)
)
_ensure_exists(orig, path=path)
if state(orig, path=path) != 'stopped':
raise CommandExecutionError(
'Container \'{0}\' must be stopped to be cloned'.format(orig)
)
backing = select('backing')
snapshot = select('snapshot')
if backing in ('dir',):
snapshot = False
if not snapshot:
snapshot = ''
else:
snapshot = '-s'
size = select('size', '1G')
if backing in ('dir', 'overlayfs', 'btrfs'):
size = None
# LXC commands and options changed in 2.0 - CF issue #34086 for details
if _LooseVersion(version()) >= _LooseVersion('2.0'):
# https://linuxcontainers.org/lxc/manpages//man1/lxc-copy.1.html
cmd = 'lxc-copy'
cmd += ' {0} -n {1} -N {2}'.format(snapshot, orig, name)
else:
# https://linuxcontainers.org/lxc/manpages//man1/lxc-clone.1.html
cmd = 'lxc-clone'
cmd += ' {0} -o {1} -n {2}'.format(snapshot, orig, name)
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
if not os.path.exists(path):
os.makedirs(path)
if backing:
backing = backing.lower()
cmd += ' -B {0}'.format(backing)
if backing not in ('dir', 'overlayfs'):
if size:
cmd += ' -L {0}'.format(size)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
# please do not merge extra conflicting stuff
# inside those two line (ret =, return)
return _after_ignition_network_profile(cmd,
ret,
name,
network_profile,
path,
nic_opts)
def ls_(active=None, cache=True, path=None):
'''
Return a list of the containers available on the minion
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
active
If ``True``, return only active (i.e. running) containers
.. versionadded:: 2015.5.0
CLI Example:
.. code-block:: bash
salt '*' lxc.ls
salt '*' lxc.ls active=True
'''
contextvar = 'lxc.ls{0}'.format(path)
if active:
contextvar += '.active'
if cache and (contextvar in __context__):
return __context__[contextvar]
else:
ret = []
cmd = 'lxc-ls'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
if active:
cmd += ' --active'
output = __salt__['cmd.run_stdout'](cmd, python_shell=False)
for line in output.splitlines():
ret.extend(line.split())
__context__[contextvar] = ret
return ret
def list_(extra=False, limit=None, path=None):
'''
List containers classified by state
extra
Also get per-container specific info. This will change the return data.
Instead of returning a list of containers, a dictionary of containers
and each container's output from :mod:`lxc.info
<salt.modules.lxc.info>`.
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
limit
Return output matching a specific state (**frozen**, **running**, or
**stopped**).
.. versionadded:: 2015.5.0
CLI Examples:
.. code-block:: bash
salt '*' lxc.list
salt '*' lxc.list extra=True
salt '*' lxc.list limit=running
'''
ctnrs = ls_(path=path)
if extra:
stopped = {}
frozen = {}
running = {}
else:
stopped = []
frozen = []
running = []
ret = {'running': running,
'stopped': stopped,
'frozen': frozen}
for container in ctnrs:
cmd = 'lxc-info'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0}'.format(container)
c_info = __salt__['cmd.run'](
cmd,
python_shell=False,
output_loglevel='debug'
)
c_state = None
for line in c_info.splitlines():
stat = line.split(':')
if stat[0] in ('State', 'state'):
c_state = stat[1].strip()
break
if not c_state or (limit is not None and c_state.lower() != limit):
continue
if extra:
infos = info(container, path=path)
method = 'update'
value = {container: infos}
else:
method = 'append'
value = container
if c_state == 'STOPPED':
getattr(stopped, method)(value)
continue
if c_state == 'FROZEN':
getattr(frozen, method)(value)
continue
if c_state == 'RUNNING':
getattr(running, method)(value)
continue
if limit is not None:
return ret.get(limit, {} if extra else [])
return ret
def _change_state(cmd,
name,
expected,
stdin=_marker,
stdout=_marker,
stderr=_marker,
with_communicate=_marker,
use_vt=_marker,
path=None):
pre = state(name, path=path)
if pre == expected:
return {'result': True,
'state': {'old': expected, 'new': expected},
'comment': 'Container \'{0}\' already {1}'
.format(name, expected)}
if cmd == 'lxc-destroy':
# Kill the container first
scmd = 'lxc-stop'
if path:
scmd += ' -P {0}'.format(pipes.quote(path))
scmd += ' -k -n {0}'.format(name)
__salt__['cmd.run'](scmd,
python_shell=False)
if path and ' -P ' not in cmd:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0}'.format(name)
# certain lxc commands need to be taken with care (lxc-start)
# as te command itself mess with double forks; we must not
# communicate with it, but just wait for the exit status
pkwargs = {'python_shell': False,
'redirect_stderr': True,
'with_communicate': with_communicate,
'use_vt': use_vt,
'stdin': stdin,
'stdout': stdout}
for i in [a for a in pkwargs]:
val = pkwargs[i]
if val is _marker:
pkwargs.pop(i, None)
_cmdout = __salt__['cmd.run_all'](cmd, **pkwargs)
if _cmdout['retcode'] != 0:
raise CommandExecutionError(
'Error changing state for container \'{0}\' using command '
'\'{1}\': {2}'.format(name, cmd, _cmdout['stdout'])
)
if expected is not None:
# some commands do not wait, so we will
rcmd = 'lxc-wait'
if path:
rcmd += ' -P {0}'.format(pipes.quote(path))
rcmd += ' -n {0} -s {1}'.format(name, expected.upper())
__salt__['cmd.run'](rcmd, python_shell=False, timeout=30)
_clear_context()
post = state(name, path=path)
ret = {'result': post == expected,
'state': {'old': pre, 'new': post}}
return ret
def _ensure_exists(name, path=None):
'''
Raise an exception if the container does not exist
'''
if not exists(name, path=path):
raise CommandExecutionError(
'Container \'{0}\' does not exist'.format(name)
)
def _ensure_running(name, no_start=False, path=None):
'''
If the container is not currently running, start it. This function returns
the state that the container was in before changing
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
'''
_ensure_exists(name, path=path)
pre = state(name, path=path)
if pre == 'running':
# This will be a no-op but running the function will give us a pretty
# return dict.
return start(name, path=path)
elif pre == 'stopped':
if no_start:
raise CommandExecutionError(
'Container \'{0}\' is not running'.format(name)
)
return start(name, path=path)
elif pre == 'frozen':
if no_start:
raise CommandExecutionError(
'Container \'{0}\' is not running'.format(name)
)
return unfreeze(name, path=path)
def restart(name, path=None, lxc_config=None, force=False):
'''
.. versionadded:: 2015.5.0
Restart the named container. If the container was not running, the
container will merely be started.
name
The name of the container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
lxc_config
path to a lxc config file
config file will be guessed from container name otherwise
.. versionadded:: 2015.8.0
force : False
If ``True``, the container will be force-stopped instead of gracefully
shut down
CLI Example:
.. code-block:: bash
salt myminion lxc.restart name
'''
_ensure_exists(name, path=path)
orig_state = state(name, path=path)
if orig_state != 'stopped':
stop(name, kill=force, path=path)
ret = start(name, path=path, lxc_config=lxc_config)
ret['state']['old'] = orig_state
if orig_state != 'stopped':
ret['restarted'] = True
return ret
def start(name, **kwargs):
'''
Start the named container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
lxc_config
path to a lxc config file
config file will be guessed from container name otherwise
.. versionadded:: 2015.8.0
use_vt
run the command through VT
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.start name
'''
path = kwargs.get('path', None)
cpath = get_root_path(path)
lxc_config = kwargs.get('lxc_config', None)
cmd = 'lxc-start'
if not lxc_config:
lxc_config = os.path.join(cpath, name, 'config')
# we try to start, even without config, if global opts are there
if os.path.exists(lxc_config):
cmd += ' -f {0}'.format(pipes.quote(lxc_config))
cmd += ' -d'
_ensure_exists(name, path=path)
if state(name, path=path) == 'frozen':
raise CommandExecutionError(
'Container \'{0}\' is frozen, use lxc.unfreeze'.format(name)
)
# lxc-start daemonize itself violently, we must not communicate with it
use_vt = kwargs.get('use_vt', None)
with_communicate = kwargs.get('with_communicate', False)
return _change_state(cmd, name, 'running',
stdout=None,
stderr=None,
stdin=None,
with_communicate=with_communicate,
path=path,
use_vt=use_vt)
def stop(name, kill=False, path=None, use_vt=None):
'''
Stop the named container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
kill: False
Do not wait for the container to stop, kill all tasks in the container.
Older LXC versions will stop containers like this irrespective of this
argument.
.. versionchanged:: 2015.5.0
Default value changed to ``False``
use_vt
run the command through VT
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.stop name
'''
_ensure_exists(name, path=path)
orig_state = state(name, path=path)
if orig_state == 'frozen' and not kill:
# Gracefully stopping a frozen container is slower than unfreezing and
# then stopping it (at least in my testing), so if we're not
# force-stopping the container, unfreeze it first.
unfreeze(name, path=path)
cmd = 'lxc-stop'
if kill:
cmd += ' -k'
ret = _change_state(cmd, name, 'stopped', use_vt=use_vt, path=path)
ret['state']['old'] = orig_state
return ret
def freeze(name, **kwargs):
'''
Freeze the named container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
start : False
If ``True`` and the container is stopped, the container will be started
before attempting to freeze.
.. versionadded:: 2015.5.0
use_vt
run the command through VT
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.freeze name
'''
use_vt = kwargs.get('use_vt', None)
path = kwargs.get('path', None)
_ensure_exists(name, path=path)
orig_state = state(name, path=path)
start_ = kwargs.get('start', False)
if orig_state == 'stopped':
if not start_:
raise CommandExecutionError(
'Container \'{0}\' is stopped'.format(name)
)
start(name, path=path)
cmd = 'lxc-freeze'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
ret = _change_state(cmd, name, 'frozen', use_vt=use_vt, path=path)
if orig_state == 'stopped' and start_:
ret['state']['old'] = orig_state
ret['started'] = True
ret['state']['new'] = state(name, path=path)
return ret
def unfreeze(name, path=None, use_vt=None):
'''
Unfreeze the named container.
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
use_vt
run the command through VT
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.unfreeze name
'''
_ensure_exists(name, path=path)
if state(name, path=path) == 'stopped':
raise CommandExecutionError(
'Container \'{0}\' is stopped'.format(name)
)
cmd = 'lxc-unfreeze'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
return _change_state(cmd, name, 'running', path=path, use_vt=use_vt)
def destroy(name, stop=False, path=None):
'''
Destroy the named container.
.. warning::
Destroys all data associated with the container.
path
path to the container parent directory (default: /var/lib/lxc)
.. versionadded:: 2015.8.0
stop : False
If ``True``, the container will be destroyed even if it is
running/frozen.
.. versionchanged:: 2015.5.0
Default value changed to ``False``. This more closely matches the
behavior of ``lxc-destroy(1)``, and also makes it less likely that
an accidental command will destroy a running container that was
being used for important things.
CLI Examples:
.. code-block:: bash
salt '*' lxc.destroy foo
salt '*' lxc.destroy foo stop=True
'''
_ensure_exists(name, path=path)
if not stop and state(name, path=path) != 'stopped':
raise CommandExecutionError(
'Container \'{0}\' is not stopped'.format(name)
)
return _change_state('lxc-destroy', name, None, path=path)
# Compatibility between LXC and nspawn
remove = salt.utils.functools.alias_function(destroy, 'remove')
def exists(name, path=None):
'''
Returns whether the named container exists.
path
path to the container parent directory (default: /var/lib/lxc)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.exists name
'''
_exists = name in ls_(path=path)
# container may be just created but we did cached earlier the
# lxc-ls results
if not _exists:
_exists = name in ls_(cache=False, path=path)
return _exists
def state(name, path=None):
'''
Returns the state of a container.
path
path to the container parent directory (default: /var/lib/lxc)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.state name
'''
# Don't use _ensure_exists() here, it will mess with _change_state()
cachekey = 'lxc.state.{0}{1}'.format(name, path)
try:
return __context__[cachekey]
except KeyError:
if not exists(name, path=path):
__context__[cachekey] = None
else:
cmd = 'lxc-info'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0}'.format(name)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
if ret['retcode'] != 0:
_clear_context()
raise CommandExecutionError(
'Unable to get state of container \'{0}\''.format(name)
)
c_infos = ret['stdout'].splitlines()
c_state = None
for c_info in c_infos:
stat = c_info.split(':')
if stat[0].lower() == 'state':
c_state = stat[1].strip().lower()
break
__context__[cachekey] = c_state
return __context__[cachekey]
def get_parameter(name, parameter, path=None):
'''
Returns the value of a cgroup parameter for a container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.get_parameter container_name memory.limit_in_bytes
'''
_ensure_exists(name, path=path)
cmd = 'lxc-cgroup'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0} {1}'.format(name, parameter)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
if ret['retcode'] != 0:
raise CommandExecutionError(
'Unable to retrieve value for \'{0}\''.format(parameter)
)
return ret['stdout'].strip()
def set_parameter(name, parameter, value, path=None):
'''
Set the value of a cgroup parameter for a container.
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.set_parameter name parameter value
'''
if not exists(name, path=path):
return None
cmd = 'lxc-cgroup'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0} {1} {2}'.format(name, parameter, value)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
if ret['retcode'] != 0:
return False
else:
return True
def info(name, path=None):
'''
Returns information about a container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.info name
'''
cachekey = 'lxc.info.{0}{1}'.format(name, path)
try:
return __context__[cachekey]
except KeyError:
_ensure_exists(name, path=path)
cpath = get_root_path(path)
try:
conf_file = os.path.join(cpath, name, 'config')
except AttributeError:
conf_file = os.path.join(cpath, six.text_type(name), 'config')
if not os.path.isfile(conf_file):
raise CommandExecutionError(
'LXC config file {0} does not exist'.format(conf_file)
)
ret = {}
config = []
with salt.utils.files.fopen(conf_file) as fp_:
for line in fp_:
line = salt.utils.stringutils.to_unicode(line)
comps = [x.strip() for x in
line.split('#', 1)[0].strip().split('=', 1)]
if len(comps) == 2:
config.append(tuple(comps))
ifaces = []
current = None
for key, val in config:
if key == 'lxc.network.type':
current = {'type': val}
ifaces.append(current)
elif not current:
continue
elif key.startswith('lxc.network.'):
current[key.replace('lxc.network.', '', 1)] = val
if ifaces:
ret['nics'] = ifaces
ret['rootfs'] = next(
(x[1] for x in config if x[0] == 'lxc.rootfs'),
None
)
ret['state'] = state(name, path=path)
ret['ips'] = []
ret['public_ips'] = []
ret['private_ips'] = []
ret['public_ipv4_ips'] = []
ret['public_ipv6_ips'] = []
ret['private_ipv4_ips'] = []
ret['private_ipv6_ips'] = []
ret['ipv4_ips'] = []
ret['ipv6_ips'] = []
ret['size'] = None
ret['config'] = conf_file
if ret['state'] == 'running':
try:
limit = int(get_parameter(name, 'memory.limit_in_bytes'))
except (CommandExecutionError, TypeError, ValueError):
limit = 0
try:
usage = int(get_parameter(name, 'memory.usage_in_bytes'))
except (CommandExecutionError, TypeError, ValueError):
usage = 0
free = limit - usage
ret['memory_limit'] = limit
ret['memory_free'] = free
size = run_stdout(name, 'df /', path=path, python_shell=False)
# The size is the 2nd column of the last line
ret['size'] = size.splitlines()[-1].split()[1]
# First try iproute2
ip_cmd = run_all(
name, 'ip link show', path=path, python_shell=False)
if ip_cmd['retcode'] == 0:
ip_data = ip_cmd['stdout']
ip_cmd = run_all(
name, 'ip addr show', path=path, python_shell=False)
ip_data += '\n' + ip_cmd['stdout']
ip_data = salt.utils.network._interfaces_ip(ip_data)
else:
# That didn't work, try ifconfig
ip_cmd = run_all(
name, 'ifconfig', path=path, python_shell=False)
if ip_cmd['retcode'] == 0:
ip_data = \
salt.utils.network._interfaces_ifconfig(
ip_cmd['stdout'])
else:
# Neither was successful, give up
log.warning(
'Unable to run ip or ifconfig in container \'%s\'', name
)
ip_data = {}
ret['ipv4_ips'] = salt.utils.network.ip_addrs(
include_loopback=True,
interface_data=ip_data
)
ret['ipv6_ips'] = salt.utils.network.ip_addrs6(
include_loopback=True,
interface_data=ip_data
)
ret['ips'] = ret['ipv4_ips'] + ret['ipv6_ips']
for address in ret['ipv4_ips']:
if address == '127.0.0.1':
ret['private_ips'].append(address)
ret['private_ipv4_ips'].append(address)
elif salt.utils.cloud.is_public_ip(address):
ret['public_ips'].append(address)
ret['public_ipv4_ips'].append(address)
else:
ret['private_ips'].append(address)
ret['private_ipv4_ips'].append(address)
for address in ret['ipv6_ips']:
if address == '::1' or address.startswith('fe80'):
ret['private_ips'].append(address)
ret['private_ipv6_ips'].append(address)
else:
ret['public_ips'].append(address)
ret['public_ipv6_ips'].append(address)
for key in [x for x in ret if x == 'ips' or x.endswith('ips')]:
ret[key].sort(key=_ip_sort)
__context__[cachekey] = ret
return __context__[cachekey]
def set_password(name, users, password, encrypted=True, path=None):
'''
.. versionchanged:: 2015.5.0
Function renamed from ``set_pass`` to ``set_password``. Additionally,
this function now supports (and defaults to using) a password hash
instead of a plaintext password.
Set the password of one or more system users inside containers
users
Comma-separated list (or python list) of users to change password
password
Password to set for the specified user(s)
encrypted : True
If true, ``password`` must be a password hash. Set to ``False`` to set
a plaintext password (not recommended).
.. versionadded:: 2015.5.0
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.set_pass container-name root '$6$uJ2uAyLU$KoI67t8As/0fXtJOPcHKGXmUpcoYUcVR2K6x93walnShTCQvjRwq25yIkiCBOqgbfdKQSFnAo28/ek6716vEV1'
salt '*' lxc.set_pass container-name root foo encrypted=False
'''
def _bad_user_input():
raise SaltInvocationError('Invalid input for \'users\' parameter')
if not isinstance(users, list):
try:
users = users.split(',')
except AttributeError:
_bad_user_input()
if not users:
_bad_user_input()
failed_users = []
for user in users:
result = retcode(name,
'chpasswd{0}'.format(' -e' if encrypted else ''),
stdin=':'.join((user, password)),
python_shell=False,
path=path,
chroot_fallback=True,
output_loglevel='quiet')
if result != 0:
failed_users.append(user)
if failed_users:
raise CommandExecutionError(
'Password change failed for the following user(s): {0}'
.format(', '.join(failed_users))
)
return True
set_pass = salt.utils.functools.alias_function(set_password, 'set_pass')
def update_lxc_conf(name, lxc_conf, lxc_conf_unset, path=None):
'''
Edit LXC configuration options
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.update_lxc_conf ubuntu \\
lxc_conf="[{'network.ipv4.ip':'10.0.3.5'}]" \\
lxc_conf_unset="['lxc.utsname']"
'''
_ensure_exists(name, path=path)
cpath = get_root_path(path)
lxc_conf_p = os.path.join(cpath, name, 'config')
if not os.path.exists(lxc_conf_p):
raise SaltInvocationError(
'Configuration file {0} does not exist'.format(lxc_conf_p)
)
changes = {'edited': [], 'added': [], 'removed': []}
ret = {'changes': changes, 'result': True, 'comment': ''}
# do not use salt.utils.files.fopen !
with salt.utils.files.fopen(lxc_conf_p, 'r') as fic:
filtered_lxc_conf = []
for row in lxc_conf:
if not row:
continue
for conf in row:
filtered_lxc_conf.append((conf.strip(),
row[conf].strip()))
ret['comment'] = 'lxc.conf is up to date'
lines = []
orig_config = salt.utils.stringutils.to_unicode(fic.read())
for line in orig_config.splitlines():
if line.startswith('#') or not line.strip():
lines.append([line, ''])
else:
line = line.split('=')
index = line.pop(0)
val = (index.strip(), '='.join(line).strip())
if val not in lines:
lines.append(val)
for key, item in filtered_lxc_conf:
matched = False
for idx, line in enumerate(lines[:]):
if line[0] == key:
matched = True
lines[idx] = (key, item)
if '='.join(line[1:]).strip() != item.strip():
changes['edited'].append(
({line[0]: line[1:]}, {key: item}))
break
if not matched:
if (key, item) not in lines:
lines.append((key, item))
changes['added'].append({key: item})
dest_lxc_conf = []
# filter unset
if lxc_conf_unset:
for line in lines:
for opt in lxc_conf_unset:
if (
not line[0].startswith(opt) and
line not in dest_lxc_conf
):
dest_lxc_conf.append(line)
else:
changes['removed'].append(opt)
else:
dest_lxc_conf = lines
conf = ''
for key, val in dest_lxc_conf:
if not val:
conf += '{0}\n'.format(key)
else:
conf += '{0} = {1}\n'.format(key.strip(), val.strip())
conf_changed = conf != orig_config
chrono = datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S')
if conf_changed:
# DO NOT USE salt.utils.files.fopen here, i got (kiorky)
# problems with lxc configs which were wiped !
with salt.utils.files.fopen('{0}.{1}'.format(lxc_conf_p, chrono), 'w') as wfic:
wfic.write(salt.utils.stringutils.to_str(conf))
with salt.utils.files.fopen(lxc_conf_p, 'w') as wfic:
wfic.write(salt.utils.stringutils.to_str(conf))
ret['comment'] = 'Updated'
ret['result'] = True
if not any(changes[x] for x in changes):
# Ensure an empty changes dict if nothing was modified
ret['changes'] = {}
return ret
def set_dns(name, dnsservers=None, searchdomains=None, path=None):
'''
.. versionchanged:: 2015.5.0
The ``dnsservers`` and ``searchdomains`` parameters can now be passed
as a comma-separated list.
Update /etc/resolv.confo
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.set_dns ubuntu "['8.8.8.8', '4.4.4.4']"
'''
if dnsservers is None:
dnsservers = ['8.8.8.8', '4.4.4.4']
elif not isinstance(dnsservers, list):
try:
dnsservers = dnsservers.split(',')
except AttributeError:
raise SaltInvocationError(
'Invalid input for \'dnsservers\' parameter'
)
if searchdomains is None:
searchdomains = []
elif not isinstance(searchdomains, list):
try:
searchdomains = searchdomains.split(',')
except AttributeError:
raise SaltInvocationError(
'Invalid input for \'searchdomains\' parameter'
)
dns = ['nameserver {0}'.format(x) for x in dnsservers]
dns.extend(['search {0}'.format(x) for x in searchdomains])
dns = '\n'.join(dns) + '\n'
# we may be using resolvconf in the container
# We need to handle that case with care:
# - we create the resolv.conf runtime directory (the
# linked directory) as anyway it will be shadowed when the real
# runned tmpfs mountpoint will be mounted.
# ( /etc/resolv.conf -> ../run/resolvconf/resolv.conf)
# Indeed, it can save us in any other case (running, eg, in a
# bare chroot when repairing or preparing the container for
# operation.
# - We also teach resolvconf to use the aforementioned dns.
# - We finally also set /etc/resolv.conf in all cases
rstr = __salt__['test.random_hash']()
# no tmp here, apparmor won't let us execute !
script = '/sbin/{0}_dns.sh'.format(rstr)
DNS_SCRIPT = "\n".join([
# 'set -x',
'#!/usr/bin/env bash',
'if [ -h /etc/resolv.conf ];then',
' if [ "x$(readlink /etc/resolv.conf)"'
' = "x../run/resolvconf/resolv.conf" ];then',
' if [ ! -d /run/resolvconf/ ];then',
' mkdir -p /run/resolvconf',
' fi',
' cat > /etc/resolvconf/resolv.conf.d/head <<EOF',
dns,
'EOF',
'',
' fi',
'fi',
'cat > /etc/resolv.conf <<EOF',
dns,
'EOF',
''])
result = run_all(
name, 'tee {0}'.format(script), path=path,
stdin=DNS_SCRIPT, python_shell=True)
if result['retcode'] == 0:
result = run_all(
name, 'sh -c "chmod +x {0};{0}"'.format(script),
path=path, python_shell=True)
# blindly delete the setter file
run_all(name,
'sh -c \'if [ -f "{0}" ];then rm -f "{0}";fi\''.format(script),
path=path, python_shell=True)
if result['retcode'] != 0:
error = ('Unable to write to /etc/resolv.conf in container \'{0}\''
.format(name))
if result['stderr']:
error += ': {0}'.format(result['stderr'])
raise CommandExecutionError(error)
return True
def running_systemd(name, cache=True, path=None):
'''
Determine if systemD is running
path
path to the container parent
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.running_systemd ubuntu
'''
k = 'lxc.systemd.test.{0}{1}'.format(name, path)
ret = __context__.get(k, None)
if ret is None or not cache:
rstr = __salt__['test.random_hash']()
# no tmp here, apparmor won't let us execute !
script = '/sbin/{0}_testsystemd.sh'.format(rstr)
# ubuntu already had since trusty some bits of systemd but was
# still using upstart ...
# we need to be a bit more careful that just testing that systemd
# is present
_script = textwrap.dedent(
'''\
#!/usr/bin/env bash
set -x
if ! command -v systemctl 1>/dev/null 2>/dev/null;then exit 2;fi
for i in \\
/run/systemd/journal/dev-log\\
/run/systemd/journal/flushed\\
/run/systemd/journal/kernel-seqnum\\
/run/systemd/journal/socket\\
/run/systemd/journal/stdout\\
/var/run/systemd/journal/dev-log\\
/var/run/systemd/journal/flushed\\
/var/run/systemd/journal/kernel-seqnum\\
/var/run/systemd/journal/socket\\
/var/run/systemd/journal/stdout\\
;do\\
if test -e ${i};then exit 0;fi
done
if test -d /var/systemd/system;then exit 0;fi
exit 2
''')
result = run_all(
name, 'tee {0}'.format(script), path=path,
stdin=_script, python_shell=True)
if result['retcode'] == 0:
result = run_all(name,
'sh -c "chmod +x {0};{0}"'''.format(script),
path=path,
python_shell=True)
else:
raise CommandExecutionError(
'lxc {0} failed to copy initd tester'.format(name))
run_all(name,
'sh -c \'if [ -f "{0}" ];then rm -f "{0}";fi\''
''.format(script),
path=path,
ignore_retcode=True,
python_shell=True)
if result['retcode'] != 0:
error = ('Unable to determine if the container \'{0}\''
' was running systemd, assmuming it is not.'
''.format(name))
if result['stderr']:
error += ': {0}'.format(result['stderr'])
# only cache result if we got a known exit code
if result['retcode'] in (0, 2):
__context__[k] = ret = not result['retcode']
return ret
def systemd_running_state(name, path=None):
'''
Get the operational state of a systemd based container
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.systemd_running_state ubuntu
'''
try:
ret = run_all(name,
'systemctl is-system-running',
path=path,
ignore_retcode=True)['stdout']
except CommandExecutionError:
ret = ''
return ret
def test_sd_started_state(name, path=None):
'''
Test if a systemd container is fully started
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.test_sd_started_state ubuntu
'''
qstate = systemd_running_state(name, path=path)
if qstate in ('initializing', 'starting'):
return False
elif qstate == '':
return None
else:
return True
def test_bare_started_state(name, path=None):
'''
Test if a non systemd container is fully started
For now, it consists only to test if the container is attachable
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.test_bare_started_state ubuntu
'''
try:
ret = run_all(
name, 'ls', path=path, ignore_retcode=True
)['retcode'] == 0
except (CommandExecutionError,):
ret = None
return ret
def wait_started(name, path=None, timeout=300):
'''
Check that the system has fully inited
This is actually very important for systemD based containers
see https://github.com/saltstack/salt/issues/23847
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.wait_started ubuntu
'''
if not exists(name, path=path):
raise CommandExecutionError(
'Container {0} does does exists'.format(name))
if not state(name, path=path) == 'running':
raise CommandExecutionError(
'Container {0} is not running'.format(name))
ret = False
if running_systemd(name, path=path):
test_started = test_sd_started_state
logger = log.error
else:
test_started = test_bare_started_state
logger = log.debug
now = time.time()
expire = now + timeout
now = time.time()
started = test_started(name, path=path)
while time.time() < expire and not started:
time.sleep(0.3)
started = test_started(name, path=path)
if started is None:
logger(
'Assuming %s is started, although we failed to detect that'
' is fully started correctly', name)
ret = True
else:
ret = started
return ret
def _needs_install(name, path=None):
ret = 0
has_minion = retcode(name,
'which salt-minion',
path=path,
ignore_retcode=True)
# we assume that installing is when no minion is running
# but testing the executable presence is not enougth for custom
# installs where the bootstrap can do much more than installing
# the bare salt binaries.
if has_minion:
processes = run_stdout(name, "ps aux", path=path)
if 'salt-minion' not in processes:
ret = 1
else:
retcode(name, 'salt-call --local service.stop salt-minion')
else:
ret = 1
return ret
def bootstrap(name,
config=None,
approve_key=True,
install=True,
pub_key=None,
priv_key=None,
bootstrap_url=None,
force_install=False,
unconditional_install=False,
path=None,
bootstrap_delay=None,
bootstrap_args=None,
bootstrap_shell=None):
'''
Install and configure salt in a container.
config
Minion configuration options. By default, the ``master`` option is set
to the target host's master.
approve_key
Request a pre-approval of the generated minion key. Requires
that the salt-master be configured to either auto-accept all keys or
expect a signing request from the target host. Default: ``True``
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
pub_key
Explicit public key to pressed the minion with (optional).
This can be either a filepath or a string representing the key
priv_key
Explicit private key to pressed the minion with (optional).
This can be either a filepath or a string representing the key
bootstrap_delay
Delay in seconds between end of container creation and bootstrapping.
Useful when waiting for container to obtain a DHCP lease.
.. versionadded:: 2015.5.0
bootstrap_url
url, content or filepath to the salt bootstrap script
bootstrap_args
salt bootstrap script arguments
bootstrap_shell
shell to execute the script into
install
Whether to attempt a full installation of salt-minion if needed.
force_install
Force installation even if salt-minion is detected,
this is the way to run vendor bootstrap scripts even
if a salt minion is already present in the container
unconditional_install
Run the script even if the container seems seeded
CLI Examples:
.. code-block:: bash
salt 'minion' lxc.bootstrap container_name [config=config_data] \\
[approve_key=(True|False)] [install=(True|False)]
'''
wait_started(name, path=path)
if bootstrap_delay is not None:
try:
log.info('LXC %s: bootstrap_delay: %s', name, bootstrap_delay)
time.sleep(bootstrap_delay)
except TypeError:
# Bad input, but assume since a value was passed that
# a delay was desired, and sleep for 5 seconds
time.sleep(5)
c_info = info(name, path=path)
if not c_info:
return None
# default set here as we cannot set them
# in def as it can come from a chain of procedures.
if bootstrap_args:
# custom bootstrap args can be totally customized, and user could
# have inserted the placeholder for the config directory.
# For example, some salt bootstrap script do not use at all -c
if '{0}' not in bootstrap_args:
bootstrap_args += ' -c {0}'
else:
bootstrap_args = '-c {0}'
if not bootstrap_shell:
bootstrap_shell = 'sh'
orig_state = _ensure_running(name, path=path)
if not orig_state:
return orig_state
if not force_install:
needs_install = _needs_install(name, path=path)
else:
needs_install = True
seeded = retcode(name,
'test -e \'{0}\''.format(SEED_MARKER),
path=path,
chroot_fallback=True,
ignore_retcode=True) == 0
tmp = tempfile.mkdtemp()
if seeded and not unconditional_install:
ret = True
else:
ret = False
cfg_files = __salt__['seed.mkconfig'](
config, tmp=tmp, id_=name, approve_key=approve_key,
pub_key=pub_key, priv_key=priv_key)
if needs_install or force_install or unconditional_install:
if install:
rstr = __salt__['test.random_hash']()
configdir = '/var/tmp/.c_{0}'.format(rstr)
cmd = 'install -m 0700 -d {0}'.format(configdir)
if run_all(
name, cmd, path=path, python_shell=False
)['retcode'] != 0:
log.error('tmpdir %s creation failed %s', configdir, cmd)
return False
bs_ = __salt__['config.gather_bootstrap_script'](
bootstrap=bootstrap_url)
script = '/sbin/{0}_bootstrap.sh'.format(rstr)
copy_to(name, bs_, script, path=path)
result = run_all(name,
'sh -c "chmod +x {0}"'.format(script),
path=path,
python_shell=True)
copy_to(name, cfg_files['config'],
os.path.join(configdir, 'minion'),
path=path)
copy_to(name, cfg_files['privkey'],
os.path.join(configdir, 'minion.pem'),
path=path)
copy_to(name, cfg_files['pubkey'],
os.path.join(configdir, 'minion.pub'),
path=path)
bootstrap_args = bootstrap_args.format(configdir)
cmd = ('{0} {2} {1}'
.format(bootstrap_shell,
bootstrap_args.replace("'", "''"),
script))
# log ASAP the forged bootstrap command which can be wrapped
# out of the output in case of unexpected problem
log.info('Running %s in LXC container \'%s\'', cmd, name)
ret = retcode(name, cmd, output_loglevel='info',
path=path, use_vt=True) == 0
run_all(name,
'sh -c \'if [ -f "{0}" ];then rm -f "{0}";fi\''
''.format(script),
path=path,
ignore_retcode=True,
python_shell=True)
else:
ret = False
else:
minion_config = salt.config.minion_config(cfg_files['config'])
pki_dir = minion_config['pki_dir']
copy_to(name,
cfg_files['config'],
'/etc/salt/minion',
path=path)
copy_to(name,
cfg_files['privkey'],
os.path.join(pki_dir, 'minion.pem'),
path=path)
copy_to(name,
cfg_files['pubkey'],
os.path.join(pki_dir, 'minion.pub'),
path=path)
run(name,
'salt-call --local service.enable salt-minion',
path=path,
python_shell=False)
ret = True
shutil.rmtree(tmp)
if orig_state == 'stopped':
stop(name, path=path)
elif orig_state == 'frozen':
freeze(name, path=path)
# mark seeded upon successful install
if ret:
run(name,
'touch \'{0}\''.format(SEED_MARKER),
path=path,
python_shell=False)
return ret
def attachable(name, path=None):
'''
Return True if the named container can be attached to via the lxc-attach
command
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt 'minion' lxc.attachable ubuntu
'''
cachekey = 'lxc.attachable{0}{1}'.format(name, path)
try:
return __context__[cachekey]
except KeyError:
_ensure_exists(name, path=path)
# Can't use run() here because it uses attachable() and would
# endlessly recurse, resulting in a traceback
log.debug('Checking if LXC container %s is attachable', name)
cmd = 'lxc-attach'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' --clear-env -n {0} -- /usr/bin/env'.format(name)
result = __salt__['cmd.retcode'](cmd,
python_shell=False,
output_loglevel='quiet',
ignore_retcode=True) == 0
__context__[cachekey] = result
return __context__[cachekey]
def _run(name,
cmd,
output=None,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=None,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
Common logic for lxc.run functions
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
'''
orig_state = state(name, path=path)
try:
if attachable(name, path=path):
ret = __salt__['container_resource.run'](
name,
cmd,
path=path,
container_type=__virtualname__,
exec_driver=EXEC_DRIVER,
output=output,
no_start=no_start,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
ignore_retcode=ignore_retcode,
use_vt=use_vt,
keep_env=keep_env)
else:
if not chroot_fallback:
raise CommandExecutionError(
'{0} is not attachable.'.format(name))
rootfs = info(name, path=path).get('rootfs')
# Set context var to make cmd.run_chroot run cmd.run instead of
# cmd.run_all.
__context__['cmd.run_chroot.func'] = __salt__['cmd.run']
ret = __salt__['cmd.run_chroot'](rootfs,
cmd,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
ignore_retcode=ignore_retcode)
except Exception:
raise
finally:
# Make sure we honor preserve_state, even if there was an exception
new_state = state(name, path=path)
if preserve_state:
if orig_state == 'stopped' and new_state != 'stopped':
stop(name, path=path)
elif orig_state == 'frozen' and new_state != 'frozen':
freeze(name, start=True, path=path)
if output in (None, 'all'):
return ret
else:
return ret[output]
def run(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.8.0
Run :mod:`cmd.run <salt.modules.cmdmod.run>` within a container
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed in stderr if the command being run
does not exist. If no output is returned using this function, try using
:mod:`lxc.run_stderr <salt.modules.lxc.run_stderr>` or
:mod:`lxc.run_all <salt.modules.lxc.run_all>`.
name
Name of the container in which to run the command
cmd
Command to run
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console. Assumes
``output=all``.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
CLI Example:
.. code-block:: bash
salt myminion lxc.run mycontainer 'ifconfig -a'
'''
return _run(name,
cmd,
path=path,
output=None,
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def run_stdout(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.5.0
Run :mod:`cmd.run_stdout <salt.modules.cmdmod.run_stdout>` within a container
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed in stderr if the command being run
does not exist. If no output is returned using this function, try using
:mod:`lxc.run_stderr <salt.modules.lxc.run_stderr>` or
:mod:`lxc.run_all <salt.modules.lxc.run_all>`.
name
Name of the container in which to run the command
cmd
Command to run
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console
``output=all``.
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
CLI Example:
.. code-block:: bash
salt myminion lxc.run_stdout mycontainer 'ifconfig -a'
'''
return _run(name,
cmd,
path=path,
output='stdout',
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def run_stderr(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.5.0
Run :mod:`cmd.run_stderr <salt.modules.cmdmod.run_stderr>` within a container
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed if the command being run does not
exist.
name
Name of the container in which to run the command
cmd
Command to run
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console
``output=all``.
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
CLI Example:
.. code-block:: bash
salt myminion lxc.run_stderr mycontainer 'ip addr show'
'''
return _run(name,
cmd,
path=path,
output='stderr',
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def retcode(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.5.0
Run :mod:`cmd.retcode <salt.modules.cmdmod.retcode>` within a container
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed in stderr if the command being run
does not exist. If the retcode is nonzero and not what was expected,
try using :mod:`lxc.run_stderr <salt.modules.lxc.run_stderr>`
or :mod:`lxc.run_all <salt.modules.lxc.run_all>`.
name
Name of the container in which to run the command
cmd
Command to run
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console
``output=all``.
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
CLI Example:
.. code-block:: bash
salt myminion lxc.retcode mycontainer 'ip addr show'
'''
return _run(name,
cmd,
output='retcode',
path=path,
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def run_all(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.5.0
Run :mod:`cmd.run_all <salt.modules.cmdmod.run_all>` within a container
.. note::
While the command is run within the container, it is initiated from the
host. Therefore, the PID in the return dict is from the host, not from
the container.
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed in stderr if the command being run
does not exist.
name
Name of the container in which to run the command
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
cmd
Command to run
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console
``output=all``.
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
CLI Example:
.. code-block:: bash
salt myminion lxc.run_all mycontainer 'ip addr show'
'''
return _run(name,
cmd,
output='all',
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
path=path,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def _get_md5(name, path):
'''
Get the MD5 checksum of a file from a container
'''
output = run_stdout(name, 'md5sum "{0}"'.format(path),
chroot_fallback=True,
ignore_retcode=True)
try:
return output.split()[0]
except IndexError:
# Destination file does not exist or could not be accessed
return None
def copy_to(name, source, dest, overwrite=False, makedirs=False, path=None):
'''
.. versionchanged:: 2015.8.0
Function renamed from ``lxc.cp`` to ``lxc.copy_to`` for consistency
with other container types. ``lxc.cp`` will continue to work, however.
For versions 2015.2.x and earlier, use ``lxc.cp``.
Copy a file or directory from the host into a container
name
Container name
source
File to be copied to the container
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
dest
Destination on the container. Must be an absolute path.
.. versionchanged:: 2015.5.0
If the destination is a directory, the file will be copied into
that directory.
overwrite : False
Unless this option is set to ``True``, then if a file exists at the
location specified by the ``dest`` argument, an error will be raised.
.. versionadded:: 2015.8.0
makedirs : False
Create the parent directory on the container if it does not already
exist.
.. versionadded:: 2015.5.0
CLI Example:
.. code-block:: bash
salt 'minion' lxc.copy_to /tmp/foo /root/foo
salt 'minion' lxc.cp /tmp/foo /root/foo
'''
_ensure_running(name, no_start=True, path=path)
return __salt__['container_resource.copy_to'](
name,
source,
dest,
container_type=__virtualname__,
path=path,
exec_driver=EXEC_DRIVER,
overwrite=overwrite,
makedirs=makedirs)
cp = salt.utils.functools.alias_function(copy_to, 'cp')
def read_conf(conf_file, out_format='simple'):
'''
Read in an LXC configuration file. By default returns a simple, unsorted
dict, but can also return a more detailed structure including blank lines
and comments.
out_format:
set to 'simple' if you need the old and unsupported behavior.
This won't support the multiple lxc values (eg: multiple network nics)
CLI Examples:
.. code-block:: bash
salt 'minion' lxc.read_conf /etc/lxc/mycontainer.conf
salt 'minion' lxc.read_conf /etc/lxc/mycontainer.conf out_format=commented
'''
ret_commented = []
ret_simple = {}
with salt.utils.files.fopen(conf_file, 'r') as fp_:
for line in salt.utils.data.decode(fp_.readlines()):
if '=' not in line:
ret_commented.append(line)
continue
comps = line.split('=')
value = '='.join(comps[1:]).strip()
comment = None
if value.strip().startswith('#'):
vcomps = value.strip().split('#')
value = vcomps[1].strip()
comment = '#'.join(vcomps[1:]).strip()
ret_commented.append({comps[0].strip(): {
'value': value,
'comment': comment,
}})
else:
ret_commented.append({comps[0].strip(): value})
ret_simple[comps[0].strip()] = value
if out_format == 'simple':
return ret_simple
return ret_commented
def write_conf(conf_file, conf):
'''
Write out an LXC configuration file
This is normally only used internally. The format of the data structure
must match that which is returned from ``lxc.read_conf()``, with
``out_format`` set to ``commented``.
An example might look like:
.. code-block:: python
[
{'lxc.utsname': '$CONTAINER_NAME'},
'# This is a commented line\\n',
'\\n',
{'lxc.mount': '$CONTAINER_FSTAB'},
{'lxc.rootfs': {'comment': 'This is another test',
'value': 'This is another test'}},
'\\n',
{'lxc.network.type': 'veth'},
{'lxc.network.flags': 'up'},
{'lxc.network.link': 'br0'},
{'lxc.network.mac': '$CONTAINER_MACADDR'},
{'lxc.network.ipv4': '$CONTAINER_IPADDR'},
{'lxc.network.name': '$CONTAINER_DEVICENAME'},
]
CLI Example:
.. code-block:: bash
salt 'minion' lxc.write_conf /etc/lxc/mycontainer.conf \\
out_format=commented
'''
if not isinstance(conf, list):
raise SaltInvocationError('Configuration must be passed as a list')
# construct the content prior to write to the file
# to avoid half written configs
content = ''
for line in conf:
if isinstance(line, (six.text_type, six.string_types)):
content += line
elif isinstance(line, dict):
for key in list(line.keys()):
out_line = None
if isinstance(
line[key],
(six.text_type, six.string_types, six.integer_types, float)
):
out_line = ' = '.join((key, "{0}".format(line[key])))
elif isinstance(line[key], dict):
out_line = ' = '.join((key, line[key]['value']))
if 'comment' in line[key]:
out_line = ' # '.join((out_line, line[key]['comment']))
if out_line:
content += out_line
content += '\n'
with salt.utils.files.fopen(conf_file, 'w') as fp_:
fp_.write(salt.utils.stringutils.to_str(content))
return {}
def edit_conf(conf_file,
out_format='simple',
read_only=False,
lxc_config=None,
**kwargs):
'''
Edit an LXC configuration file. If a setting is already present inside the
file, its value will be replaced. If it does not exist, it will be appended
to the end of the file. Comments and blank lines will be kept in-tact if
they already exist in the file.
out_format:
Set to simple if you need backward compatibility (multiple items for a
simple key is not supported)
read_only:
return only the edited configuration without applying it
to the underlying lxc configuration file
lxc_config:
List of dict containning lxc configuration items
For network configuration, you also need to add the device it belongs
to, otherwise it will default to eth0.
Also, any change to a network parameter will result in the whole
network reconfiguration to avoid mismatchs, be aware of that !
After the file is edited, its contents will be returned. By default, it
will be returned in ``simple`` format, meaning an unordered dict (which
may not represent the actual file order). Passing in an ``out_format`` of
``commented`` will return a data structure which accurately represents the
order and content of the file.
CLI Example:
.. code-block:: bash
salt 'minion' lxc.edit_conf /etc/lxc/mycontainer.conf \\
out_format=commented lxc.network.type=veth
salt 'minion' lxc.edit_conf /etc/lxc/mycontainer.conf \\
out_format=commented \\
lxc_config="[{'lxc.network.name': 'eth0', \\
'lxc.network.ipv4': '1.2.3.4'},
{'lxc.network.name': 'eth2', \\
'lxc.network.ipv4': '1.2.3.5',\\
'lxc.network.gateway': '1.2.3.1'}]"
'''
data = []
try:
conf = read_conf(conf_file, out_format=out_format)
except Exception:
conf = []
if not lxc_config:
lxc_config = []
lxc_config = copy.deepcopy(lxc_config)
# search if we want to access net config
# in that case, we will replace all the net configuration
net_config = []
for lxc_kws in lxc_config + [kwargs]:
net_params = {}
for kwarg in [a for a in lxc_kws]:
if kwarg.startswith('__'):
continue
if kwarg.startswith('lxc.network.'):
net_params[kwarg] = lxc_kws[kwarg]
lxc_kws.pop(kwarg, None)
if net_params:
net_config.append(net_params)
nic_opts = salt.utils.odict.OrderedDict()
for params in net_config:
dev = params.get('lxc.network.name', DEFAULT_NIC)
dev_opts = nic_opts.setdefault(dev, salt.utils.odict.OrderedDict())
for param in params:
opt = param.replace('lxc.network.', '')
opt = {'hwaddr': 'mac'}.get(opt, opt)
dev_opts[opt] = params[param]
net_changes = []
if nic_opts:
net_changes = _config_list(conf, only_net=True,
**{'network_profile': DEFAULT_NIC,
'nic_opts': nic_opts})
if net_changes:
lxc_config.extend(net_changes)
for line in conf:
if not isinstance(line, dict):
data.append(line)
continue
else:
for key in list(line.keys()):
val = line[key]
if net_changes and key.startswith('lxc.network.'):
continue
found = False
for ix in range(len(lxc_config)):
kw = lxc_config[ix]
if key in kw:
found = True
data.append({key: kw[key]})
del kw[key]
if not found:
data.append({key: val})
for lxc_kws in lxc_config:
for kwarg in lxc_kws:
data.append({kwarg: lxc_kws[kwarg]})
if read_only:
return data
write_conf(conf_file, data)
return read_conf(conf_file, out_format)
def reboot(name, path=None):
'''
Reboot a container.
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Examples:
.. code-block:: bash
salt 'minion' lxc.reboot myvm
'''
ret = {'result': True,
'changes': {},
'comment': '{0} rebooted'.format(name)}
does_exist = exists(name, path=path)
if does_exist and (state(name, path=path) == 'running'):
try:
stop(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
ret['result'] = False
return ret
if does_exist and (state(name, path=path) != 'running'):
try:
start(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
ret['result'] = False
return ret
ret['changes'][name] = 'rebooted'
return ret
def reconfigure(name,
cpu=None,
cpuset=None,
cpushare=None,
memory=None,
profile=None,
network_profile=None,
nic_opts=None,
bridge=None,
gateway=None,
autostart=None,
utsname=None,
rootfs=None,
path=None,
**kwargs):
'''
Reconfigure a container.
This only applies to a few property
name
Name of the container.
utsname
utsname of the container.
.. versionadded:: 2016.3.0
rootfs
rootfs of the container.
.. versionadded:: 2016.3.0
cpu
Select a random number of cpu cores and assign it to the cpuset, if the
cpuset option is set then this option will be ignored
cpuset
Explicitly define the cpus this container will be bound to
cpushare
cgroups cpu shares.
autostart
autostart container on reboot
memory
cgroups memory limit, in MB.
(0 for nolimit, None for old default 1024MB)
gateway
the ipv4 gateway to use
the default does nothing more than lxcutils does
bridge
the bridge to use
the default does nothing more than lxcutils does
nic
Network interfaces profile (defined in config or pillar).
nic_opts
Extra options for network interfaces, will override
``{"eth0": {"mac": "aa:bb:cc:dd:ee:ff", "ipv4": "10.1.1.1", "ipv6": "2001:db8::ff00:42:8329"}}``
or
``{"eth0": {"mac": "aa:bb:cc:dd:ee:ff", "ipv4": "10.1.1.1/24", "ipv6": "2001:db8::ff00:42:8329"}}``
path
path to the container parent
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt-call -lall mc_lxc_fork.reconfigure foobar nic_opts="{'eth1': {'mac': '00:16:3e:dd:ee:44'}}" memory=4
'''
changes = {}
cpath = get_root_path(path)
path = os.path.join(cpath, name, 'config')
ret = {'name': name,
'comment': 'config for {0} up to date'.format(name),
'result': True,
'changes': changes}
profile = get_container_profile(copy.deepcopy(profile))
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, _marker)
profile_match = profile.pop(key, default)
# let kwarg overrides be the preferred choice
if kw_overrides_match is _marker:
return profile_match
return kw_overrides_match
if nic_opts is not None and not network_profile:
network_profile = DEFAULT_NIC
if autostart is not None:
autostart = select('autostart', autostart)
else:
autostart = 'keep'
if not utsname:
utsname = select('utsname', utsname)
if os.path.exists(path):
old_chunks = read_conf(path, out_format='commented')
make_kw = salt.utils.odict.OrderedDict([
('utsname', utsname),
('rootfs', rootfs),
('autostart', autostart),
('cpu', cpu),
('gateway', gateway),
('cpuset', cpuset),
('cpushare', cpushare),
('network_profile', network_profile),
('nic_opts', nic_opts),
('bridge', bridge)])
# match 0 and none as memory = 0 in lxc config is harmful
if memory:
make_kw['memory'] = memory
kw = salt.utils.odict.OrderedDict()
for key, val in six.iteritems(make_kw):
if val is not None:
kw[key] = val
new_cfg = _config_list(conf_tuples=old_chunks, **kw)
if new_cfg:
edit_conf(path, out_format='commented', lxc_config=new_cfg)
chunks = read_conf(path, out_format='commented')
if old_chunks != chunks:
ret['comment'] = '{0} lxc config updated'.format(name)
if state(name, path=path) == 'running':
cret = reboot(name, path=path)
ret['result'] = cret['result']
return ret
def apply_network_profile(name, network_profile, nic_opts=None, path=None):
'''
.. versionadded:: 2015.5.0
Apply a network profile to a container
network_profile
profile name or default values (dict)
nic_opts
values to override in defaults (dict)
indexed by nic card names
path
path to the container parent
.. versionadded:: 2015.8.0
CLI Examples:
.. code-block:: bash
salt 'minion' lxc.apply_network_profile web1 centos
salt 'minion' lxc.apply_network_profile web1 centos \\
nic_opts="{'eth0': {'mac': 'xx:xx:xx:xx:xx:xx'}}"
salt 'minion' lxc.apply_network_profile web1 \\
"{'eth0': {'mac': 'xx:xx:xx:xx:xx:yy'}}"
nic_opts="{'eth0': {'mac': 'xx:xx:xx:xx:xx:xx'}}"
The special case to disable use of ethernet nics:
.. code-block:: bash
salt 'minion' lxc.apply_network_profile web1 centos \\
"{eth0: {disable: true}}"
'''
cpath = get_root_path(path)
cfgpath = os.path.join(cpath, name, 'config')
before = []
with salt.utils.files.fopen(cfgpath, 'r') as fp_:
for line in fp_:
before.append(line)
lxcconfig = _LXCConfig(name=name, path=path)
old_net = lxcconfig._filter_data('lxc.network')
network_params = {}
for param in _network_conf(
conf_tuples=old_net,
network_profile=network_profile, nic_opts=nic_opts
):
network_params.update(param)
if network_params:
edit_conf(cfgpath, out_format='commented', **network_params)
after = []
with salt.utils.files.fopen(cfgpath, 'r') as fp_:
for line in fp_:
after.append(line)
diff = ''
for line in difflib.unified_diff(before,
after,
fromfile='before',
tofile='after'):
diff += line
return diff
def get_pid(name, path=None):
'''
Returns a container pid.
Throw an exception if the container isn't running.
CLI Example:
.. code-block:: bash
salt '*' lxc.get_pid name
'''
if name not in list_(limit='running', path=path):
raise CommandExecutionError('Container {0} is not running, can\'t determine PID'.format(name))
info = __salt__['cmd.run']('lxc-info -n {0}'.format(name)).split("\n")
pid = [line.split(':')[1].strip() for line in info if re.match(r'\s*PID', line)][0]
return pid
def add_veth(name, interface_name, bridge=None, path=None):
'''
Add a veth to a container.
Note : this function doesn't update the container config, just add the interface at runtime
name
Name of the container
interface_name
Name of the interface in the container
bridge
Name of the bridge to attach the interface to (facultative)
CLI Examples:
.. code-block:: bash
salt '*' lxc.add_veth container_name eth1 br1
salt '*' lxc.add_veth container_name eth1
'''
# Get container init PID
pid = get_pid(name, path=path)
# Generate a ramdom string for veth and ensure that is isn't present on the system
while True:
random_veth = 'veth'+''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(6))
if random_veth not in __salt__['network.interfaces']().keys():
break
# Check prerequisites
if not __salt__['file.directory_exists']('/var/run/'):
raise CommandExecutionError('Directory /var/run required for lxc.add_veth doesn\'t exists')
if not __salt__['file.file_exists']('/proc/{0}/ns/net'.format(pid)):
raise CommandExecutionError('Proc file for container {0} network namespace doesn\'t exists'.format(name))
if not __salt__['file.directory_exists']('/var/run/netns'):
__salt__['file.mkdir']('/var/run/netns')
# Ensure that the symlink is up to date (change on container restart)
if __salt__['file.is_link']('/var/run/netns/{0}'.format(name)):
__salt__['file.remove']('/var/run/netns/{0}'.format(name))
__salt__['file.symlink']('/proc/{0}/ns/net'.format(pid), '/var/run/netns/{0}'.format(name))
# Ensure that interface doesn't exists
interface_exists = 0 == __salt__['cmd.retcode']('ip netns exec {netns} ip address list {interface}'.format(
netns=name,
interface=interface_name
))
if interface_exists:
raise CommandExecutionError('Interface {interface} already exists in {container}'.format(
interface=interface_name,
container=name
))
# Create veth and bring it up
if __salt__['cmd.retcode']('ip link add name {veth} type veth peer name {veth}_c'.format(veth=random_veth)) != 0:
raise CommandExecutionError('Error while creating the veth pair {0}'.format(random_veth))
if __salt__['cmd.retcode']('ip link set dev {0} up'.format(random_veth)) != 0:
raise CommandExecutionError('Error while bringing up host-side veth {0}'.format(random_veth))
# Attach it to the container
attached = 0 == __salt__['cmd.retcode']('ip link set dev {veth}_c netns {container} name {interface_name}'.format(
veth=random_veth,
container=name,
interface_name=interface_name
))
if not attached:
raise CommandExecutionError('Error while attaching the veth {veth} to container {container}'.format(
veth=random_veth,
container=name
))
__salt__['file.remove']('/var/run/netns/{0}'.format(name))
if bridge is not None:
__salt__['bridge.addif'](bridge, random_veth)
|
saltstack/salt
|
salt/modules/lxc.py
|
templates
|
python
|
def templates():
'''
.. versionadded:: 2015.5.0
List the available LXC template scripts installed on the minion
CLI Examples:
.. code-block:: bash
salt myminion lxc.templates
'''
try:
template_scripts = os.listdir('/usr/share/lxc/templates')
except OSError:
return []
else:
return [x[4:] for x in template_scripts if x.startswith('lxc-')]
|
.. versionadded:: 2015.5.0
List the available LXC template scripts installed on the minion
CLI Examples:
.. code-block:: bash
salt myminion lxc.templates
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/lxc.py#L1717-L1734
| null |
# -*- coding: utf-8 -*-
'''
Control Linux Containers via Salt
:depends: lxc package for distribution
lxc >= 1.0 (even beta alpha) is required
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import datetime
import copy
import string
import textwrap
import difflib
import logging
import tempfile
import os
import pipes
import time
import shutil
import re
import random
# Import salt libs
import salt.utils.args
import salt.utils.cloud
import salt.utils.data
import salt.utils.dictupdate
import salt.utils.files
import salt.utils.functools
import salt.utils.hashutils
import salt.utils.network
import salt.utils.odict
import salt.utils.path
import salt.utils.stringutils
from salt.exceptions import CommandExecutionError, SaltInvocationError
import salt.config
from salt.utils.versions import LooseVersion as _LooseVersion
# Import 3rd-party libs
from salt.ext import six
# pylint: disable=import-error,no-name-in-module
from salt.ext.six.moves import range # pylint: disable=redefined-builtin
from salt.ext.six.moves.urllib.parse import urlparse as _urlparse
# pylint: enable=import-error,no-name-in-module
# Set up logging
log = logging.getLogger(__name__)
# Don't shadow built-in's.
__func_alias__ = {
'list_': 'list',
'ls_': 'ls'
}
__virtualname__ = 'lxc'
DEFAULT_NIC = 'eth0'
DEFAULT_BR = 'br0'
SEED_MARKER = '/lxc.initial_seed'
EXEC_DRIVER = 'lxc-attach'
DEFAULT_PATH = '/var/lib/lxc'
_marker = object()
def __virtual__():
if salt.utils.path.which('lxc-start'):
return __virtualname__
# To speed up the whole thing, we decided to not use the
# subshell way and assume things are in place for lxc
# Discussion made by @kiorky and @thatch45
# lxc-version presence is not sufficient, in lxc1.0 alpha
# (precise backports), we have it and it is sufficient
# for the module to execute.
# elif salt.utils.path.which('lxc-version'):
# passed = False
# try:
# passed = subprocess.check_output(
# 'lxc-version').split(':')[1].strip() >= '1.0'
# except Exception:
# pass
# if not passed:
# log.warning('Support for lxc < 1.0 may be incomplete.')
# return 'lxc'
# return False
#
return (False, 'The lxc execution module cannot be loaded: the lxc-start binary is not in the path.')
def get_root_path(path):
'''
Get the configured lxc root for containers
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.get_root_path
'''
if not path:
path = __opts__.get('lxc.root_path', DEFAULT_PATH)
return path
def version():
'''
Return the actual lxc client version
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.version
'''
k = 'lxc.version'
if not __context__.get(k, None):
cversion = __salt__['cmd.run_all']('lxc-info --version')
if not cversion['retcode']:
ver = _LooseVersion(cversion['stdout'])
if ver < _LooseVersion('1.0'):
raise CommandExecutionError('LXC should be at least 1.0')
__context__[k] = "{0}".format(ver)
return __context__.get(k, None)
def _clear_context():
'''
Clear any lxc variables set in __context__
'''
for var in [x for x in __context__ if x.startswith('lxc.')]:
log.trace('Clearing __context__[\'%s\']', var)
__context__.pop(var, None)
def _ip_sort(ip):
'''Ip sorting'''
idx = '001'
if ip == '127.0.0.1':
idx = '200'
if ip == '::1':
idx = '201'
elif '::' in ip:
idx = '100'
return '{0}___{1}'.format(idx, ip)
def search_lxc_bridges():
'''
Search which bridges are potentially available as LXC bridges
CLI Example:
.. code-block:: bash
salt '*' lxc.search_lxc_bridges
'''
bridges = __context__.get('lxc.bridges', None)
# either match not yet called or no bridges were found
# to handle the case where lxc was not installed on the first
# call
if not bridges:
bridges = set()
running_bridges = set()
bridges.add(DEFAULT_BR)
try:
output = __salt__['cmd.run_all']('brctl show')
for line in output['stdout'].splitlines()[1:]:
if not line.startswith(' '):
running_bridges.add(line.split()[0].strip())
except (SaltInvocationError, CommandExecutionError):
pass
for ifc, ip in six.iteritems(
__grains__.get('ip_interfaces', {})
):
if ifc in running_bridges:
bridges.add(ifc)
elif os.path.exists(
'/sys/devices/virtual/net/{0}/bridge'.format(ifc)
):
bridges.add(ifc)
bridges = list(bridges)
# if we found interfaces that have lxc in their names
# we filter them as being the potential lxc bridges
# we also try to default on br0 on other cases
def sort_bridges(a):
pref = 'z'
if 'lxc' in a:
pref = 'a'
elif 'br0' == a:
pref = 'c'
return '{0}_{1}'.format(pref, a)
bridges.sort(key=sort_bridges)
__context__['lxc.bridges'] = bridges
return bridges
def search_lxc_bridge():
'''
Search the first bridge which is potentially available as LXC bridge
CLI Example:
.. code-block:: bash
salt '*' lxc.search_lxc_bridge
'''
return search_lxc_bridges()[0]
def _get_salt_config(config, **kwargs):
if not config:
config = kwargs.get('minion', {})
if not config:
config = {}
config.setdefault('master',
kwargs.get('master',
__opts__.get('master',
__opts__['id'])))
config.setdefault(
'master_port',
kwargs.get('master_port',
__opts__.get('master_port',
__opts__.get('ret_port',
__opts__.get('4506')))))
if not config['master']:
config = {}
return config
def cloud_init_interface(name, vm_=None, **kwargs):
'''
Interface between salt.cloud.lxc driver and lxc.init
``vm_`` is a mapping of vm opts in the salt.cloud format
as documented for the lxc driver.
This can be used either:
- from the salt cloud driver
- because you find the argument to give easier here
than using directly lxc.init
.. warning::
BE REALLY CAREFUL CHANGING DEFAULTS !!!
IT'S A RETRO COMPATIBLE INTERFACE WITH
THE SALT CLOUD DRIVER (ask kiorky).
name
name of the lxc container to create
pub_key
public key to preseed the minion with.
Can be the keycontent or a filepath
priv_key
private key to preseed the minion with.
Can be the keycontent or a filepath
path
path to the container parent directory (default: /var/lib/lxc)
.. versionadded:: 2015.8.0
profile
:ref:`profile <tutorial-lxc-profiles-container>` selection
network_profile
:ref:`network profile <tutorial-lxc-profiles-network>` selection
nic_opts
per interface settings compatibles with
network profile (ipv4/ipv6/link/gateway/mac/netmask)
eg::
- {'eth0': {'mac': '00:16:3e:01:29:40',
'gateway': None, (default)
'link': 'br0', (default)
'gateway': None, (default)
'netmask': '', (default)
'ip': '22.1.4.25'}}
unconditional_install
given to lxc.bootstrap (see relative doc)
force_install
given to lxc.bootstrap (see relative doc)
config
any extra argument for the salt minion config
dnsservers
list of DNS servers to set inside the container
dns_via_dhcp
do not set the dns servers, let them be set by the dhcp.
autostart
autostart the container at boot time
password
administrative password for the container
bootstrap_delay
delay before launching bootstrap script at Container init
.. warning::
Legacy but still supported options:
from_container
which container we use as a template
when running lxc.clone
image
which template do we use when we
are using lxc.create. This is the default
mode unless you specify something in from_container
backing
which backing store to use.
Values can be: overlayfs, dir(default), lvm, zfs, brtfs
fstype
When using a blockdevice level backing store,
which filesystem to use on
size
When using a blockdevice level backing store,
which size for the filesystem to use on
snapshot
Use snapshot when cloning the container source
vgname
if using LVM: vgname
lvname
if using LVM: lvname
thinpool:
if using LVM: thinpool
ip
ip for the primary nic
mac
mac address for the primary nic
netmask
netmask for the primary nic (24)
= ``vm_.get('netmask', '24')``
bridge
bridge for the primary nic (lxcbr0)
gateway
network gateway for the container
additional_ips
additional ips which will be wired on the main bridge (br0)
which is connected to internet.
Be aware that you may use manual virtual mac addresses
providen by you provider (online, ovh, etc).
This is a list of mappings {ip: '', mac: '', netmask:''}
Set gateway to None and an interface with a gateway
to escape from another interface that eth0.
eg::
- {'mac': '00:16:3e:01:29:40',
'gateway': None, (default)
'link': 'br0', (default)
'netmask': '', (default)
'ip': '22.1.4.25'}
users
administrative users for the container
default: [root] and [root, ubuntu] on ubuntu
default_nic
name of the first interface, you should
really not override this
CLI Example:
.. code-block:: bash
salt '*' lxc.cloud_init_interface foo
'''
if vm_ is None:
vm_ = {}
vm_ = copy.deepcopy(vm_)
vm_ = salt.utils.dictupdate.update(vm_, kwargs)
profile_data = copy.deepcopy(
vm_.get('lxc_profile',
vm_.get('profile', {})))
if not isinstance(profile_data, (dict, six.string_types)):
profile_data = {}
profile = get_container_profile(profile_data)
def _cloud_get(k, default=None):
return vm_.get(k, profile.get(k, default))
if name is None:
name = vm_['name']
# if we are on ubuntu, default to ubuntu
default_template = ''
if __grains__.get('os', '') in ['Ubuntu']:
default_template = 'ubuntu'
image = _cloud_get('image')
if not image:
_cloud_get('template', default_template)
backing = _cloud_get('backing', 'dir')
if image:
profile['template'] = image
vgname = _cloud_get('vgname', None)
if vgname:
profile['vgname'] = vgname
if backing:
profile['backing'] = backing
snapshot = _cloud_get('snapshot', False)
autostart = bool(_cloud_get('autostart', True))
dnsservers = _cloud_get('dnsservers', [])
dns_via_dhcp = _cloud_get('dns_via_dhcp', True)
password = _cloud_get('password', 's3cr3t')
password_encrypted = _cloud_get('password_encrypted', False)
fstype = _cloud_get('fstype', None)
lvname = _cloud_get('lvname', None)
thinpool = _cloud_get('thinpool', None)
pub_key = _cloud_get('pub_key', None)
priv_key = _cloud_get('priv_key', None)
size = _cloud_get('size', '20G')
script = _cloud_get('script', None)
script_args = _cloud_get('script_args', None)
users = _cloud_get('users', None)
if users is None:
users = []
ssh_username = _cloud_get('ssh_username', None)
if ssh_username and (ssh_username not in users):
users.append(ssh_username)
network_profile = _cloud_get('network_profile', None)
nic_opts = kwargs.get('nic_opts', None)
netmask = _cloud_get('netmask', '24')
path = _cloud_get('path', None)
bridge = _cloud_get('bridge', None)
gateway = _cloud_get('gateway', None)
unconditional_install = _cloud_get('unconditional_install', False)
force_install = _cloud_get('force_install', True)
config = _get_salt_config(_cloud_get('config', {}), **vm_)
default_nic = _cloud_get('default_nic', DEFAULT_NIC)
# do the interface with lxc.init mainly via nic_opts
# to avoid extra and confusing extra use cases.
if not isinstance(nic_opts, dict):
nic_opts = salt.utils.odict.OrderedDict()
# have a reference to the default nic
eth0 = nic_opts.setdefault(default_nic,
salt.utils.odict.OrderedDict())
# lxc config is based of ifc order, be sure to use odicts.
if not isinstance(nic_opts, salt.utils.odict.OrderedDict):
bnic_opts = salt.utils.odict.OrderedDict()
bnic_opts.update(nic_opts)
nic_opts = bnic_opts
gw = None
# legacy salt.cloud scheme for network interfaces settings support
bridge = _cloud_get('bridge', None)
ip = _cloud_get('ip', None)
mac = _cloud_get('mac', None)
if ip:
fullip = ip
if netmask:
fullip += '/{0}'.format(netmask)
eth0['ipv4'] = fullip
if mac is not None:
eth0['mac'] = mac
for ix, iopts in enumerate(_cloud_get("additional_ips", [])):
ifh = "eth{0}".format(ix+1)
ethx = nic_opts.setdefault(ifh, {})
if gw is None:
gw = iopts.get('gateway', ethx.get('gateway', None))
if gw:
# only one and only one default gateway is allowed !
eth0.pop('gateway', None)
gateway = None
# even if the gateway if on default "eth0" nic
# and we popped it will work
# as we reinject or set it here.
ethx['gateway'] = gw
elink = iopts.get('link', ethx.get('link', None))
if elink:
ethx['link'] = elink
# allow dhcp
aip = iopts.get('ipv4', iopts.get('ip', None))
if aip:
ethx['ipv4'] = aip
nm = iopts.get('netmask', '')
if nm:
ethx['ipv4'] += '/{0}'.format(nm)
for i in ('mac', 'hwaddr'):
if i in iopts:
ethx['mac'] = iopts[i]
break
if 'mac' not in ethx:
ethx['mac'] = salt.utils.network.gen_mac()
# last round checking for unique gateway and such
gw = None
for ethx in [a for a in nic_opts]:
ndata = nic_opts[ethx]
if gw:
ndata.pop('gateway', None)
if 'gateway' in ndata:
gw = ndata['gateway']
gateway = None
# only use a default bridge / gateway if we configured them
# via the legacy salt cloud configuration style.
# On other cases, we should rely on settings provided by the new
# salt lxc network profile style configuration which can
# be also be overridden or a per interface basis via the nic_opts dict.
if bridge:
eth0['link'] = bridge
if gateway:
eth0['gateway'] = gateway
#
lxc_init_interface = {}
lxc_init_interface['name'] = name
lxc_init_interface['config'] = config
lxc_init_interface['memory'] = _cloud_get('memory', 0) # nolimit
lxc_init_interface['pub_key'] = pub_key
lxc_init_interface['priv_key'] = priv_key
lxc_init_interface['nic_opts'] = nic_opts
for clone_from in ['clone_from', 'clone', 'from_container']:
# clone_from should default to None if not available
lxc_init_interface['clone_from'] = _cloud_get(clone_from, None)
if lxc_init_interface['clone_from'] is not None:
break
lxc_init_interface['profile'] = profile
lxc_init_interface['snapshot'] = snapshot
lxc_init_interface['dnsservers'] = dnsservers
lxc_init_interface['fstype'] = fstype
lxc_init_interface['path'] = path
lxc_init_interface['vgname'] = vgname
lxc_init_interface['size'] = size
lxc_init_interface['lvname'] = lvname
lxc_init_interface['thinpool'] = thinpool
lxc_init_interface['force_install'] = force_install
lxc_init_interface['unconditional_install'] = (
unconditional_install
)
lxc_init_interface['bootstrap_url'] = script
lxc_init_interface['bootstrap_args'] = script_args
lxc_init_interface['bootstrap_shell'] = _cloud_get('bootstrap_shell', 'sh')
lxc_init_interface['bootstrap_delay'] = _cloud_get('bootstrap_delay', None)
lxc_init_interface['autostart'] = autostart
lxc_init_interface['users'] = users
lxc_init_interface['password'] = password
lxc_init_interface['password_encrypted'] = password_encrypted
# be sure not to let objects goes inside the return
# as this return will be msgpacked for use in the runner !
lxc_init_interface['network_profile'] = network_profile
for i in ['cpu', 'cpuset', 'cpushare']:
if _cloud_get(i, None):
try:
lxc_init_interface[i] = vm_[i]
except KeyError:
lxc_init_interface[i] = profile[i]
return lxc_init_interface
def _get_profile(key, name, **kwargs):
if isinstance(name, dict):
profilename = name.pop('name', None)
return _get_profile(key, profilename, **name)
if name is None:
profile_match = {}
else:
profile_match = \
__salt__['config.get'](
'lxc.{1}:{0}'.format(name, key),
default=None,
merge='recurse'
)
if profile_match is None:
# No matching profile, make the profile an empty dict so that
# overrides can be applied below.
profile_match = {}
if not isinstance(profile_match, dict):
raise CommandExecutionError('lxc.{0} must be a dictionary'.format(key))
# Overlay the kwargs to override matched profile data
overrides = salt.utils.args.clean_kwargs(**copy.deepcopy(kwargs))
profile_match = salt.utils.dictupdate.update(
copy.deepcopy(profile_match),
overrides
)
return profile_match
def get_container_profile(name=None, **kwargs):
'''
.. versionadded:: 2015.5.0
Gather a pre-configured set of container configuration parameters. If no
arguments are passed, an empty profile is returned.
Profiles can be defined in the minion or master config files, or in pillar
or grains, and are loaded using :mod:`config.get
<salt.modules.config.get>`. The key under which LXC profiles must be
configured is ``lxc.container_profile.profile_name``. An example container
profile would be as follows:
.. code-block:: yaml
lxc.container_profile:
ubuntu:
template: ubuntu
backing: lvm
vgname: lxc
size: 1G
Parameters set in a profile can be overridden by passing additional
container creation arguments (such as the ones passed to :mod:`lxc.create
<salt.modules.lxc.create>`) to this function.
A profile can be defined either as the name of the profile, or a dictionary
of variable names and values. See the :ref:`LXC Tutorial
<tutorial-lxc-profiles>` for more information on how to use LXC profiles.
CLI Example:
.. code-block:: bash
salt-call lxc.get_container_profile centos
salt-call lxc.get_container_profile ubuntu template=ubuntu backing=overlayfs
'''
profile = _get_profile('container_profile', name, **kwargs)
return profile
def get_network_profile(name=None, **kwargs):
'''
.. versionadded:: 2015.5.0
Gather a pre-configured set of network configuration parameters. If no
arguments are passed, the following default profile is returned:
.. code-block:: python
{'eth0': {'link': 'br0', 'type': 'veth', 'flags': 'up'}}
Profiles can be defined in the minion or master config files, or in pillar
or grains, and are loaded using :mod:`config.get
<salt.modules.config.get>`. The key under which LXC profiles must be
configured is ``lxc.network_profile``. An example network profile would be
as follows:
.. code-block:: yaml
lxc.network_profile.centos:
eth0:
link: br0
type: veth
flags: up
To disable networking entirely:
.. code-block:: yaml
lxc.network_profile.centos:
eth0:
disable: true
Parameters set in a profile can be overridden by passing additional
arguments to this function.
A profile can be passed either as the name of the profile, or a
dictionary of variable names and values. See the :ref:`LXC Tutorial
<tutorial-lxc-profiles>` for more information on how to use network
profiles.
.. warning::
The ``ipv4``, ``ipv6``, ``gateway``, and ``link`` (bridge) settings in
network profiles will only work if the container doesn't redefine the
network configuration (for example in
``/etc/sysconfig/network-scripts/ifcfg-<interface_name>`` on
RHEL/CentOS, or ``/etc/network/interfaces`` on Debian/Ubuntu/etc.)
CLI Example:
.. code-block:: bash
salt-call lxc.get_network_profile default
'''
profile = _get_profile('network_profile', name, **kwargs)
return profile
def _rand_cpu_str(cpu):
'''
Return a random subset of cpus for the cpuset config
'''
cpu = int(cpu)
avail = __salt__['status.nproc']()
if cpu < avail:
return '0-{0}'.format(avail)
to_set = set()
while len(to_set) < cpu:
choice = random.randint(0, avail - 1)
if choice not in to_set:
to_set.add(six.text_type(choice))
return ','.join(sorted(to_set))
def _network_conf(conf_tuples=None, **kwargs):
'''
Network configuration defaults
network_profile
as for containers, we can either call this function
either with a network_profile dict or network profile name
in the kwargs
nic_opts
overrides or extra nics in the form {nic_name: {set: tings}
'''
nic = kwargs.get('network_profile', None)
ret = []
nic_opts = kwargs.get('nic_opts', {})
if nic_opts is None:
# coming from elsewhere
nic_opts = {}
if not conf_tuples:
conf_tuples = []
old = _get_veths(conf_tuples)
if not old:
old = {}
# if we have a profile name, get the profile and load the network settings
# this will obviously by default look for a profile called "eth0"
# or by what is defined in nic_opts
# and complete each nic settings by sane defaults
if nic and isinstance(nic, (six.string_types, dict)):
nicp = get_network_profile(nic)
else:
nicp = {}
if DEFAULT_NIC not in nicp:
nicp[DEFAULT_NIC] = {}
kwargs = copy.deepcopy(kwargs)
gateway = kwargs.pop('gateway', None)
bridge = kwargs.get('bridge', None)
if nic_opts:
for dev, args in six.iteritems(nic_opts):
ethx = nicp.setdefault(dev, {})
try:
ethx = salt.utils.dictupdate.update(ethx, args)
except AttributeError:
raise SaltInvocationError('Invalid nic_opts configuration')
ifs = [a for a in nicp]
ifs += [a for a in old if a not in nicp]
ifs.sort()
gateway_set = False
for dev in ifs:
args = nicp.get(dev, {})
opts = nic_opts.get(dev, {}) if nic_opts else {}
old_if = old.get(dev, {})
disable = opts.get('disable', args.get('disable', False))
if disable:
continue
mac = opts.get('mac',
opts.get('hwaddr',
args.get('mac',
args.get('hwaddr', ''))))
type_ = opts.get('type', args.get('type', ''))
flags = opts.get('flags', args.get('flags', ''))
link = opts.get('link', args.get('link', ''))
ipv4 = opts.get('ipv4', args.get('ipv4', ''))
ipv6 = opts.get('ipv6', args.get('ipv6', ''))
infos = salt.utils.odict.OrderedDict([
('lxc.network.type', {
'test': not type_,
'value': type_,
'old': old_if.get('lxc.network.type'),
'default': 'veth'}),
('lxc.network.name', {
'test': False,
'value': dev,
'old': dev,
'default': dev}),
('lxc.network.flags', {
'test': not flags,
'value': flags,
'old': old_if.get('lxc.network.flags'),
'default': 'up'}),
('lxc.network.link', {
'test': not link,
'value': link,
'old': old_if.get('lxc.network.link'),
'default': search_lxc_bridge()}),
('lxc.network.hwaddr', {
'test': not mac,
'value': mac,
'old': old_if.get('lxc.network.hwaddr'),
'default': salt.utils.network.gen_mac()}),
('lxc.network.ipv4', {
'test': not ipv4,
'value': ipv4,
'old': old_if.get('lxc.network.ipv4', ''),
'default': None}),
('lxc.network.ipv6', {
'test': not ipv6,
'value': ipv6,
'old': old_if.get('lxc.network.ipv6', ''),
'default': None})])
# for each parameter, if not explicitly set, the
# config value present in the LXC configuration should
# take precedence over the profile configuration
for info in list(infos.keys()):
bundle = infos[info]
if bundle['test']:
if bundle['old']:
bundle['value'] = bundle['old']
elif bundle['default']:
bundle['value'] = bundle['default']
for info, data in six.iteritems(infos):
if data['value']:
ret.append({info: data['value']})
for key, val in six.iteritems(args):
if key == 'link' and bridge:
val = bridge
val = opts.get(key, val)
if key in [
'type', 'flags', 'name',
'gateway', 'mac', 'link', 'ipv4', 'ipv6'
]:
continue
ret.append({'lxc.network.{0}'.format(key): val})
# gateway (in automode) must be appended following network conf !
if not gateway:
gateway = args.get('gateway', None)
if gateway is not None and not gateway_set:
ret.append({'lxc.network.ipv4.gateway': gateway})
# only one network gateway ;)
gateway_set = True
# normally, this won't happen
# set the gateway if specified even if we did
# not managed the network underlying
if gateway is not None and not gateway_set:
ret.append({'lxc.network.ipv4.gateway': gateway})
# only one network gateway ;)
gateway_set = True
new = _get_veths(ret)
# verify that we did not loose the mac settings
for iface in [a for a in new]:
ndata = new[iface]
nmac = ndata.get('lxc.network.hwaddr', '')
ntype = ndata.get('lxc.network.type', '')
omac, otype = '', ''
if iface in old:
odata = old[iface]
omac = odata.get('lxc.network.hwaddr', '')
otype = odata.get('lxc.network.type', '')
# default for network type is setted here
# attention not to change the network type
# without a good and explicit reason to.
if otype and not ntype:
ntype = otype
if not ntype:
ntype = 'veth'
new[iface]['lxc.network.type'] = ntype
if omac and not nmac:
new[iface]['lxc.network.hwaddr'] = omac
ret = []
for val in six.itervalues(new):
for row in val:
ret.append(salt.utils.odict.OrderedDict([(row, val[row])]))
# on old versions of lxc, still support the gateway auto mode
# if we didn't explicitly say no to
# (lxc.network.ipv4.gateway: auto)
if _LooseVersion(version()) <= _LooseVersion('1.0.7') and \
True not in ['lxc.network.ipv4.gateway' in a for a in ret] and \
True in ['lxc.network.ipv4' in a for a in ret]:
ret.append({'lxc.network.ipv4.gateway': 'auto'})
return ret
def _get_lxc_default_data(**kwargs):
kwargs = copy.deepcopy(kwargs)
ret = {}
for k in ['utsname', 'rootfs']:
val = kwargs.get(k, None)
if val is not None:
ret['lxc.{0}'.format(k)] = val
autostart = kwargs.get('autostart')
# autostart can have made in kwargs, but with the None
# value which is invalid, we need an explicit boolean
# autostart = on is the default.
if autostart is None:
autostart = True
# we will set the regular lxc marker to restart container at
# machine (re)boot only if we did not explicitly ask
# not to touch to the autostart settings via
# autostart == 'keep'
if autostart != 'keep':
if autostart:
ret['lxc.start.auto'] = '1'
else:
ret['lxc.start.auto'] = '0'
memory = kwargs.get('memory')
if memory is not None:
# converting the config value from MB to bytes
ret['lxc.cgroup.memory.limit_in_bytes'] = memory * 1024 * 1024
cpuset = kwargs.get('cpuset')
if cpuset:
ret['lxc.cgroup.cpuset.cpus'] = cpuset
cpushare = kwargs.get('cpushare')
cpu = kwargs.get('cpu')
if cpushare:
ret['lxc.cgroup.cpu.shares'] = cpushare
if cpu and not cpuset:
ret['lxc.cgroup.cpuset.cpus'] = _rand_cpu_str(cpu)
return ret
def _config_list(conf_tuples=None, only_net=False, **kwargs):
'''
Return a list of dicts from the salt level configurations
conf_tuples
_LXCConfig compatible list of entries which can contain
- string line
- tuple (lxc config param,value)
- dict of one entry: {lxc config param: value)
only_net
by default we add to the tuples a reflection of both
the real config if avalaible and a certain amount of
default values like the cpu parameters, the memory
and etc.
On the other hand, we also no matter the case reflect
the network configuration computed from the actual config if
available and given values.
if no_default_loads is set, we will only
reflect the network configuration back to the conf tuples
list
'''
# explicit cast
only_net = bool(only_net)
if not conf_tuples:
conf_tuples = []
kwargs = copy.deepcopy(kwargs)
ret = []
if not only_net:
default_data = _get_lxc_default_data(**kwargs)
for k, val in six.iteritems(default_data):
ret.append({k: val})
net_datas = _network_conf(conf_tuples=conf_tuples, **kwargs)
ret.extend(net_datas)
return ret
def _get_veths(net_data):
'''
Parse the nic setup inside lxc conf tuples back to a dictionary indexed by
network interface
'''
if isinstance(net_data, dict):
net_data = list(net_data.items())
nics = salt.utils.odict.OrderedDict()
current_nic = salt.utils.odict.OrderedDict()
no_names = True
for item in net_data:
if item and isinstance(item, dict):
item = list(item.items())[0]
# skip LXC configuration comment lines, and play only with tuples conf
elif isinstance(item, six.string_types):
# deal with reflection of commented lxc configs
sitem = item.strip()
if sitem.startswith('#') or not sitem:
continue
elif '=' in item:
item = tuple([a.strip() for a in item.split('=', 1)])
if item[0] == 'lxc.network.type':
current_nic = salt.utils.odict.OrderedDict()
if item[0] == 'lxc.network.name':
no_names = False
nics[item[1].strip()] = current_nic
current_nic[item[0].strip()] = item[1].strip()
# if not ethernet card name has been collected, assuming we collected
# data for eth0
if no_names and current_nic:
nics[DEFAULT_NIC] = current_nic
return nics
class _LXCConfig(object):
'''
LXC configuration data
'''
pattern = re.compile(r'^(\S+)(\s*)(=)(\s*)(.*)')
non_interpretable_pattern = re.compile(r'^((#.*)|(\s*))$')
def __init__(self, **kwargs):
kwargs = copy.deepcopy(kwargs)
self.name = kwargs.pop('name', None)
path = get_root_path(kwargs.get('path', None))
self.data = []
if self.name:
self.path = os.path.join(path, self.name, 'config')
if os.path.isfile(self.path):
with salt.utils.files.fopen(self.path) as fhr:
for line in salt.utils.data.decode(fhr.readlines()):
match = self.pattern.findall((line.strip()))
if match:
self.data.append((match[0][0], match[0][-1]))
match = self.non_interpretable_pattern.findall(
(line.strip()))
if match:
self.data.append(('', match[0][0]))
else:
self.path = None
def _replace(key, val):
if val:
self._filter_data(key)
self.data.append((key, val))
default_data = _get_lxc_default_data(**kwargs)
for key, val in six.iteritems(default_data):
_replace(key, val)
old_net = self._filter_data('lxc.network')
net_datas = _network_conf(conf_tuples=old_net, **kwargs)
if net_datas:
for row in net_datas:
self.data.extend(list(row.items()))
# be sure to reset harmful settings
for idx in ['lxc.cgroup.memory.limit_in_bytes']:
if not default_data.get(idx):
self._filter_data(idx)
def as_string(self):
chunks = ('{0[0]}{1}{0[1]}'.format(item, (' = ' if item[0] else '')) for item in self.data)
return '\n'.join(chunks) + '\n'
def write(self):
if self.path:
content = self.as_string()
# 2 step rendering to be sure not to open/wipe the config
# before as_string succeeds.
with salt.utils.files.fopen(self.path, 'w') as fic:
fic.write(salt.utils.stringutils.to_str(content))
fic.flush()
def tempfile(self):
# this might look like the function name is shadowing the
# module, but it's not since the method belongs to the class
ntf = tempfile.NamedTemporaryFile()
ntf.write(self.as_string())
ntf.flush()
return ntf
def _filter_data(self, pattern):
'''
Removes parameters which match the pattern from the config data
'''
removed = []
filtered = []
for param in self.data:
if not param[0].startswith(pattern):
filtered.append(param)
else:
removed.append(param)
self.data = filtered
return removed
def _get_base(**kwargs):
'''
If the needed base does not exist, then create it, if it does exist
create nothing and return the name of the base lxc container so
it can be cloned.
'''
profile = get_container_profile(copy.deepcopy(kwargs.get('profile')))
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, _marker)
profile_match = profile.pop(key, default)
# let kwarg overrides be the preferred choice
if kw_overrides_match is _marker:
return profile_match
return kw_overrides_match
template = select('template')
image = select('image')
vgname = select('vgname')
path = kwargs.get('path', None)
# remove the above three variables from kwargs, if they exist, to avoid
# duplicates if create() is invoked below.
for param in ('path', 'image', 'vgname', 'template'):
kwargs.pop(param, None)
if image:
proto = _urlparse(image).scheme
img_tar = __salt__['cp.cache_file'](image)
img_name = os.path.basename(img_tar)
hash_ = salt.utils.hashutils.get_hash(
img_tar,
__salt__['config.get']('hash_type'))
name = '__base_{0}_{1}_{2}'.format(proto, img_name, hash_)
if not exists(name, path=path):
create(name, template=template, image=image,
path=path, vgname=vgname, **kwargs)
if vgname:
rootfs = os.path.join('/dev', vgname, name)
edit_conf(info(name, path=path)['config'],
out_format='commented', **{'lxc.rootfs': rootfs})
return name
elif template:
name = '__base_{0}'.format(template)
if not exists(name, path=path):
create(name, template=template, image=image, path=path,
vgname=vgname, **kwargs)
if vgname:
rootfs = os.path.join('/dev', vgname, name)
edit_conf(info(name, path=path)['config'],
out_format='commented', **{'lxc.rootfs': rootfs})
return name
return ''
def init(name,
config=None,
cpuset=None,
cpushare=None,
memory=None,
profile=None,
network_profile=None,
nic_opts=None,
cpu=None,
autostart=True,
password=None,
password_encrypted=None,
users=None,
dnsservers=None,
searchdomains=None,
bridge=None,
gateway=None,
pub_key=None,
priv_key=None,
force_install=False,
unconditional_install=False,
bootstrap_delay=None,
bootstrap_args=None,
bootstrap_shell=None,
bootstrap_url=None,
**kwargs):
'''
Initialize a new container.
This is a partial idempotent function as if it is already provisioned, we
will reset a bit the lxc configuration file but much of the hard work will
be escaped as markers will prevent re-execution of harmful tasks.
name
Name of the container
image
A tar archive to use as the rootfs for the container. Conflicts with
the ``template`` argument.
cpus
Select a random number of cpu cores and assign it to the cpuset, if the
cpuset option is set then this option will be ignored
cpuset
Explicitly define the cpus this container will be bound to
cpushare
cgroups cpu shares
autostart
autostart container on reboot
memory
cgroups memory limit, in MB
.. versionchanged:: 2015.5.0
If no value is passed, no limit is set. In earlier Salt versions,
not passing this value causes a 1024MB memory limit to be set, and
it was necessary to pass ``memory=0`` to set no limit.
gateway
the ipv4 gateway to use
the default does nothing more than lxcutils does
bridge
the bridge to use
the default does nothing more than lxcutils does
network_profile
Network profile to use for the container
.. versionadded:: 2015.5.0
nic_opts
Extra options for network interfaces, will override
``{"eth0": {"hwaddr": "aa:bb:cc:dd:ee:ff", "ipv4": "10.1.1.1", "ipv6": "2001:db8::ff00:42:8329"}}``
or
``{"eth0": {"hwaddr": "aa:bb:cc:dd:ee:ff", "ipv4": "10.1.1.1/24", "ipv6": "2001:db8::ff00:42:8329"}}``
users
Users for which the password defined in the ``password`` param should
be set. Can be passed as a comma separated list or a python list.
Defaults to just the ``root`` user.
password
Set the initial password for the users defined in the ``users``
parameter
password_encrypted : False
Set to ``True`` to denote a password hash instead of a plaintext
password
.. versionadded:: 2015.5.0
profile
A LXC profile (defined in config or pillar).
This can be either a real profile mapping or a string
to retrieve it in configuration
start
Start the newly-created container
dnsservers
list of dns servers to set in the container, default [] (no setting)
seed
Seed the container with the minion config. Default: ``True``
install
If salt-minion is not already installed, install it. Default: ``True``
config
Optional config parameters. By default, the id is set to
the name of the container.
master
salt master (default to minion's master)
master_port
salt master port (default to minion's master port)
pub_key
Explicit public key to preseed the minion with (optional).
This can be either a filepath or a string representing the key
priv_key
Explicit private key to preseed the minion with (optional).
This can be either a filepath or a string representing the key
approve_key
If explicit preseeding is not used;
Attempt to request key approval from the master. Default: ``True``
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
clone_from
Original from which to use a clone operation to create the container.
Default: ``None``
bootstrap_delay
Delay in seconds between end of container creation and bootstrapping.
Useful when waiting for container to obtain a DHCP lease.
.. versionadded:: 2015.5.0
bootstrap_url
See lxc.bootstrap
bootstrap_shell
See lxc.bootstrap
bootstrap_args
See lxc.bootstrap
force_install
Force installation even if salt-minion is detected,
this is the way to run vendor bootstrap scripts even
if a salt minion is already present in the container
unconditional_install
Run the script even if the container seems seeded
CLI Example:
.. code-block:: bash
salt 'minion' lxc.init name [cpuset=cgroups_cpuset] \\
[cpushare=cgroups_cpushare] [memory=cgroups_memory] \\
[nic=nic_profile] [profile=lxc_profile] \\
[nic_opts=nic_opts] [start=(True|False)] \\
[seed=(True|False)] [install=(True|False)] \\
[config=minion_config] [approve_key=(True|False) \\
[clone_from=original] [autostart=True] \\
[priv_key=/path_or_content] [pub_key=/path_or_content] \\
[bridge=lxcbr0] [gateway=10.0.3.1] \\
[dnsservers[dns1,dns2]] \\
[users=[foo]] [password='secret'] \\
[password_encrypted=(True|False)]
'''
ret = {'name': name,
'changes': {}}
profile = get_container_profile(copy.deepcopy(profile))
if not network_profile:
network_profile = profile.get('network_profile')
if not network_profile:
network_profile = DEFAULT_NIC
# Changes is a pointer to changes_dict['init']. This method is used so that
# we can have a list of changes as they are made, providing an ordered list
# of things that were changed.
changes_dict = {'init': []}
changes = changes_dict.get('init')
if users is None:
users = []
dusers = ['root']
for user in dusers:
if user not in users:
users.append(user)
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, _marker)
profile_match = profile.pop(key, default)
# let kwarg overrides be the preferred choice
if kw_overrides_match is _marker:
return profile_match
return kw_overrides_match
path = select('path')
bpath = get_root_path(path)
state_pre = state(name, path=path)
tvg = select('vgname')
vgname = tvg if tvg else __salt__['config.get']('lxc.vgname')
start_ = select('start', True)
autostart = select('autostart', autostart)
seed = select('seed', True)
install = select('install', True)
seed_cmd = select('seed_cmd')
salt_config = _get_salt_config(config, **kwargs)
approve_key = select('approve_key', True)
clone_from = select('clone_from')
# If using a volume group then set up to make snapshot cow clones
if vgname and not clone_from:
try:
kwargs['vgname'] = vgname
clone_from = _get_base(profile=profile, **kwargs)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = exc.strerror
if changes:
ret['changes'] = changes_dict
return ret
if not kwargs.get('snapshot') is False:
kwargs['snapshot'] = True
does_exist = exists(name, path=path)
to_reboot = False
remove_seed_marker = False
if does_exist:
pass
elif clone_from:
remove_seed_marker = True
try:
clone(name, clone_from, profile=profile, **kwargs)
changes.append({'create': 'Container cloned'})
except (SaltInvocationError, CommandExecutionError) as exc:
if 'already exists' in exc.strerror:
changes.append({'create': 'Container already exists'})
else:
ret['result'] = False
ret['comment'] = exc.strerror
if changes:
ret['changes'] = changes_dict
return ret
cfg = _LXCConfig(name=name, network_profile=network_profile,
nic_opts=nic_opts, bridge=bridge, path=path,
gateway=gateway, autostart=autostart,
cpuset=cpuset, cpushare=cpushare, memory=memory)
old_chunks = read_conf(cfg.path, out_format='commented')
cfg.write()
chunks = read_conf(cfg.path, out_format='commented')
if old_chunks != chunks:
to_reboot = True
else:
remove_seed_marker = True
cfg = _LXCConfig(network_profile=network_profile,
nic_opts=nic_opts, cpuset=cpuset, path=path,
bridge=bridge, gateway=gateway,
autostart=autostart,
cpushare=cpushare, memory=memory)
with cfg.tempfile() as cfile:
try:
create(name, config=cfile.name, profile=profile, **kwargs)
changes.append({'create': 'Container created'})
except (SaltInvocationError, CommandExecutionError) as exc:
if 'already exists' in exc.strerror:
changes.append({'create': 'Container already exists'})
else:
ret['comment'] = exc.strerror
if changes:
ret['changes'] = changes_dict
return ret
cpath = os.path.join(bpath, name, 'config')
old_chunks = []
if os.path.exists(cpath):
old_chunks = read_conf(cpath, out_format='commented')
new_cfg = _config_list(conf_tuples=old_chunks,
cpu=cpu,
network_profile=network_profile,
nic_opts=nic_opts, bridge=bridge,
cpuset=cpuset, cpushare=cpushare,
memory=memory)
if new_cfg:
edit_conf(cpath, out_format='commented', lxc_config=new_cfg)
chunks = read_conf(cpath, out_format='commented')
if old_chunks != chunks:
to_reboot = True
# last time to be sure any of our property is correctly applied
cfg = _LXCConfig(name=name, network_profile=network_profile,
nic_opts=nic_opts, bridge=bridge, path=path,
gateway=gateway, autostart=autostart,
cpuset=cpuset, cpushare=cpushare, memory=memory)
old_chunks = []
if os.path.exists(cfg.path):
old_chunks = read_conf(cfg.path, out_format='commented')
cfg.write()
chunks = read_conf(cfg.path, out_format='commented')
if old_chunks != chunks:
changes.append({'config': 'Container configuration updated'})
to_reboot = True
if to_reboot:
try:
stop(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
if changes:
ret['changes'] = changes_dict
return ret
if not does_exist or (does_exist and state(name, path=path) != 'running'):
try:
start(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
if changes:
ret['changes'] = changes_dict
return ret
if remove_seed_marker:
run(name,
'rm -f \'{0}\''.format(SEED_MARKER),
path=path,
chroot_fallback=False,
python_shell=False)
# set the default user/password, only the first time
if ret.get('result', True) and password:
gid = '/.lxc.initial_pass'
gids = [gid,
'/lxc.initial_pass',
'/.lxc.{0}.initial_pass'.format(name)]
if not any(retcode(name,
'test -e "{0}"'.format(x),
chroot_fallback=True,
path=path,
ignore_retcode=True) == 0
for x in gids):
# think to touch the default user generated by default templates
# which has a really unsecure passwords...
# root is defined as a member earlier in the code
for default_user in ['ubuntu']:
if (
default_user not in users and
retcode(name,
'id {0}'.format(default_user),
python_shell=False,
path=path,
chroot_fallback=True,
ignore_retcode=True) == 0
):
users.append(default_user)
for user in users:
try:
cret = set_password(name,
users=[user],
path=path,
password=password,
encrypted=password_encrypted)
except (SaltInvocationError, CommandExecutionError) as exc:
msg = '{0}: Failed to set password'.format(
user) + exc.strerror
# only hardfail in unrecoverable situation:
# root cannot be setted up
if user == 'root':
ret['comment'] = msg
ret['result'] = False
else:
log.debug(msg)
if ret.get('result', True):
changes.append({'password': 'Password(s) updated'})
if retcode(name,
('sh -c \'touch "{0}"; test -e "{0}"\''
.format(gid)),
path=path,
chroot_fallback=True,
ignore_retcode=True) != 0:
ret['comment'] = 'Failed to set password marker'
changes[-1]['password'] += '. ' + ret['comment'] + '.'
ret['result'] = False
# set dns servers if any, only the first time
if ret.get('result', True) and dnsservers:
# retro compatibility, test also old markers
gid = '/.lxc.initial_dns'
gids = [gid,
'/lxc.initial_dns',
'/lxc.{0}.initial_dns'.format(name)]
if not any(retcode(name,
'test -e "{0}"'.format(x),
chroot_fallback=True,
path=path,
ignore_retcode=True) == 0
for x in gids):
try:
set_dns(name,
path=path,
dnsservers=dnsservers,
searchdomains=searchdomains)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Failed to set DNS: ' + exc.strerror
ret['result'] = False
else:
changes.append({'dns': 'DNS updated'})
if retcode(name,
('sh -c \'touch "{0}"; test -e "{0}"\''
.format(gid)),
chroot_fallback=True,
path=path,
ignore_retcode=True) != 0:
ret['comment'] = 'Failed to set DNS marker'
changes[-1]['dns'] += '. ' + ret['comment'] + '.'
ret['result'] = False
# retro compatibility, test also old markers
if remove_seed_marker:
run(name,
'rm -f \'{0}\''.format(SEED_MARKER),
path=path,
python_shell=False)
gid = '/.lxc.initial_seed'
gids = [gid, '/lxc.initial_seed']
if (
any(retcode(name,
'test -e {0}'.format(x),
path=path,
chroot_fallback=True,
ignore_retcode=True) == 0
for x in gids) or not ret.get('result', True)
):
pass
elif seed or seed_cmd:
if seed:
try:
result = bootstrap(
name, config=salt_config, path=path,
approve_key=approve_key,
pub_key=pub_key, priv_key=priv_key,
install=install,
force_install=force_install,
unconditional_install=unconditional_install,
bootstrap_delay=bootstrap_delay,
bootstrap_url=bootstrap_url,
bootstrap_shell=bootstrap_shell,
bootstrap_args=bootstrap_args)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Bootstrap failed: ' + exc.strerror
ret['result'] = False
else:
if not result:
ret['comment'] = ('Bootstrap failed, see minion log for '
'more information')
ret['result'] = False
else:
changes.append(
{'bootstrap': 'Container successfully bootstrapped'}
)
elif seed_cmd:
try:
result = __salt__[seed_cmd](info(name, path=path)['rootfs'],
name,
salt_config)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = ('Bootstrap via seed_cmd \'{0}\' failed: {1}'
.format(seed_cmd, exc.strerror))
ret['result'] = False
else:
if not result:
ret['comment'] = ('Bootstrap via seed_cmd \'{0}\' failed, '
'see minion log for more information '
.format(seed_cmd))
ret['result'] = False
else:
changes.append(
{'bootstrap': 'Container successfully bootstrapped '
'using seed_cmd \'{0}\''
.format(seed_cmd)}
)
if ret.get('result', True) and not start_:
try:
stop(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
ret['result'] = False
state_post = state(name, path=path)
if state_pre != state_post:
changes.append({'state': {'old': state_pre, 'new': state_post}})
if ret.get('result', True):
ret['comment'] = ('Container \'{0}\' successfully initialized'
.format(name))
ret['result'] = True
if changes:
ret['changes'] = changes_dict
return ret
def cloud_init(name, vm_=None, **kwargs):
'''
Thin wrapper to lxc.init to be used from the saltcloud lxc driver
name
Name of the container
may be None and then guessed from saltcloud mapping
`vm_`
saltcloud mapping defaults for the vm
CLI Example:
.. code-block:: bash
salt '*' lxc.cloud_init foo
'''
init_interface = cloud_init_interface(name, vm_, **kwargs)
name = init_interface.pop('name', name)
return init(name, **init_interface)
def images(dist=None):
'''
.. versionadded:: 2015.5.0
List the available images for LXC's ``download`` template.
dist : None
Filter results to a single Linux distribution
CLI Examples:
.. code-block:: bash
salt myminion lxc.images
salt myminion lxc.images dist=centos
'''
out = __salt__['cmd.run_stdout'](
'lxc-create -n __imgcheck -t download -- --list',
ignore_retcode=True
)
if 'DIST' not in out:
raise CommandExecutionError(
'Unable to run the \'download\' template script. Is it installed?'
)
ret = {}
passed_header = False
for line in out.splitlines():
try:
distro, release, arch, variant, build_time = line.split()
except ValueError:
continue
if not passed_header:
if distro == 'DIST':
passed_header = True
continue
dist_list = ret.setdefault(distro, [])
dist_list.append({
'release': release,
'arch': arch,
'variant': variant,
'build_time': build_time,
})
if dist is not None:
return dict([(dist, ret.get(dist, []))])
return ret
def _after_ignition_network_profile(cmd,
ret,
name,
network_profile,
path,
nic_opts):
_clear_context()
if ret['retcode'] == 0 and exists(name, path=path):
if network_profile:
network_changes = apply_network_profile(name,
network_profile,
path=path,
nic_opts=nic_opts)
if network_changes:
log.info(
'Network changes from applying network profile \'%s\' '
'to newly-created container \'%s\':\n%s',
network_profile, name, network_changes
)
c_state = state(name, path=path)
return {'result': True,
'state': {'old': None, 'new': c_state}}
else:
if exists(name, path=path):
# destroy the container if it was partially created
cmd = 'lxc-destroy'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0}'.format(name)
__salt__['cmd.retcode'](cmd, python_shell=False)
raise CommandExecutionError(
'Container could not be created with cmd \'{0}\': {1}'
.format(cmd, ret['stderr'])
)
def create(name,
config=None,
profile=None,
network_profile=None,
nic_opts=None,
**kwargs):
'''
Create a new container.
name
Name of the container
config
The config file to use for the container. Defaults to system-wide
config (usually in /etc/lxc/lxc.conf).
profile
Profile to use in container creation (see
:mod:`lxc.get_container_profile
<salt.modules.lxc.get_container_profile>`). Values in a profile will be
overridden by the **Container Creation Arguments** listed below.
network_profile
Network profile to use for container
.. versionadded:: 2015.5.0
**Container Creation Arguments**
template
The template to use. For example, ``ubuntu`` or ``fedora``.
For a full list of available templates, check out
the :mod:`lxc.templates <salt.modules.lxc.templates>` function.
Conflicts with the ``image`` argument.
.. note::
The ``download`` template requires the following three parameters
to be defined in ``options``:
* **dist** - The name of the distribution
* **release** - Release name/version
* **arch** - Architecture of the container
The available images can be listed using the :mod:`lxc.images
<salt.modules.lxc.images>` function.
options
Template-specific options to pass to the lxc-create command. These
correspond to the long options (ones beginning with two dashes) that
the template script accepts. For example:
.. code-block:: bash
options='{"dist": "centos", "release": "6", "arch": "amd64"}'
For available template options, refer to the lxc template scripts
which are ususally located under ``/usr/share/lxc/templates``,
or run ``lxc-create -t <template> -h``.
image
A tar archive to use as the rootfs for the container. Conflicts with
the ``template`` argument.
backing
The type of storage to use. Set to ``lvm`` to use an LVM group.
Defaults to filesystem within /var/lib/lxc.
fstype
Filesystem type to use on LVM logical volume
size : 1G
Size of the volume to create. Only applicable if ``backing=lvm``.
vgname : lxc
Name of the LVM volume group in which to create the volume for this
container. Only applicable if ``backing=lvm``.
lvname
Name of the LVM logical volume in which to create the volume for this
container. Only applicable if ``backing=lvm``.
thinpool
Name of a pool volume that will be used for thin-provisioning this
container. Only applicable if ``backing=lvm``.
nic_opts
give extra opts overriding network profile values
path
parent path for the container creation (default: /var/lib/lxc)
zfsroot
Name of the ZFS root in which to create the volume for this container.
Only applicable if ``backing=zfs``. (default: tank/lxc)
.. versionadded:: 2015.8.0
'''
# Required params for 'download' template
download_template_deps = ('dist', 'release', 'arch')
cmd = 'lxc-create -n {0}'.format(name)
profile = get_container_profile(copy.deepcopy(profile))
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, None)
profile_match = profile.pop(key, default)
# Return the profile match if the the kwarg match was None, as the
# lxc.present state will pass these kwargs set to None by default.
if kw_overrides_match is None:
return profile_match
return kw_overrides_match
path = select('path')
if exists(name, path=path):
raise CommandExecutionError(
'Container \'{0}\' already exists'.format(name)
)
tvg = select('vgname')
vgname = tvg if tvg else __salt__['config.get']('lxc.vgname')
# The 'template' and 'image' params conflict
template = select('template')
image = select('image')
if template and image:
raise SaltInvocationError(
'Only one of \'template\' and \'image\' is permitted'
)
elif not any((template, image, profile)):
raise SaltInvocationError(
'At least one of \'template\', \'image\', and \'profile\' is '
'required'
)
options = select('options') or {}
backing = select('backing')
if vgname and not backing:
backing = 'lvm'
lvname = select('lvname')
thinpool = select('thinpool')
fstype = select('fstype')
size = select('size', '1G')
zfsroot = select('zfsroot')
if backing in ('dir', 'overlayfs', 'btrfs', 'zfs'):
fstype = None
size = None
# some backends won't support some parameters
if backing in ('aufs', 'dir', 'overlayfs', 'btrfs'):
lvname = vgname = thinpool = None
if image:
img_tar = __salt__['cp.cache_file'](image)
template = os.path.join(
os.path.dirname(salt.__file__),
'templates',
'lxc',
'salt_tarball')
options['imgtar'] = img_tar
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
if not os.path.exists(path):
os.makedirs(path)
if config:
cmd += ' -f {0}'.format(config)
if template:
cmd += ' -t {0}'.format(template)
if backing:
backing = backing.lower()
cmd += ' -B {0}'.format(backing)
if backing in ('zfs',):
if zfsroot:
cmd += ' --zfsroot {0}'.format(zfsroot)
if backing in ('lvm',):
if lvname:
cmd += ' --lvname {0}'.format(lvname)
if vgname:
cmd += ' --vgname {0}'.format(vgname)
if thinpool:
cmd += ' --thinpool {0}'.format(thinpool)
if backing not in ('dir', 'overlayfs'):
if fstype:
cmd += ' --fstype {0}'.format(fstype)
if size:
cmd += ' --fssize {0}'.format(size)
if options:
if template == 'download':
missing_deps = [x for x in download_template_deps
if x not in options]
if missing_deps:
raise SaltInvocationError(
'Missing params in \'options\' dict: {0}'
.format(', '.join(missing_deps))
)
cmd += ' --'
for key, val in six.iteritems(options):
cmd += ' --{0} {1}'.format(key, val)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
# please do not merge extra conflicting stuff
# inside those two line (ret =, return)
return _after_ignition_network_profile(cmd,
ret,
name,
network_profile,
path,
nic_opts)
def clone(name,
orig,
profile=None,
network_profile=None,
nic_opts=None,
**kwargs):
'''
Create a new container as a clone of another container
name
Name of the container
orig
Name of the original container to be cloned
profile
Profile to use in container cloning (see
:mod:`lxc.get_container_profile
<salt.modules.lxc.get_container_profile>`). Values in a profile will be
overridden by the **Container Cloning Arguments** listed below.
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
**Container Cloning Arguments**
snapshot
Use Copy On Write snapshots (LVM)
size : 1G
Size of the volume to create. Only applicable if ``backing=lvm``.
backing
The type of storage to use. Set to ``lvm`` to use an LVM group.
Defaults to filesystem within /var/lib/lxc.
network_profile
Network profile to use for container
.. versionadded:: 2015.8.0
nic_opts
give extra opts overriding network profile values
.. versionadded:: 2015.8.0
CLI Examples:
.. code-block:: bash
salt '*' lxc.clone myclone orig=orig_container
salt '*' lxc.clone myclone orig=orig_container snapshot=True
'''
profile = get_container_profile(copy.deepcopy(profile))
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, None)
profile_match = profile.pop(key, default)
# let kwarg overrides be the preferred choice
if kw_overrides_match is None:
return profile_match
return kw_overrides_match
path = select('path')
if exists(name, path=path):
raise CommandExecutionError(
'Container \'{0}\' already exists'.format(name)
)
_ensure_exists(orig, path=path)
if state(orig, path=path) != 'stopped':
raise CommandExecutionError(
'Container \'{0}\' must be stopped to be cloned'.format(orig)
)
backing = select('backing')
snapshot = select('snapshot')
if backing in ('dir',):
snapshot = False
if not snapshot:
snapshot = ''
else:
snapshot = '-s'
size = select('size', '1G')
if backing in ('dir', 'overlayfs', 'btrfs'):
size = None
# LXC commands and options changed in 2.0 - CF issue #34086 for details
if _LooseVersion(version()) >= _LooseVersion('2.0'):
# https://linuxcontainers.org/lxc/manpages//man1/lxc-copy.1.html
cmd = 'lxc-copy'
cmd += ' {0} -n {1} -N {2}'.format(snapshot, orig, name)
else:
# https://linuxcontainers.org/lxc/manpages//man1/lxc-clone.1.html
cmd = 'lxc-clone'
cmd += ' {0} -o {1} -n {2}'.format(snapshot, orig, name)
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
if not os.path.exists(path):
os.makedirs(path)
if backing:
backing = backing.lower()
cmd += ' -B {0}'.format(backing)
if backing not in ('dir', 'overlayfs'):
if size:
cmd += ' -L {0}'.format(size)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
# please do not merge extra conflicting stuff
# inside those two line (ret =, return)
return _after_ignition_network_profile(cmd,
ret,
name,
network_profile,
path,
nic_opts)
def ls_(active=None, cache=True, path=None):
'''
Return a list of the containers available on the minion
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
active
If ``True``, return only active (i.e. running) containers
.. versionadded:: 2015.5.0
CLI Example:
.. code-block:: bash
salt '*' lxc.ls
salt '*' lxc.ls active=True
'''
contextvar = 'lxc.ls{0}'.format(path)
if active:
contextvar += '.active'
if cache and (contextvar in __context__):
return __context__[contextvar]
else:
ret = []
cmd = 'lxc-ls'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
if active:
cmd += ' --active'
output = __salt__['cmd.run_stdout'](cmd, python_shell=False)
for line in output.splitlines():
ret.extend(line.split())
__context__[contextvar] = ret
return ret
def list_(extra=False, limit=None, path=None):
'''
List containers classified by state
extra
Also get per-container specific info. This will change the return data.
Instead of returning a list of containers, a dictionary of containers
and each container's output from :mod:`lxc.info
<salt.modules.lxc.info>`.
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
limit
Return output matching a specific state (**frozen**, **running**, or
**stopped**).
.. versionadded:: 2015.5.0
CLI Examples:
.. code-block:: bash
salt '*' lxc.list
salt '*' lxc.list extra=True
salt '*' lxc.list limit=running
'''
ctnrs = ls_(path=path)
if extra:
stopped = {}
frozen = {}
running = {}
else:
stopped = []
frozen = []
running = []
ret = {'running': running,
'stopped': stopped,
'frozen': frozen}
for container in ctnrs:
cmd = 'lxc-info'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0}'.format(container)
c_info = __salt__['cmd.run'](
cmd,
python_shell=False,
output_loglevel='debug'
)
c_state = None
for line in c_info.splitlines():
stat = line.split(':')
if stat[0] in ('State', 'state'):
c_state = stat[1].strip()
break
if not c_state or (limit is not None and c_state.lower() != limit):
continue
if extra:
infos = info(container, path=path)
method = 'update'
value = {container: infos}
else:
method = 'append'
value = container
if c_state == 'STOPPED':
getattr(stopped, method)(value)
continue
if c_state == 'FROZEN':
getattr(frozen, method)(value)
continue
if c_state == 'RUNNING':
getattr(running, method)(value)
continue
if limit is not None:
return ret.get(limit, {} if extra else [])
return ret
def _change_state(cmd,
name,
expected,
stdin=_marker,
stdout=_marker,
stderr=_marker,
with_communicate=_marker,
use_vt=_marker,
path=None):
pre = state(name, path=path)
if pre == expected:
return {'result': True,
'state': {'old': expected, 'new': expected},
'comment': 'Container \'{0}\' already {1}'
.format(name, expected)}
if cmd == 'lxc-destroy':
# Kill the container first
scmd = 'lxc-stop'
if path:
scmd += ' -P {0}'.format(pipes.quote(path))
scmd += ' -k -n {0}'.format(name)
__salt__['cmd.run'](scmd,
python_shell=False)
if path and ' -P ' not in cmd:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0}'.format(name)
# certain lxc commands need to be taken with care (lxc-start)
# as te command itself mess with double forks; we must not
# communicate with it, but just wait for the exit status
pkwargs = {'python_shell': False,
'redirect_stderr': True,
'with_communicate': with_communicate,
'use_vt': use_vt,
'stdin': stdin,
'stdout': stdout}
for i in [a for a in pkwargs]:
val = pkwargs[i]
if val is _marker:
pkwargs.pop(i, None)
_cmdout = __salt__['cmd.run_all'](cmd, **pkwargs)
if _cmdout['retcode'] != 0:
raise CommandExecutionError(
'Error changing state for container \'{0}\' using command '
'\'{1}\': {2}'.format(name, cmd, _cmdout['stdout'])
)
if expected is not None:
# some commands do not wait, so we will
rcmd = 'lxc-wait'
if path:
rcmd += ' -P {0}'.format(pipes.quote(path))
rcmd += ' -n {0} -s {1}'.format(name, expected.upper())
__salt__['cmd.run'](rcmd, python_shell=False, timeout=30)
_clear_context()
post = state(name, path=path)
ret = {'result': post == expected,
'state': {'old': pre, 'new': post}}
return ret
def _ensure_exists(name, path=None):
'''
Raise an exception if the container does not exist
'''
if not exists(name, path=path):
raise CommandExecutionError(
'Container \'{0}\' does not exist'.format(name)
)
def _ensure_running(name, no_start=False, path=None):
'''
If the container is not currently running, start it. This function returns
the state that the container was in before changing
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
'''
_ensure_exists(name, path=path)
pre = state(name, path=path)
if pre == 'running':
# This will be a no-op but running the function will give us a pretty
# return dict.
return start(name, path=path)
elif pre == 'stopped':
if no_start:
raise CommandExecutionError(
'Container \'{0}\' is not running'.format(name)
)
return start(name, path=path)
elif pre == 'frozen':
if no_start:
raise CommandExecutionError(
'Container \'{0}\' is not running'.format(name)
)
return unfreeze(name, path=path)
def restart(name, path=None, lxc_config=None, force=False):
'''
.. versionadded:: 2015.5.0
Restart the named container. If the container was not running, the
container will merely be started.
name
The name of the container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
lxc_config
path to a lxc config file
config file will be guessed from container name otherwise
.. versionadded:: 2015.8.0
force : False
If ``True``, the container will be force-stopped instead of gracefully
shut down
CLI Example:
.. code-block:: bash
salt myminion lxc.restart name
'''
_ensure_exists(name, path=path)
orig_state = state(name, path=path)
if orig_state != 'stopped':
stop(name, kill=force, path=path)
ret = start(name, path=path, lxc_config=lxc_config)
ret['state']['old'] = orig_state
if orig_state != 'stopped':
ret['restarted'] = True
return ret
def start(name, **kwargs):
'''
Start the named container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
lxc_config
path to a lxc config file
config file will be guessed from container name otherwise
.. versionadded:: 2015.8.0
use_vt
run the command through VT
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.start name
'''
path = kwargs.get('path', None)
cpath = get_root_path(path)
lxc_config = kwargs.get('lxc_config', None)
cmd = 'lxc-start'
if not lxc_config:
lxc_config = os.path.join(cpath, name, 'config')
# we try to start, even without config, if global opts are there
if os.path.exists(lxc_config):
cmd += ' -f {0}'.format(pipes.quote(lxc_config))
cmd += ' -d'
_ensure_exists(name, path=path)
if state(name, path=path) == 'frozen':
raise CommandExecutionError(
'Container \'{0}\' is frozen, use lxc.unfreeze'.format(name)
)
# lxc-start daemonize itself violently, we must not communicate with it
use_vt = kwargs.get('use_vt', None)
with_communicate = kwargs.get('with_communicate', False)
return _change_state(cmd, name, 'running',
stdout=None,
stderr=None,
stdin=None,
with_communicate=with_communicate,
path=path,
use_vt=use_vt)
def stop(name, kill=False, path=None, use_vt=None):
'''
Stop the named container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
kill: False
Do not wait for the container to stop, kill all tasks in the container.
Older LXC versions will stop containers like this irrespective of this
argument.
.. versionchanged:: 2015.5.0
Default value changed to ``False``
use_vt
run the command through VT
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.stop name
'''
_ensure_exists(name, path=path)
orig_state = state(name, path=path)
if orig_state == 'frozen' and not kill:
# Gracefully stopping a frozen container is slower than unfreezing and
# then stopping it (at least in my testing), so if we're not
# force-stopping the container, unfreeze it first.
unfreeze(name, path=path)
cmd = 'lxc-stop'
if kill:
cmd += ' -k'
ret = _change_state(cmd, name, 'stopped', use_vt=use_vt, path=path)
ret['state']['old'] = orig_state
return ret
def freeze(name, **kwargs):
'''
Freeze the named container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
start : False
If ``True`` and the container is stopped, the container will be started
before attempting to freeze.
.. versionadded:: 2015.5.0
use_vt
run the command through VT
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.freeze name
'''
use_vt = kwargs.get('use_vt', None)
path = kwargs.get('path', None)
_ensure_exists(name, path=path)
orig_state = state(name, path=path)
start_ = kwargs.get('start', False)
if orig_state == 'stopped':
if not start_:
raise CommandExecutionError(
'Container \'{0}\' is stopped'.format(name)
)
start(name, path=path)
cmd = 'lxc-freeze'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
ret = _change_state(cmd, name, 'frozen', use_vt=use_vt, path=path)
if orig_state == 'stopped' and start_:
ret['state']['old'] = orig_state
ret['started'] = True
ret['state']['new'] = state(name, path=path)
return ret
def unfreeze(name, path=None, use_vt=None):
'''
Unfreeze the named container.
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
use_vt
run the command through VT
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.unfreeze name
'''
_ensure_exists(name, path=path)
if state(name, path=path) == 'stopped':
raise CommandExecutionError(
'Container \'{0}\' is stopped'.format(name)
)
cmd = 'lxc-unfreeze'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
return _change_state(cmd, name, 'running', path=path, use_vt=use_vt)
def destroy(name, stop=False, path=None):
'''
Destroy the named container.
.. warning::
Destroys all data associated with the container.
path
path to the container parent directory (default: /var/lib/lxc)
.. versionadded:: 2015.8.0
stop : False
If ``True``, the container will be destroyed even if it is
running/frozen.
.. versionchanged:: 2015.5.0
Default value changed to ``False``. This more closely matches the
behavior of ``lxc-destroy(1)``, and also makes it less likely that
an accidental command will destroy a running container that was
being used for important things.
CLI Examples:
.. code-block:: bash
salt '*' lxc.destroy foo
salt '*' lxc.destroy foo stop=True
'''
_ensure_exists(name, path=path)
if not stop and state(name, path=path) != 'stopped':
raise CommandExecutionError(
'Container \'{0}\' is not stopped'.format(name)
)
return _change_state('lxc-destroy', name, None, path=path)
# Compatibility between LXC and nspawn
remove = salt.utils.functools.alias_function(destroy, 'remove')
def exists(name, path=None):
'''
Returns whether the named container exists.
path
path to the container parent directory (default: /var/lib/lxc)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.exists name
'''
_exists = name in ls_(path=path)
# container may be just created but we did cached earlier the
# lxc-ls results
if not _exists:
_exists = name in ls_(cache=False, path=path)
return _exists
def state(name, path=None):
'''
Returns the state of a container.
path
path to the container parent directory (default: /var/lib/lxc)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.state name
'''
# Don't use _ensure_exists() here, it will mess with _change_state()
cachekey = 'lxc.state.{0}{1}'.format(name, path)
try:
return __context__[cachekey]
except KeyError:
if not exists(name, path=path):
__context__[cachekey] = None
else:
cmd = 'lxc-info'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0}'.format(name)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
if ret['retcode'] != 0:
_clear_context()
raise CommandExecutionError(
'Unable to get state of container \'{0}\''.format(name)
)
c_infos = ret['stdout'].splitlines()
c_state = None
for c_info in c_infos:
stat = c_info.split(':')
if stat[0].lower() == 'state':
c_state = stat[1].strip().lower()
break
__context__[cachekey] = c_state
return __context__[cachekey]
def get_parameter(name, parameter, path=None):
'''
Returns the value of a cgroup parameter for a container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.get_parameter container_name memory.limit_in_bytes
'''
_ensure_exists(name, path=path)
cmd = 'lxc-cgroup'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0} {1}'.format(name, parameter)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
if ret['retcode'] != 0:
raise CommandExecutionError(
'Unable to retrieve value for \'{0}\''.format(parameter)
)
return ret['stdout'].strip()
def set_parameter(name, parameter, value, path=None):
'''
Set the value of a cgroup parameter for a container.
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.set_parameter name parameter value
'''
if not exists(name, path=path):
return None
cmd = 'lxc-cgroup'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0} {1} {2}'.format(name, parameter, value)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
if ret['retcode'] != 0:
return False
else:
return True
def info(name, path=None):
'''
Returns information about a container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.info name
'''
cachekey = 'lxc.info.{0}{1}'.format(name, path)
try:
return __context__[cachekey]
except KeyError:
_ensure_exists(name, path=path)
cpath = get_root_path(path)
try:
conf_file = os.path.join(cpath, name, 'config')
except AttributeError:
conf_file = os.path.join(cpath, six.text_type(name), 'config')
if not os.path.isfile(conf_file):
raise CommandExecutionError(
'LXC config file {0} does not exist'.format(conf_file)
)
ret = {}
config = []
with salt.utils.files.fopen(conf_file) as fp_:
for line in fp_:
line = salt.utils.stringutils.to_unicode(line)
comps = [x.strip() for x in
line.split('#', 1)[0].strip().split('=', 1)]
if len(comps) == 2:
config.append(tuple(comps))
ifaces = []
current = None
for key, val in config:
if key == 'lxc.network.type':
current = {'type': val}
ifaces.append(current)
elif not current:
continue
elif key.startswith('lxc.network.'):
current[key.replace('lxc.network.', '', 1)] = val
if ifaces:
ret['nics'] = ifaces
ret['rootfs'] = next(
(x[1] for x in config if x[0] == 'lxc.rootfs'),
None
)
ret['state'] = state(name, path=path)
ret['ips'] = []
ret['public_ips'] = []
ret['private_ips'] = []
ret['public_ipv4_ips'] = []
ret['public_ipv6_ips'] = []
ret['private_ipv4_ips'] = []
ret['private_ipv6_ips'] = []
ret['ipv4_ips'] = []
ret['ipv6_ips'] = []
ret['size'] = None
ret['config'] = conf_file
if ret['state'] == 'running':
try:
limit = int(get_parameter(name, 'memory.limit_in_bytes'))
except (CommandExecutionError, TypeError, ValueError):
limit = 0
try:
usage = int(get_parameter(name, 'memory.usage_in_bytes'))
except (CommandExecutionError, TypeError, ValueError):
usage = 0
free = limit - usage
ret['memory_limit'] = limit
ret['memory_free'] = free
size = run_stdout(name, 'df /', path=path, python_shell=False)
# The size is the 2nd column of the last line
ret['size'] = size.splitlines()[-1].split()[1]
# First try iproute2
ip_cmd = run_all(
name, 'ip link show', path=path, python_shell=False)
if ip_cmd['retcode'] == 0:
ip_data = ip_cmd['stdout']
ip_cmd = run_all(
name, 'ip addr show', path=path, python_shell=False)
ip_data += '\n' + ip_cmd['stdout']
ip_data = salt.utils.network._interfaces_ip(ip_data)
else:
# That didn't work, try ifconfig
ip_cmd = run_all(
name, 'ifconfig', path=path, python_shell=False)
if ip_cmd['retcode'] == 0:
ip_data = \
salt.utils.network._interfaces_ifconfig(
ip_cmd['stdout'])
else:
# Neither was successful, give up
log.warning(
'Unable to run ip or ifconfig in container \'%s\'', name
)
ip_data = {}
ret['ipv4_ips'] = salt.utils.network.ip_addrs(
include_loopback=True,
interface_data=ip_data
)
ret['ipv6_ips'] = salt.utils.network.ip_addrs6(
include_loopback=True,
interface_data=ip_data
)
ret['ips'] = ret['ipv4_ips'] + ret['ipv6_ips']
for address in ret['ipv4_ips']:
if address == '127.0.0.1':
ret['private_ips'].append(address)
ret['private_ipv4_ips'].append(address)
elif salt.utils.cloud.is_public_ip(address):
ret['public_ips'].append(address)
ret['public_ipv4_ips'].append(address)
else:
ret['private_ips'].append(address)
ret['private_ipv4_ips'].append(address)
for address in ret['ipv6_ips']:
if address == '::1' or address.startswith('fe80'):
ret['private_ips'].append(address)
ret['private_ipv6_ips'].append(address)
else:
ret['public_ips'].append(address)
ret['public_ipv6_ips'].append(address)
for key in [x for x in ret if x == 'ips' or x.endswith('ips')]:
ret[key].sort(key=_ip_sort)
__context__[cachekey] = ret
return __context__[cachekey]
def set_password(name, users, password, encrypted=True, path=None):
'''
.. versionchanged:: 2015.5.0
Function renamed from ``set_pass`` to ``set_password``. Additionally,
this function now supports (and defaults to using) a password hash
instead of a plaintext password.
Set the password of one or more system users inside containers
users
Comma-separated list (or python list) of users to change password
password
Password to set for the specified user(s)
encrypted : True
If true, ``password`` must be a password hash. Set to ``False`` to set
a plaintext password (not recommended).
.. versionadded:: 2015.5.0
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.set_pass container-name root '$6$uJ2uAyLU$KoI67t8As/0fXtJOPcHKGXmUpcoYUcVR2K6x93walnShTCQvjRwq25yIkiCBOqgbfdKQSFnAo28/ek6716vEV1'
salt '*' lxc.set_pass container-name root foo encrypted=False
'''
def _bad_user_input():
raise SaltInvocationError('Invalid input for \'users\' parameter')
if not isinstance(users, list):
try:
users = users.split(',')
except AttributeError:
_bad_user_input()
if not users:
_bad_user_input()
failed_users = []
for user in users:
result = retcode(name,
'chpasswd{0}'.format(' -e' if encrypted else ''),
stdin=':'.join((user, password)),
python_shell=False,
path=path,
chroot_fallback=True,
output_loglevel='quiet')
if result != 0:
failed_users.append(user)
if failed_users:
raise CommandExecutionError(
'Password change failed for the following user(s): {0}'
.format(', '.join(failed_users))
)
return True
set_pass = salt.utils.functools.alias_function(set_password, 'set_pass')
def update_lxc_conf(name, lxc_conf, lxc_conf_unset, path=None):
'''
Edit LXC configuration options
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.update_lxc_conf ubuntu \\
lxc_conf="[{'network.ipv4.ip':'10.0.3.5'}]" \\
lxc_conf_unset="['lxc.utsname']"
'''
_ensure_exists(name, path=path)
cpath = get_root_path(path)
lxc_conf_p = os.path.join(cpath, name, 'config')
if not os.path.exists(lxc_conf_p):
raise SaltInvocationError(
'Configuration file {0} does not exist'.format(lxc_conf_p)
)
changes = {'edited': [], 'added': [], 'removed': []}
ret = {'changes': changes, 'result': True, 'comment': ''}
# do not use salt.utils.files.fopen !
with salt.utils.files.fopen(lxc_conf_p, 'r') as fic:
filtered_lxc_conf = []
for row in lxc_conf:
if not row:
continue
for conf in row:
filtered_lxc_conf.append((conf.strip(),
row[conf].strip()))
ret['comment'] = 'lxc.conf is up to date'
lines = []
orig_config = salt.utils.stringutils.to_unicode(fic.read())
for line in orig_config.splitlines():
if line.startswith('#') or not line.strip():
lines.append([line, ''])
else:
line = line.split('=')
index = line.pop(0)
val = (index.strip(), '='.join(line).strip())
if val not in lines:
lines.append(val)
for key, item in filtered_lxc_conf:
matched = False
for idx, line in enumerate(lines[:]):
if line[0] == key:
matched = True
lines[idx] = (key, item)
if '='.join(line[1:]).strip() != item.strip():
changes['edited'].append(
({line[0]: line[1:]}, {key: item}))
break
if not matched:
if (key, item) not in lines:
lines.append((key, item))
changes['added'].append({key: item})
dest_lxc_conf = []
# filter unset
if lxc_conf_unset:
for line in lines:
for opt in lxc_conf_unset:
if (
not line[0].startswith(opt) and
line not in dest_lxc_conf
):
dest_lxc_conf.append(line)
else:
changes['removed'].append(opt)
else:
dest_lxc_conf = lines
conf = ''
for key, val in dest_lxc_conf:
if not val:
conf += '{0}\n'.format(key)
else:
conf += '{0} = {1}\n'.format(key.strip(), val.strip())
conf_changed = conf != orig_config
chrono = datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S')
if conf_changed:
# DO NOT USE salt.utils.files.fopen here, i got (kiorky)
# problems with lxc configs which were wiped !
with salt.utils.files.fopen('{0}.{1}'.format(lxc_conf_p, chrono), 'w') as wfic:
wfic.write(salt.utils.stringutils.to_str(conf))
with salt.utils.files.fopen(lxc_conf_p, 'w') as wfic:
wfic.write(salt.utils.stringutils.to_str(conf))
ret['comment'] = 'Updated'
ret['result'] = True
if not any(changes[x] for x in changes):
# Ensure an empty changes dict if nothing was modified
ret['changes'] = {}
return ret
def set_dns(name, dnsservers=None, searchdomains=None, path=None):
'''
.. versionchanged:: 2015.5.0
The ``dnsservers`` and ``searchdomains`` parameters can now be passed
as a comma-separated list.
Update /etc/resolv.confo
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.set_dns ubuntu "['8.8.8.8', '4.4.4.4']"
'''
if dnsservers is None:
dnsservers = ['8.8.8.8', '4.4.4.4']
elif not isinstance(dnsservers, list):
try:
dnsservers = dnsservers.split(',')
except AttributeError:
raise SaltInvocationError(
'Invalid input for \'dnsservers\' parameter'
)
if searchdomains is None:
searchdomains = []
elif not isinstance(searchdomains, list):
try:
searchdomains = searchdomains.split(',')
except AttributeError:
raise SaltInvocationError(
'Invalid input for \'searchdomains\' parameter'
)
dns = ['nameserver {0}'.format(x) for x in dnsservers]
dns.extend(['search {0}'.format(x) for x in searchdomains])
dns = '\n'.join(dns) + '\n'
# we may be using resolvconf in the container
# We need to handle that case with care:
# - we create the resolv.conf runtime directory (the
# linked directory) as anyway it will be shadowed when the real
# runned tmpfs mountpoint will be mounted.
# ( /etc/resolv.conf -> ../run/resolvconf/resolv.conf)
# Indeed, it can save us in any other case (running, eg, in a
# bare chroot when repairing or preparing the container for
# operation.
# - We also teach resolvconf to use the aforementioned dns.
# - We finally also set /etc/resolv.conf in all cases
rstr = __salt__['test.random_hash']()
# no tmp here, apparmor won't let us execute !
script = '/sbin/{0}_dns.sh'.format(rstr)
DNS_SCRIPT = "\n".join([
# 'set -x',
'#!/usr/bin/env bash',
'if [ -h /etc/resolv.conf ];then',
' if [ "x$(readlink /etc/resolv.conf)"'
' = "x../run/resolvconf/resolv.conf" ];then',
' if [ ! -d /run/resolvconf/ ];then',
' mkdir -p /run/resolvconf',
' fi',
' cat > /etc/resolvconf/resolv.conf.d/head <<EOF',
dns,
'EOF',
'',
' fi',
'fi',
'cat > /etc/resolv.conf <<EOF',
dns,
'EOF',
''])
result = run_all(
name, 'tee {0}'.format(script), path=path,
stdin=DNS_SCRIPT, python_shell=True)
if result['retcode'] == 0:
result = run_all(
name, 'sh -c "chmod +x {0};{0}"'.format(script),
path=path, python_shell=True)
# blindly delete the setter file
run_all(name,
'sh -c \'if [ -f "{0}" ];then rm -f "{0}";fi\''.format(script),
path=path, python_shell=True)
if result['retcode'] != 0:
error = ('Unable to write to /etc/resolv.conf in container \'{0}\''
.format(name))
if result['stderr']:
error += ': {0}'.format(result['stderr'])
raise CommandExecutionError(error)
return True
def running_systemd(name, cache=True, path=None):
'''
Determine if systemD is running
path
path to the container parent
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.running_systemd ubuntu
'''
k = 'lxc.systemd.test.{0}{1}'.format(name, path)
ret = __context__.get(k, None)
if ret is None or not cache:
rstr = __salt__['test.random_hash']()
# no tmp here, apparmor won't let us execute !
script = '/sbin/{0}_testsystemd.sh'.format(rstr)
# ubuntu already had since trusty some bits of systemd but was
# still using upstart ...
# we need to be a bit more careful that just testing that systemd
# is present
_script = textwrap.dedent(
'''\
#!/usr/bin/env bash
set -x
if ! command -v systemctl 1>/dev/null 2>/dev/null;then exit 2;fi
for i in \\
/run/systemd/journal/dev-log\\
/run/systemd/journal/flushed\\
/run/systemd/journal/kernel-seqnum\\
/run/systemd/journal/socket\\
/run/systemd/journal/stdout\\
/var/run/systemd/journal/dev-log\\
/var/run/systemd/journal/flushed\\
/var/run/systemd/journal/kernel-seqnum\\
/var/run/systemd/journal/socket\\
/var/run/systemd/journal/stdout\\
;do\\
if test -e ${i};then exit 0;fi
done
if test -d /var/systemd/system;then exit 0;fi
exit 2
''')
result = run_all(
name, 'tee {0}'.format(script), path=path,
stdin=_script, python_shell=True)
if result['retcode'] == 0:
result = run_all(name,
'sh -c "chmod +x {0};{0}"'''.format(script),
path=path,
python_shell=True)
else:
raise CommandExecutionError(
'lxc {0} failed to copy initd tester'.format(name))
run_all(name,
'sh -c \'if [ -f "{0}" ];then rm -f "{0}";fi\''
''.format(script),
path=path,
ignore_retcode=True,
python_shell=True)
if result['retcode'] != 0:
error = ('Unable to determine if the container \'{0}\''
' was running systemd, assmuming it is not.'
''.format(name))
if result['stderr']:
error += ': {0}'.format(result['stderr'])
# only cache result if we got a known exit code
if result['retcode'] in (0, 2):
__context__[k] = ret = not result['retcode']
return ret
def systemd_running_state(name, path=None):
'''
Get the operational state of a systemd based container
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.systemd_running_state ubuntu
'''
try:
ret = run_all(name,
'systemctl is-system-running',
path=path,
ignore_retcode=True)['stdout']
except CommandExecutionError:
ret = ''
return ret
def test_sd_started_state(name, path=None):
'''
Test if a systemd container is fully started
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.test_sd_started_state ubuntu
'''
qstate = systemd_running_state(name, path=path)
if qstate in ('initializing', 'starting'):
return False
elif qstate == '':
return None
else:
return True
def test_bare_started_state(name, path=None):
'''
Test if a non systemd container is fully started
For now, it consists only to test if the container is attachable
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.test_bare_started_state ubuntu
'''
try:
ret = run_all(
name, 'ls', path=path, ignore_retcode=True
)['retcode'] == 0
except (CommandExecutionError,):
ret = None
return ret
def wait_started(name, path=None, timeout=300):
'''
Check that the system has fully inited
This is actually very important for systemD based containers
see https://github.com/saltstack/salt/issues/23847
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.wait_started ubuntu
'''
if not exists(name, path=path):
raise CommandExecutionError(
'Container {0} does does exists'.format(name))
if not state(name, path=path) == 'running':
raise CommandExecutionError(
'Container {0} is not running'.format(name))
ret = False
if running_systemd(name, path=path):
test_started = test_sd_started_state
logger = log.error
else:
test_started = test_bare_started_state
logger = log.debug
now = time.time()
expire = now + timeout
now = time.time()
started = test_started(name, path=path)
while time.time() < expire and not started:
time.sleep(0.3)
started = test_started(name, path=path)
if started is None:
logger(
'Assuming %s is started, although we failed to detect that'
' is fully started correctly', name)
ret = True
else:
ret = started
return ret
def _needs_install(name, path=None):
ret = 0
has_minion = retcode(name,
'which salt-minion',
path=path,
ignore_retcode=True)
# we assume that installing is when no minion is running
# but testing the executable presence is not enougth for custom
# installs where the bootstrap can do much more than installing
# the bare salt binaries.
if has_minion:
processes = run_stdout(name, "ps aux", path=path)
if 'salt-minion' not in processes:
ret = 1
else:
retcode(name, 'salt-call --local service.stop salt-minion')
else:
ret = 1
return ret
def bootstrap(name,
config=None,
approve_key=True,
install=True,
pub_key=None,
priv_key=None,
bootstrap_url=None,
force_install=False,
unconditional_install=False,
path=None,
bootstrap_delay=None,
bootstrap_args=None,
bootstrap_shell=None):
'''
Install and configure salt in a container.
config
Minion configuration options. By default, the ``master`` option is set
to the target host's master.
approve_key
Request a pre-approval of the generated minion key. Requires
that the salt-master be configured to either auto-accept all keys or
expect a signing request from the target host. Default: ``True``
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
pub_key
Explicit public key to pressed the minion with (optional).
This can be either a filepath or a string representing the key
priv_key
Explicit private key to pressed the minion with (optional).
This can be either a filepath or a string representing the key
bootstrap_delay
Delay in seconds between end of container creation and bootstrapping.
Useful when waiting for container to obtain a DHCP lease.
.. versionadded:: 2015.5.0
bootstrap_url
url, content or filepath to the salt bootstrap script
bootstrap_args
salt bootstrap script arguments
bootstrap_shell
shell to execute the script into
install
Whether to attempt a full installation of salt-minion if needed.
force_install
Force installation even if salt-minion is detected,
this is the way to run vendor bootstrap scripts even
if a salt minion is already present in the container
unconditional_install
Run the script even if the container seems seeded
CLI Examples:
.. code-block:: bash
salt 'minion' lxc.bootstrap container_name [config=config_data] \\
[approve_key=(True|False)] [install=(True|False)]
'''
wait_started(name, path=path)
if bootstrap_delay is not None:
try:
log.info('LXC %s: bootstrap_delay: %s', name, bootstrap_delay)
time.sleep(bootstrap_delay)
except TypeError:
# Bad input, but assume since a value was passed that
# a delay was desired, and sleep for 5 seconds
time.sleep(5)
c_info = info(name, path=path)
if not c_info:
return None
# default set here as we cannot set them
# in def as it can come from a chain of procedures.
if bootstrap_args:
# custom bootstrap args can be totally customized, and user could
# have inserted the placeholder for the config directory.
# For example, some salt bootstrap script do not use at all -c
if '{0}' not in bootstrap_args:
bootstrap_args += ' -c {0}'
else:
bootstrap_args = '-c {0}'
if not bootstrap_shell:
bootstrap_shell = 'sh'
orig_state = _ensure_running(name, path=path)
if not orig_state:
return orig_state
if not force_install:
needs_install = _needs_install(name, path=path)
else:
needs_install = True
seeded = retcode(name,
'test -e \'{0}\''.format(SEED_MARKER),
path=path,
chroot_fallback=True,
ignore_retcode=True) == 0
tmp = tempfile.mkdtemp()
if seeded and not unconditional_install:
ret = True
else:
ret = False
cfg_files = __salt__['seed.mkconfig'](
config, tmp=tmp, id_=name, approve_key=approve_key,
pub_key=pub_key, priv_key=priv_key)
if needs_install or force_install or unconditional_install:
if install:
rstr = __salt__['test.random_hash']()
configdir = '/var/tmp/.c_{0}'.format(rstr)
cmd = 'install -m 0700 -d {0}'.format(configdir)
if run_all(
name, cmd, path=path, python_shell=False
)['retcode'] != 0:
log.error('tmpdir %s creation failed %s', configdir, cmd)
return False
bs_ = __salt__['config.gather_bootstrap_script'](
bootstrap=bootstrap_url)
script = '/sbin/{0}_bootstrap.sh'.format(rstr)
copy_to(name, bs_, script, path=path)
result = run_all(name,
'sh -c "chmod +x {0}"'.format(script),
path=path,
python_shell=True)
copy_to(name, cfg_files['config'],
os.path.join(configdir, 'minion'),
path=path)
copy_to(name, cfg_files['privkey'],
os.path.join(configdir, 'minion.pem'),
path=path)
copy_to(name, cfg_files['pubkey'],
os.path.join(configdir, 'minion.pub'),
path=path)
bootstrap_args = bootstrap_args.format(configdir)
cmd = ('{0} {2} {1}'
.format(bootstrap_shell,
bootstrap_args.replace("'", "''"),
script))
# log ASAP the forged bootstrap command which can be wrapped
# out of the output in case of unexpected problem
log.info('Running %s in LXC container \'%s\'', cmd, name)
ret = retcode(name, cmd, output_loglevel='info',
path=path, use_vt=True) == 0
run_all(name,
'sh -c \'if [ -f "{0}" ];then rm -f "{0}";fi\''
''.format(script),
path=path,
ignore_retcode=True,
python_shell=True)
else:
ret = False
else:
minion_config = salt.config.minion_config(cfg_files['config'])
pki_dir = minion_config['pki_dir']
copy_to(name,
cfg_files['config'],
'/etc/salt/minion',
path=path)
copy_to(name,
cfg_files['privkey'],
os.path.join(pki_dir, 'minion.pem'),
path=path)
copy_to(name,
cfg_files['pubkey'],
os.path.join(pki_dir, 'minion.pub'),
path=path)
run(name,
'salt-call --local service.enable salt-minion',
path=path,
python_shell=False)
ret = True
shutil.rmtree(tmp)
if orig_state == 'stopped':
stop(name, path=path)
elif orig_state == 'frozen':
freeze(name, path=path)
# mark seeded upon successful install
if ret:
run(name,
'touch \'{0}\''.format(SEED_MARKER),
path=path,
python_shell=False)
return ret
def attachable(name, path=None):
'''
Return True if the named container can be attached to via the lxc-attach
command
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt 'minion' lxc.attachable ubuntu
'''
cachekey = 'lxc.attachable{0}{1}'.format(name, path)
try:
return __context__[cachekey]
except KeyError:
_ensure_exists(name, path=path)
# Can't use run() here because it uses attachable() and would
# endlessly recurse, resulting in a traceback
log.debug('Checking if LXC container %s is attachable', name)
cmd = 'lxc-attach'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' --clear-env -n {0} -- /usr/bin/env'.format(name)
result = __salt__['cmd.retcode'](cmd,
python_shell=False,
output_loglevel='quiet',
ignore_retcode=True) == 0
__context__[cachekey] = result
return __context__[cachekey]
def _run(name,
cmd,
output=None,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=None,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
Common logic for lxc.run functions
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
'''
orig_state = state(name, path=path)
try:
if attachable(name, path=path):
ret = __salt__['container_resource.run'](
name,
cmd,
path=path,
container_type=__virtualname__,
exec_driver=EXEC_DRIVER,
output=output,
no_start=no_start,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
ignore_retcode=ignore_retcode,
use_vt=use_vt,
keep_env=keep_env)
else:
if not chroot_fallback:
raise CommandExecutionError(
'{0} is not attachable.'.format(name))
rootfs = info(name, path=path).get('rootfs')
# Set context var to make cmd.run_chroot run cmd.run instead of
# cmd.run_all.
__context__['cmd.run_chroot.func'] = __salt__['cmd.run']
ret = __salt__['cmd.run_chroot'](rootfs,
cmd,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
ignore_retcode=ignore_retcode)
except Exception:
raise
finally:
# Make sure we honor preserve_state, even if there was an exception
new_state = state(name, path=path)
if preserve_state:
if orig_state == 'stopped' and new_state != 'stopped':
stop(name, path=path)
elif orig_state == 'frozen' and new_state != 'frozen':
freeze(name, start=True, path=path)
if output in (None, 'all'):
return ret
else:
return ret[output]
def run(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.8.0
Run :mod:`cmd.run <salt.modules.cmdmod.run>` within a container
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed in stderr if the command being run
does not exist. If no output is returned using this function, try using
:mod:`lxc.run_stderr <salt.modules.lxc.run_stderr>` or
:mod:`lxc.run_all <salt.modules.lxc.run_all>`.
name
Name of the container in which to run the command
cmd
Command to run
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console. Assumes
``output=all``.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
CLI Example:
.. code-block:: bash
salt myminion lxc.run mycontainer 'ifconfig -a'
'''
return _run(name,
cmd,
path=path,
output=None,
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def run_stdout(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.5.0
Run :mod:`cmd.run_stdout <salt.modules.cmdmod.run_stdout>` within a container
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed in stderr if the command being run
does not exist. If no output is returned using this function, try using
:mod:`lxc.run_stderr <salt.modules.lxc.run_stderr>` or
:mod:`lxc.run_all <salt.modules.lxc.run_all>`.
name
Name of the container in which to run the command
cmd
Command to run
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console
``output=all``.
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
CLI Example:
.. code-block:: bash
salt myminion lxc.run_stdout mycontainer 'ifconfig -a'
'''
return _run(name,
cmd,
path=path,
output='stdout',
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def run_stderr(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.5.0
Run :mod:`cmd.run_stderr <salt.modules.cmdmod.run_stderr>` within a container
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed if the command being run does not
exist.
name
Name of the container in which to run the command
cmd
Command to run
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console
``output=all``.
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
CLI Example:
.. code-block:: bash
salt myminion lxc.run_stderr mycontainer 'ip addr show'
'''
return _run(name,
cmd,
path=path,
output='stderr',
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def retcode(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.5.0
Run :mod:`cmd.retcode <salt.modules.cmdmod.retcode>` within a container
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed in stderr if the command being run
does not exist. If the retcode is nonzero and not what was expected,
try using :mod:`lxc.run_stderr <salt.modules.lxc.run_stderr>`
or :mod:`lxc.run_all <salt.modules.lxc.run_all>`.
name
Name of the container in which to run the command
cmd
Command to run
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console
``output=all``.
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
CLI Example:
.. code-block:: bash
salt myminion lxc.retcode mycontainer 'ip addr show'
'''
return _run(name,
cmd,
output='retcode',
path=path,
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def run_all(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.5.0
Run :mod:`cmd.run_all <salt.modules.cmdmod.run_all>` within a container
.. note::
While the command is run within the container, it is initiated from the
host. Therefore, the PID in the return dict is from the host, not from
the container.
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed in stderr if the command being run
does not exist.
name
Name of the container in which to run the command
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
cmd
Command to run
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console
``output=all``.
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
CLI Example:
.. code-block:: bash
salt myminion lxc.run_all mycontainer 'ip addr show'
'''
return _run(name,
cmd,
output='all',
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
path=path,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def _get_md5(name, path):
'''
Get the MD5 checksum of a file from a container
'''
output = run_stdout(name, 'md5sum "{0}"'.format(path),
chroot_fallback=True,
ignore_retcode=True)
try:
return output.split()[0]
except IndexError:
# Destination file does not exist or could not be accessed
return None
def copy_to(name, source, dest, overwrite=False, makedirs=False, path=None):
'''
.. versionchanged:: 2015.8.0
Function renamed from ``lxc.cp`` to ``lxc.copy_to`` for consistency
with other container types. ``lxc.cp`` will continue to work, however.
For versions 2015.2.x and earlier, use ``lxc.cp``.
Copy a file or directory from the host into a container
name
Container name
source
File to be copied to the container
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
dest
Destination on the container. Must be an absolute path.
.. versionchanged:: 2015.5.0
If the destination is a directory, the file will be copied into
that directory.
overwrite : False
Unless this option is set to ``True``, then if a file exists at the
location specified by the ``dest`` argument, an error will be raised.
.. versionadded:: 2015.8.0
makedirs : False
Create the parent directory on the container if it does not already
exist.
.. versionadded:: 2015.5.0
CLI Example:
.. code-block:: bash
salt 'minion' lxc.copy_to /tmp/foo /root/foo
salt 'minion' lxc.cp /tmp/foo /root/foo
'''
_ensure_running(name, no_start=True, path=path)
return __salt__['container_resource.copy_to'](
name,
source,
dest,
container_type=__virtualname__,
path=path,
exec_driver=EXEC_DRIVER,
overwrite=overwrite,
makedirs=makedirs)
cp = salt.utils.functools.alias_function(copy_to, 'cp')
def read_conf(conf_file, out_format='simple'):
'''
Read in an LXC configuration file. By default returns a simple, unsorted
dict, but can also return a more detailed structure including blank lines
and comments.
out_format:
set to 'simple' if you need the old and unsupported behavior.
This won't support the multiple lxc values (eg: multiple network nics)
CLI Examples:
.. code-block:: bash
salt 'minion' lxc.read_conf /etc/lxc/mycontainer.conf
salt 'minion' lxc.read_conf /etc/lxc/mycontainer.conf out_format=commented
'''
ret_commented = []
ret_simple = {}
with salt.utils.files.fopen(conf_file, 'r') as fp_:
for line in salt.utils.data.decode(fp_.readlines()):
if '=' not in line:
ret_commented.append(line)
continue
comps = line.split('=')
value = '='.join(comps[1:]).strip()
comment = None
if value.strip().startswith('#'):
vcomps = value.strip().split('#')
value = vcomps[1].strip()
comment = '#'.join(vcomps[1:]).strip()
ret_commented.append({comps[0].strip(): {
'value': value,
'comment': comment,
}})
else:
ret_commented.append({comps[0].strip(): value})
ret_simple[comps[0].strip()] = value
if out_format == 'simple':
return ret_simple
return ret_commented
def write_conf(conf_file, conf):
'''
Write out an LXC configuration file
This is normally only used internally. The format of the data structure
must match that which is returned from ``lxc.read_conf()``, with
``out_format`` set to ``commented``.
An example might look like:
.. code-block:: python
[
{'lxc.utsname': '$CONTAINER_NAME'},
'# This is a commented line\\n',
'\\n',
{'lxc.mount': '$CONTAINER_FSTAB'},
{'lxc.rootfs': {'comment': 'This is another test',
'value': 'This is another test'}},
'\\n',
{'lxc.network.type': 'veth'},
{'lxc.network.flags': 'up'},
{'lxc.network.link': 'br0'},
{'lxc.network.mac': '$CONTAINER_MACADDR'},
{'lxc.network.ipv4': '$CONTAINER_IPADDR'},
{'lxc.network.name': '$CONTAINER_DEVICENAME'},
]
CLI Example:
.. code-block:: bash
salt 'minion' lxc.write_conf /etc/lxc/mycontainer.conf \\
out_format=commented
'''
if not isinstance(conf, list):
raise SaltInvocationError('Configuration must be passed as a list')
# construct the content prior to write to the file
# to avoid half written configs
content = ''
for line in conf:
if isinstance(line, (six.text_type, six.string_types)):
content += line
elif isinstance(line, dict):
for key in list(line.keys()):
out_line = None
if isinstance(
line[key],
(six.text_type, six.string_types, six.integer_types, float)
):
out_line = ' = '.join((key, "{0}".format(line[key])))
elif isinstance(line[key], dict):
out_line = ' = '.join((key, line[key]['value']))
if 'comment' in line[key]:
out_line = ' # '.join((out_line, line[key]['comment']))
if out_line:
content += out_line
content += '\n'
with salt.utils.files.fopen(conf_file, 'w') as fp_:
fp_.write(salt.utils.stringutils.to_str(content))
return {}
def edit_conf(conf_file,
out_format='simple',
read_only=False,
lxc_config=None,
**kwargs):
'''
Edit an LXC configuration file. If a setting is already present inside the
file, its value will be replaced. If it does not exist, it will be appended
to the end of the file. Comments and blank lines will be kept in-tact if
they already exist in the file.
out_format:
Set to simple if you need backward compatibility (multiple items for a
simple key is not supported)
read_only:
return only the edited configuration without applying it
to the underlying lxc configuration file
lxc_config:
List of dict containning lxc configuration items
For network configuration, you also need to add the device it belongs
to, otherwise it will default to eth0.
Also, any change to a network parameter will result in the whole
network reconfiguration to avoid mismatchs, be aware of that !
After the file is edited, its contents will be returned. By default, it
will be returned in ``simple`` format, meaning an unordered dict (which
may not represent the actual file order). Passing in an ``out_format`` of
``commented`` will return a data structure which accurately represents the
order and content of the file.
CLI Example:
.. code-block:: bash
salt 'minion' lxc.edit_conf /etc/lxc/mycontainer.conf \\
out_format=commented lxc.network.type=veth
salt 'minion' lxc.edit_conf /etc/lxc/mycontainer.conf \\
out_format=commented \\
lxc_config="[{'lxc.network.name': 'eth0', \\
'lxc.network.ipv4': '1.2.3.4'},
{'lxc.network.name': 'eth2', \\
'lxc.network.ipv4': '1.2.3.5',\\
'lxc.network.gateway': '1.2.3.1'}]"
'''
data = []
try:
conf = read_conf(conf_file, out_format=out_format)
except Exception:
conf = []
if not lxc_config:
lxc_config = []
lxc_config = copy.deepcopy(lxc_config)
# search if we want to access net config
# in that case, we will replace all the net configuration
net_config = []
for lxc_kws in lxc_config + [kwargs]:
net_params = {}
for kwarg in [a for a in lxc_kws]:
if kwarg.startswith('__'):
continue
if kwarg.startswith('lxc.network.'):
net_params[kwarg] = lxc_kws[kwarg]
lxc_kws.pop(kwarg, None)
if net_params:
net_config.append(net_params)
nic_opts = salt.utils.odict.OrderedDict()
for params in net_config:
dev = params.get('lxc.network.name', DEFAULT_NIC)
dev_opts = nic_opts.setdefault(dev, salt.utils.odict.OrderedDict())
for param in params:
opt = param.replace('lxc.network.', '')
opt = {'hwaddr': 'mac'}.get(opt, opt)
dev_opts[opt] = params[param]
net_changes = []
if nic_opts:
net_changes = _config_list(conf, only_net=True,
**{'network_profile': DEFAULT_NIC,
'nic_opts': nic_opts})
if net_changes:
lxc_config.extend(net_changes)
for line in conf:
if not isinstance(line, dict):
data.append(line)
continue
else:
for key in list(line.keys()):
val = line[key]
if net_changes and key.startswith('lxc.network.'):
continue
found = False
for ix in range(len(lxc_config)):
kw = lxc_config[ix]
if key in kw:
found = True
data.append({key: kw[key]})
del kw[key]
if not found:
data.append({key: val})
for lxc_kws in lxc_config:
for kwarg in lxc_kws:
data.append({kwarg: lxc_kws[kwarg]})
if read_only:
return data
write_conf(conf_file, data)
return read_conf(conf_file, out_format)
def reboot(name, path=None):
'''
Reboot a container.
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Examples:
.. code-block:: bash
salt 'minion' lxc.reboot myvm
'''
ret = {'result': True,
'changes': {},
'comment': '{0} rebooted'.format(name)}
does_exist = exists(name, path=path)
if does_exist and (state(name, path=path) == 'running'):
try:
stop(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
ret['result'] = False
return ret
if does_exist and (state(name, path=path) != 'running'):
try:
start(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
ret['result'] = False
return ret
ret['changes'][name] = 'rebooted'
return ret
def reconfigure(name,
cpu=None,
cpuset=None,
cpushare=None,
memory=None,
profile=None,
network_profile=None,
nic_opts=None,
bridge=None,
gateway=None,
autostart=None,
utsname=None,
rootfs=None,
path=None,
**kwargs):
'''
Reconfigure a container.
This only applies to a few property
name
Name of the container.
utsname
utsname of the container.
.. versionadded:: 2016.3.0
rootfs
rootfs of the container.
.. versionadded:: 2016.3.0
cpu
Select a random number of cpu cores and assign it to the cpuset, if the
cpuset option is set then this option will be ignored
cpuset
Explicitly define the cpus this container will be bound to
cpushare
cgroups cpu shares.
autostart
autostart container on reboot
memory
cgroups memory limit, in MB.
(0 for nolimit, None for old default 1024MB)
gateway
the ipv4 gateway to use
the default does nothing more than lxcutils does
bridge
the bridge to use
the default does nothing more than lxcutils does
nic
Network interfaces profile (defined in config or pillar).
nic_opts
Extra options for network interfaces, will override
``{"eth0": {"mac": "aa:bb:cc:dd:ee:ff", "ipv4": "10.1.1.1", "ipv6": "2001:db8::ff00:42:8329"}}``
or
``{"eth0": {"mac": "aa:bb:cc:dd:ee:ff", "ipv4": "10.1.1.1/24", "ipv6": "2001:db8::ff00:42:8329"}}``
path
path to the container parent
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt-call -lall mc_lxc_fork.reconfigure foobar nic_opts="{'eth1': {'mac': '00:16:3e:dd:ee:44'}}" memory=4
'''
changes = {}
cpath = get_root_path(path)
path = os.path.join(cpath, name, 'config')
ret = {'name': name,
'comment': 'config for {0} up to date'.format(name),
'result': True,
'changes': changes}
profile = get_container_profile(copy.deepcopy(profile))
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, _marker)
profile_match = profile.pop(key, default)
# let kwarg overrides be the preferred choice
if kw_overrides_match is _marker:
return profile_match
return kw_overrides_match
if nic_opts is not None and not network_profile:
network_profile = DEFAULT_NIC
if autostart is not None:
autostart = select('autostart', autostart)
else:
autostart = 'keep'
if not utsname:
utsname = select('utsname', utsname)
if os.path.exists(path):
old_chunks = read_conf(path, out_format='commented')
make_kw = salt.utils.odict.OrderedDict([
('utsname', utsname),
('rootfs', rootfs),
('autostart', autostart),
('cpu', cpu),
('gateway', gateway),
('cpuset', cpuset),
('cpushare', cpushare),
('network_profile', network_profile),
('nic_opts', nic_opts),
('bridge', bridge)])
# match 0 and none as memory = 0 in lxc config is harmful
if memory:
make_kw['memory'] = memory
kw = salt.utils.odict.OrderedDict()
for key, val in six.iteritems(make_kw):
if val is not None:
kw[key] = val
new_cfg = _config_list(conf_tuples=old_chunks, **kw)
if new_cfg:
edit_conf(path, out_format='commented', lxc_config=new_cfg)
chunks = read_conf(path, out_format='commented')
if old_chunks != chunks:
ret['comment'] = '{0} lxc config updated'.format(name)
if state(name, path=path) == 'running':
cret = reboot(name, path=path)
ret['result'] = cret['result']
return ret
def apply_network_profile(name, network_profile, nic_opts=None, path=None):
'''
.. versionadded:: 2015.5.0
Apply a network profile to a container
network_profile
profile name or default values (dict)
nic_opts
values to override in defaults (dict)
indexed by nic card names
path
path to the container parent
.. versionadded:: 2015.8.0
CLI Examples:
.. code-block:: bash
salt 'minion' lxc.apply_network_profile web1 centos
salt 'minion' lxc.apply_network_profile web1 centos \\
nic_opts="{'eth0': {'mac': 'xx:xx:xx:xx:xx:xx'}}"
salt 'minion' lxc.apply_network_profile web1 \\
"{'eth0': {'mac': 'xx:xx:xx:xx:xx:yy'}}"
nic_opts="{'eth0': {'mac': 'xx:xx:xx:xx:xx:xx'}}"
The special case to disable use of ethernet nics:
.. code-block:: bash
salt 'minion' lxc.apply_network_profile web1 centos \\
"{eth0: {disable: true}}"
'''
cpath = get_root_path(path)
cfgpath = os.path.join(cpath, name, 'config')
before = []
with salt.utils.files.fopen(cfgpath, 'r') as fp_:
for line in fp_:
before.append(line)
lxcconfig = _LXCConfig(name=name, path=path)
old_net = lxcconfig._filter_data('lxc.network')
network_params = {}
for param in _network_conf(
conf_tuples=old_net,
network_profile=network_profile, nic_opts=nic_opts
):
network_params.update(param)
if network_params:
edit_conf(cfgpath, out_format='commented', **network_params)
after = []
with salt.utils.files.fopen(cfgpath, 'r') as fp_:
for line in fp_:
after.append(line)
diff = ''
for line in difflib.unified_diff(before,
after,
fromfile='before',
tofile='after'):
diff += line
return diff
def get_pid(name, path=None):
'''
Returns a container pid.
Throw an exception if the container isn't running.
CLI Example:
.. code-block:: bash
salt '*' lxc.get_pid name
'''
if name not in list_(limit='running', path=path):
raise CommandExecutionError('Container {0} is not running, can\'t determine PID'.format(name))
info = __salt__['cmd.run']('lxc-info -n {0}'.format(name)).split("\n")
pid = [line.split(':')[1].strip() for line in info if re.match(r'\s*PID', line)][0]
return pid
def add_veth(name, interface_name, bridge=None, path=None):
'''
Add a veth to a container.
Note : this function doesn't update the container config, just add the interface at runtime
name
Name of the container
interface_name
Name of the interface in the container
bridge
Name of the bridge to attach the interface to (facultative)
CLI Examples:
.. code-block:: bash
salt '*' lxc.add_veth container_name eth1 br1
salt '*' lxc.add_veth container_name eth1
'''
# Get container init PID
pid = get_pid(name, path=path)
# Generate a ramdom string for veth and ensure that is isn't present on the system
while True:
random_veth = 'veth'+''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(6))
if random_veth not in __salt__['network.interfaces']().keys():
break
# Check prerequisites
if not __salt__['file.directory_exists']('/var/run/'):
raise CommandExecutionError('Directory /var/run required for lxc.add_veth doesn\'t exists')
if not __salt__['file.file_exists']('/proc/{0}/ns/net'.format(pid)):
raise CommandExecutionError('Proc file for container {0} network namespace doesn\'t exists'.format(name))
if not __salt__['file.directory_exists']('/var/run/netns'):
__salt__['file.mkdir']('/var/run/netns')
# Ensure that the symlink is up to date (change on container restart)
if __salt__['file.is_link']('/var/run/netns/{0}'.format(name)):
__salt__['file.remove']('/var/run/netns/{0}'.format(name))
__salt__['file.symlink']('/proc/{0}/ns/net'.format(pid), '/var/run/netns/{0}'.format(name))
# Ensure that interface doesn't exists
interface_exists = 0 == __salt__['cmd.retcode']('ip netns exec {netns} ip address list {interface}'.format(
netns=name,
interface=interface_name
))
if interface_exists:
raise CommandExecutionError('Interface {interface} already exists in {container}'.format(
interface=interface_name,
container=name
))
# Create veth and bring it up
if __salt__['cmd.retcode']('ip link add name {veth} type veth peer name {veth}_c'.format(veth=random_veth)) != 0:
raise CommandExecutionError('Error while creating the veth pair {0}'.format(random_veth))
if __salt__['cmd.retcode']('ip link set dev {0} up'.format(random_veth)) != 0:
raise CommandExecutionError('Error while bringing up host-side veth {0}'.format(random_veth))
# Attach it to the container
attached = 0 == __salt__['cmd.retcode']('ip link set dev {veth}_c netns {container} name {interface_name}'.format(
veth=random_veth,
container=name,
interface_name=interface_name
))
if not attached:
raise CommandExecutionError('Error while attaching the veth {veth} to container {container}'.format(
veth=random_veth,
container=name
))
__salt__['file.remove']('/var/run/netns/{0}'.format(name))
if bridge is not None:
__salt__['bridge.addif'](bridge, random_veth)
|
saltstack/salt
|
salt/modules/lxc.py
|
create
|
python
|
def create(name,
config=None,
profile=None,
network_profile=None,
nic_opts=None,
**kwargs):
'''
Create a new container.
name
Name of the container
config
The config file to use for the container. Defaults to system-wide
config (usually in /etc/lxc/lxc.conf).
profile
Profile to use in container creation (see
:mod:`lxc.get_container_profile
<salt.modules.lxc.get_container_profile>`). Values in a profile will be
overridden by the **Container Creation Arguments** listed below.
network_profile
Network profile to use for container
.. versionadded:: 2015.5.0
**Container Creation Arguments**
template
The template to use. For example, ``ubuntu`` or ``fedora``.
For a full list of available templates, check out
the :mod:`lxc.templates <salt.modules.lxc.templates>` function.
Conflicts with the ``image`` argument.
.. note::
The ``download`` template requires the following three parameters
to be defined in ``options``:
* **dist** - The name of the distribution
* **release** - Release name/version
* **arch** - Architecture of the container
The available images can be listed using the :mod:`lxc.images
<salt.modules.lxc.images>` function.
options
Template-specific options to pass to the lxc-create command. These
correspond to the long options (ones beginning with two dashes) that
the template script accepts. For example:
.. code-block:: bash
options='{"dist": "centos", "release": "6", "arch": "amd64"}'
For available template options, refer to the lxc template scripts
which are ususally located under ``/usr/share/lxc/templates``,
or run ``lxc-create -t <template> -h``.
image
A tar archive to use as the rootfs for the container. Conflicts with
the ``template`` argument.
backing
The type of storage to use. Set to ``lvm`` to use an LVM group.
Defaults to filesystem within /var/lib/lxc.
fstype
Filesystem type to use on LVM logical volume
size : 1G
Size of the volume to create. Only applicable if ``backing=lvm``.
vgname : lxc
Name of the LVM volume group in which to create the volume for this
container. Only applicable if ``backing=lvm``.
lvname
Name of the LVM logical volume in which to create the volume for this
container. Only applicable if ``backing=lvm``.
thinpool
Name of a pool volume that will be used for thin-provisioning this
container. Only applicable if ``backing=lvm``.
nic_opts
give extra opts overriding network profile values
path
parent path for the container creation (default: /var/lib/lxc)
zfsroot
Name of the ZFS root in which to create the volume for this container.
Only applicable if ``backing=zfs``. (default: tank/lxc)
.. versionadded:: 2015.8.0
'''
# Required params for 'download' template
download_template_deps = ('dist', 'release', 'arch')
cmd = 'lxc-create -n {0}'.format(name)
profile = get_container_profile(copy.deepcopy(profile))
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, None)
profile_match = profile.pop(key, default)
# Return the profile match if the the kwarg match was None, as the
# lxc.present state will pass these kwargs set to None by default.
if kw_overrides_match is None:
return profile_match
return kw_overrides_match
path = select('path')
if exists(name, path=path):
raise CommandExecutionError(
'Container \'{0}\' already exists'.format(name)
)
tvg = select('vgname')
vgname = tvg if tvg else __salt__['config.get']('lxc.vgname')
# The 'template' and 'image' params conflict
template = select('template')
image = select('image')
if template and image:
raise SaltInvocationError(
'Only one of \'template\' and \'image\' is permitted'
)
elif not any((template, image, profile)):
raise SaltInvocationError(
'At least one of \'template\', \'image\', and \'profile\' is '
'required'
)
options = select('options') or {}
backing = select('backing')
if vgname and not backing:
backing = 'lvm'
lvname = select('lvname')
thinpool = select('thinpool')
fstype = select('fstype')
size = select('size', '1G')
zfsroot = select('zfsroot')
if backing in ('dir', 'overlayfs', 'btrfs', 'zfs'):
fstype = None
size = None
# some backends won't support some parameters
if backing in ('aufs', 'dir', 'overlayfs', 'btrfs'):
lvname = vgname = thinpool = None
if image:
img_tar = __salt__['cp.cache_file'](image)
template = os.path.join(
os.path.dirname(salt.__file__),
'templates',
'lxc',
'salt_tarball')
options['imgtar'] = img_tar
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
if not os.path.exists(path):
os.makedirs(path)
if config:
cmd += ' -f {0}'.format(config)
if template:
cmd += ' -t {0}'.format(template)
if backing:
backing = backing.lower()
cmd += ' -B {0}'.format(backing)
if backing in ('zfs',):
if zfsroot:
cmd += ' --zfsroot {0}'.format(zfsroot)
if backing in ('lvm',):
if lvname:
cmd += ' --lvname {0}'.format(lvname)
if vgname:
cmd += ' --vgname {0}'.format(vgname)
if thinpool:
cmd += ' --thinpool {0}'.format(thinpool)
if backing not in ('dir', 'overlayfs'):
if fstype:
cmd += ' --fstype {0}'.format(fstype)
if size:
cmd += ' --fssize {0}'.format(size)
if options:
if template == 'download':
missing_deps = [x for x in download_template_deps
if x not in options]
if missing_deps:
raise SaltInvocationError(
'Missing params in \'options\' dict: {0}'
.format(', '.join(missing_deps))
)
cmd += ' --'
for key, val in six.iteritems(options):
cmd += ' --{0} {1}'.format(key, val)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
# please do not merge extra conflicting stuff
# inside those two line (ret =, return)
return _after_ignition_network_profile(cmd,
ret,
name,
network_profile,
path,
nic_opts)
|
Create a new container.
name
Name of the container
config
The config file to use for the container. Defaults to system-wide
config (usually in /etc/lxc/lxc.conf).
profile
Profile to use in container creation (see
:mod:`lxc.get_container_profile
<salt.modules.lxc.get_container_profile>`). Values in a profile will be
overridden by the **Container Creation Arguments** listed below.
network_profile
Network profile to use for container
.. versionadded:: 2015.5.0
**Container Creation Arguments**
template
The template to use. For example, ``ubuntu`` or ``fedora``.
For a full list of available templates, check out
the :mod:`lxc.templates <salt.modules.lxc.templates>` function.
Conflicts with the ``image`` argument.
.. note::
The ``download`` template requires the following three parameters
to be defined in ``options``:
* **dist** - The name of the distribution
* **release** - Release name/version
* **arch** - Architecture of the container
The available images can be listed using the :mod:`lxc.images
<salt.modules.lxc.images>` function.
options
Template-specific options to pass to the lxc-create command. These
correspond to the long options (ones beginning with two dashes) that
the template script accepts. For example:
.. code-block:: bash
options='{"dist": "centos", "release": "6", "arch": "amd64"}'
For available template options, refer to the lxc template scripts
which are ususally located under ``/usr/share/lxc/templates``,
or run ``lxc-create -t <template> -h``.
image
A tar archive to use as the rootfs for the container. Conflicts with
the ``template`` argument.
backing
The type of storage to use. Set to ``lvm`` to use an LVM group.
Defaults to filesystem within /var/lib/lxc.
fstype
Filesystem type to use on LVM logical volume
size : 1G
Size of the volume to create. Only applicable if ``backing=lvm``.
vgname : lxc
Name of the LVM volume group in which to create the volume for this
container. Only applicable if ``backing=lvm``.
lvname
Name of the LVM logical volume in which to create the volume for this
container. Only applicable if ``backing=lvm``.
thinpool
Name of a pool volume that will be used for thin-provisioning this
container. Only applicable if ``backing=lvm``.
nic_opts
give extra opts overriding network profile values
path
parent path for the container creation (default: /var/lib/lxc)
zfsroot
Name of the ZFS root in which to create the volume for this container.
Only applicable if ``backing=zfs``. (default: tank/lxc)
.. versionadded:: 2015.8.0
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/lxc.py#L1774-L1984
|
[
"def exists(name, path=None):\n '''\n Returns whether the named container exists.\n\n path\n path to the container parent directory (default: /var/lib/lxc)\n\n .. versionadded:: 2015.8.0\n\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' lxc.exists name\n '''\n\n _exists = name in ls_(path=path)\n # container may be just created but we did cached earlier the\n # lxc-ls results\n if not _exists:\n _exists = name in ls_(cache=False, path=path)\n return _exists\n",
"def get_container_profile(name=None, **kwargs):\n '''\n .. versionadded:: 2015.5.0\n\n Gather a pre-configured set of container configuration parameters. If no\n arguments are passed, an empty profile is returned.\n\n Profiles can be defined in the minion or master config files, or in pillar\n or grains, and are loaded using :mod:`config.get\n <salt.modules.config.get>`. The key under which LXC profiles must be\n configured is ``lxc.container_profile.profile_name``. An example container\n profile would be as follows:\n\n .. code-block:: yaml\n\n lxc.container_profile:\n ubuntu:\n template: ubuntu\n backing: lvm\n vgname: lxc\n size: 1G\n\n Parameters set in a profile can be overridden by passing additional\n container creation arguments (such as the ones passed to :mod:`lxc.create\n <salt.modules.lxc.create>`) to this function.\n\n A profile can be defined either as the name of the profile, or a dictionary\n of variable names and values. See the :ref:`LXC Tutorial\n <tutorial-lxc-profiles>` for more information on how to use LXC profiles.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt-call lxc.get_container_profile centos\n salt-call lxc.get_container_profile ubuntu template=ubuntu backing=overlayfs\n '''\n profile = _get_profile('container_profile', name, **kwargs)\n return profile\n",
"def select(key, default=None):\n kw_overrides_match = kw_overrides.pop(key, None)\n profile_match = profile.pop(key, default)\n # Return the profile match if the the kwarg match was None, as the\n # lxc.present state will pass these kwargs set to None by default.\n if kw_overrides_match is None:\n return profile_match\n return kw_overrides_match\n"
] |
# -*- coding: utf-8 -*-
'''
Control Linux Containers via Salt
:depends: lxc package for distribution
lxc >= 1.0 (even beta alpha) is required
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import datetime
import copy
import string
import textwrap
import difflib
import logging
import tempfile
import os
import pipes
import time
import shutil
import re
import random
# Import salt libs
import salt.utils.args
import salt.utils.cloud
import salt.utils.data
import salt.utils.dictupdate
import salt.utils.files
import salt.utils.functools
import salt.utils.hashutils
import salt.utils.network
import salt.utils.odict
import salt.utils.path
import salt.utils.stringutils
from salt.exceptions import CommandExecutionError, SaltInvocationError
import salt.config
from salt.utils.versions import LooseVersion as _LooseVersion
# Import 3rd-party libs
from salt.ext import six
# pylint: disable=import-error,no-name-in-module
from salt.ext.six.moves import range # pylint: disable=redefined-builtin
from salt.ext.six.moves.urllib.parse import urlparse as _urlparse
# pylint: enable=import-error,no-name-in-module
# Set up logging
log = logging.getLogger(__name__)
# Don't shadow built-in's.
__func_alias__ = {
'list_': 'list',
'ls_': 'ls'
}
__virtualname__ = 'lxc'
DEFAULT_NIC = 'eth0'
DEFAULT_BR = 'br0'
SEED_MARKER = '/lxc.initial_seed'
EXEC_DRIVER = 'lxc-attach'
DEFAULT_PATH = '/var/lib/lxc'
_marker = object()
def __virtual__():
if salt.utils.path.which('lxc-start'):
return __virtualname__
# To speed up the whole thing, we decided to not use the
# subshell way and assume things are in place for lxc
# Discussion made by @kiorky and @thatch45
# lxc-version presence is not sufficient, in lxc1.0 alpha
# (precise backports), we have it and it is sufficient
# for the module to execute.
# elif salt.utils.path.which('lxc-version'):
# passed = False
# try:
# passed = subprocess.check_output(
# 'lxc-version').split(':')[1].strip() >= '1.0'
# except Exception:
# pass
# if not passed:
# log.warning('Support for lxc < 1.0 may be incomplete.')
# return 'lxc'
# return False
#
return (False, 'The lxc execution module cannot be loaded: the lxc-start binary is not in the path.')
def get_root_path(path):
'''
Get the configured lxc root for containers
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.get_root_path
'''
if not path:
path = __opts__.get('lxc.root_path', DEFAULT_PATH)
return path
def version():
'''
Return the actual lxc client version
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.version
'''
k = 'lxc.version'
if not __context__.get(k, None):
cversion = __salt__['cmd.run_all']('lxc-info --version')
if not cversion['retcode']:
ver = _LooseVersion(cversion['stdout'])
if ver < _LooseVersion('1.0'):
raise CommandExecutionError('LXC should be at least 1.0')
__context__[k] = "{0}".format(ver)
return __context__.get(k, None)
def _clear_context():
'''
Clear any lxc variables set in __context__
'''
for var in [x for x in __context__ if x.startswith('lxc.')]:
log.trace('Clearing __context__[\'%s\']', var)
__context__.pop(var, None)
def _ip_sort(ip):
'''Ip sorting'''
idx = '001'
if ip == '127.0.0.1':
idx = '200'
if ip == '::1':
idx = '201'
elif '::' in ip:
idx = '100'
return '{0}___{1}'.format(idx, ip)
def search_lxc_bridges():
'''
Search which bridges are potentially available as LXC bridges
CLI Example:
.. code-block:: bash
salt '*' lxc.search_lxc_bridges
'''
bridges = __context__.get('lxc.bridges', None)
# either match not yet called or no bridges were found
# to handle the case where lxc was not installed on the first
# call
if not bridges:
bridges = set()
running_bridges = set()
bridges.add(DEFAULT_BR)
try:
output = __salt__['cmd.run_all']('brctl show')
for line in output['stdout'].splitlines()[1:]:
if not line.startswith(' '):
running_bridges.add(line.split()[0].strip())
except (SaltInvocationError, CommandExecutionError):
pass
for ifc, ip in six.iteritems(
__grains__.get('ip_interfaces', {})
):
if ifc in running_bridges:
bridges.add(ifc)
elif os.path.exists(
'/sys/devices/virtual/net/{0}/bridge'.format(ifc)
):
bridges.add(ifc)
bridges = list(bridges)
# if we found interfaces that have lxc in their names
# we filter them as being the potential lxc bridges
# we also try to default on br0 on other cases
def sort_bridges(a):
pref = 'z'
if 'lxc' in a:
pref = 'a'
elif 'br0' == a:
pref = 'c'
return '{0}_{1}'.format(pref, a)
bridges.sort(key=sort_bridges)
__context__['lxc.bridges'] = bridges
return bridges
def search_lxc_bridge():
'''
Search the first bridge which is potentially available as LXC bridge
CLI Example:
.. code-block:: bash
salt '*' lxc.search_lxc_bridge
'''
return search_lxc_bridges()[0]
def _get_salt_config(config, **kwargs):
if not config:
config = kwargs.get('minion', {})
if not config:
config = {}
config.setdefault('master',
kwargs.get('master',
__opts__.get('master',
__opts__['id'])))
config.setdefault(
'master_port',
kwargs.get('master_port',
__opts__.get('master_port',
__opts__.get('ret_port',
__opts__.get('4506')))))
if not config['master']:
config = {}
return config
def cloud_init_interface(name, vm_=None, **kwargs):
'''
Interface between salt.cloud.lxc driver and lxc.init
``vm_`` is a mapping of vm opts in the salt.cloud format
as documented for the lxc driver.
This can be used either:
- from the salt cloud driver
- because you find the argument to give easier here
than using directly lxc.init
.. warning::
BE REALLY CAREFUL CHANGING DEFAULTS !!!
IT'S A RETRO COMPATIBLE INTERFACE WITH
THE SALT CLOUD DRIVER (ask kiorky).
name
name of the lxc container to create
pub_key
public key to preseed the minion with.
Can be the keycontent or a filepath
priv_key
private key to preseed the minion with.
Can be the keycontent or a filepath
path
path to the container parent directory (default: /var/lib/lxc)
.. versionadded:: 2015.8.0
profile
:ref:`profile <tutorial-lxc-profiles-container>` selection
network_profile
:ref:`network profile <tutorial-lxc-profiles-network>` selection
nic_opts
per interface settings compatibles with
network profile (ipv4/ipv6/link/gateway/mac/netmask)
eg::
- {'eth0': {'mac': '00:16:3e:01:29:40',
'gateway': None, (default)
'link': 'br0', (default)
'gateway': None, (default)
'netmask': '', (default)
'ip': '22.1.4.25'}}
unconditional_install
given to lxc.bootstrap (see relative doc)
force_install
given to lxc.bootstrap (see relative doc)
config
any extra argument for the salt minion config
dnsservers
list of DNS servers to set inside the container
dns_via_dhcp
do not set the dns servers, let them be set by the dhcp.
autostart
autostart the container at boot time
password
administrative password for the container
bootstrap_delay
delay before launching bootstrap script at Container init
.. warning::
Legacy but still supported options:
from_container
which container we use as a template
when running lxc.clone
image
which template do we use when we
are using lxc.create. This is the default
mode unless you specify something in from_container
backing
which backing store to use.
Values can be: overlayfs, dir(default), lvm, zfs, brtfs
fstype
When using a blockdevice level backing store,
which filesystem to use on
size
When using a blockdevice level backing store,
which size for the filesystem to use on
snapshot
Use snapshot when cloning the container source
vgname
if using LVM: vgname
lvname
if using LVM: lvname
thinpool:
if using LVM: thinpool
ip
ip for the primary nic
mac
mac address for the primary nic
netmask
netmask for the primary nic (24)
= ``vm_.get('netmask', '24')``
bridge
bridge for the primary nic (lxcbr0)
gateway
network gateway for the container
additional_ips
additional ips which will be wired on the main bridge (br0)
which is connected to internet.
Be aware that you may use manual virtual mac addresses
providen by you provider (online, ovh, etc).
This is a list of mappings {ip: '', mac: '', netmask:''}
Set gateway to None and an interface with a gateway
to escape from another interface that eth0.
eg::
- {'mac': '00:16:3e:01:29:40',
'gateway': None, (default)
'link': 'br0', (default)
'netmask': '', (default)
'ip': '22.1.4.25'}
users
administrative users for the container
default: [root] and [root, ubuntu] on ubuntu
default_nic
name of the first interface, you should
really not override this
CLI Example:
.. code-block:: bash
salt '*' lxc.cloud_init_interface foo
'''
if vm_ is None:
vm_ = {}
vm_ = copy.deepcopy(vm_)
vm_ = salt.utils.dictupdate.update(vm_, kwargs)
profile_data = copy.deepcopy(
vm_.get('lxc_profile',
vm_.get('profile', {})))
if not isinstance(profile_data, (dict, six.string_types)):
profile_data = {}
profile = get_container_profile(profile_data)
def _cloud_get(k, default=None):
return vm_.get(k, profile.get(k, default))
if name is None:
name = vm_['name']
# if we are on ubuntu, default to ubuntu
default_template = ''
if __grains__.get('os', '') in ['Ubuntu']:
default_template = 'ubuntu'
image = _cloud_get('image')
if not image:
_cloud_get('template', default_template)
backing = _cloud_get('backing', 'dir')
if image:
profile['template'] = image
vgname = _cloud_get('vgname', None)
if vgname:
profile['vgname'] = vgname
if backing:
profile['backing'] = backing
snapshot = _cloud_get('snapshot', False)
autostart = bool(_cloud_get('autostart', True))
dnsservers = _cloud_get('dnsservers', [])
dns_via_dhcp = _cloud_get('dns_via_dhcp', True)
password = _cloud_get('password', 's3cr3t')
password_encrypted = _cloud_get('password_encrypted', False)
fstype = _cloud_get('fstype', None)
lvname = _cloud_get('lvname', None)
thinpool = _cloud_get('thinpool', None)
pub_key = _cloud_get('pub_key', None)
priv_key = _cloud_get('priv_key', None)
size = _cloud_get('size', '20G')
script = _cloud_get('script', None)
script_args = _cloud_get('script_args', None)
users = _cloud_get('users', None)
if users is None:
users = []
ssh_username = _cloud_get('ssh_username', None)
if ssh_username and (ssh_username not in users):
users.append(ssh_username)
network_profile = _cloud_get('network_profile', None)
nic_opts = kwargs.get('nic_opts', None)
netmask = _cloud_get('netmask', '24')
path = _cloud_get('path', None)
bridge = _cloud_get('bridge', None)
gateway = _cloud_get('gateway', None)
unconditional_install = _cloud_get('unconditional_install', False)
force_install = _cloud_get('force_install', True)
config = _get_salt_config(_cloud_get('config', {}), **vm_)
default_nic = _cloud_get('default_nic', DEFAULT_NIC)
# do the interface with lxc.init mainly via nic_opts
# to avoid extra and confusing extra use cases.
if not isinstance(nic_opts, dict):
nic_opts = salt.utils.odict.OrderedDict()
# have a reference to the default nic
eth0 = nic_opts.setdefault(default_nic,
salt.utils.odict.OrderedDict())
# lxc config is based of ifc order, be sure to use odicts.
if not isinstance(nic_opts, salt.utils.odict.OrderedDict):
bnic_opts = salt.utils.odict.OrderedDict()
bnic_opts.update(nic_opts)
nic_opts = bnic_opts
gw = None
# legacy salt.cloud scheme for network interfaces settings support
bridge = _cloud_get('bridge', None)
ip = _cloud_get('ip', None)
mac = _cloud_get('mac', None)
if ip:
fullip = ip
if netmask:
fullip += '/{0}'.format(netmask)
eth0['ipv4'] = fullip
if mac is not None:
eth0['mac'] = mac
for ix, iopts in enumerate(_cloud_get("additional_ips", [])):
ifh = "eth{0}".format(ix+1)
ethx = nic_opts.setdefault(ifh, {})
if gw is None:
gw = iopts.get('gateway', ethx.get('gateway', None))
if gw:
# only one and only one default gateway is allowed !
eth0.pop('gateway', None)
gateway = None
# even if the gateway if on default "eth0" nic
# and we popped it will work
# as we reinject or set it here.
ethx['gateway'] = gw
elink = iopts.get('link', ethx.get('link', None))
if elink:
ethx['link'] = elink
# allow dhcp
aip = iopts.get('ipv4', iopts.get('ip', None))
if aip:
ethx['ipv4'] = aip
nm = iopts.get('netmask', '')
if nm:
ethx['ipv4'] += '/{0}'.format(nm)
for i in ('mac', 'hwaddr'):
if i in iopts:
ethx['mac'] = iopts[i]
break
if 'mac' not in ethx:
ethx['mac'] = salt.utils.network.gen_mac()
# last round checking for unique gateway and such
gw = None
for ethx in [a for a in nic_opts]:
ndata = nic_opts[ethx]
if gw:
ndata.pop('gateway', None)
if 'gateway' in ndata:
gw = ndata['gateway']
gateway = None
# only use a default bridge / gateway if we configured them
# via the legacy salt cloud configuration style.
# On other cases, we should rely on settings provided by the new
# salt lxc network profile style configuration which can
# be also be overridden or a per interface basis via the nic_opts dict.
if bridge:
eth0['link'] = bridge
if gateway:
eth0['gateway'] = gateway
#
lxc_init_interface = {}
lxc_init_interface['name'] = name
lxc_init_interface['config'] = config
lxc_init_interface['memory'] = _cloud_get('memory', 0) # nolimit
lxc_init_interface['pub_key'] = pub_key
lxc_init_interface['priv_key'] = priv_key
lxc_init_interface['nic_opts'] = nic_opts
for clone_from in ['clone_from', 'clone', 'from_container']:
# clone_from should default to None if not available
lxc_init_interface['clone_from'] = _cloud_get(clone_from, None)
if lxc_init_interface['clone_from'] is not None:
break
lxc_init_interface['profile'] = profile
lxc_init_interface['snapshot'] = snapshot
lxc_init_interface['dnsservers'] = dnsservers
lxc_init_interface['fstype'] = fstype
lxc_init_interface['path'] = path
lxc_init_interface['vgname'] = vgname
lxc_init_interface['size'] = size
lxc_init_interface['lvname'] = lvname
lxc_init_interface['thinpool'] = thinpool
lxc_init_interface['force_install'] = force_install
lxc_init_interface['unconditional_install'] = (
unconditional_install
)
lxc_init_interface['bootstrap_url'] = script
lxc_init_interface['bootstrap_args'] = script_args
lxc_init_interface['bootstrap_shell'] = _cloud_get('bootstrap_shell', 'sh')
lxc_init_interface['bootstrap_delay'] = _cloud_get('bootstrap_delay', None)
lxc_init_interface['autostart'] = autostart
lxc_init_interface['users'] = users
lxc_init_interface['password'] = password
lxc_init_interface['password_encrypted'] = password_encrypted
# be sure not to let objects goes inside the return
# as this return will be msgpacked for use in the runner !
lxc_init_interface['network_profile'] = network_profile
for i in ['cpu', 'cpuset', 'cpushare']:
if _cloud_get(i, None):
try:
lxc_init_interface[i] = vm_[i]
except KeyError:
lxc_init_interface[i] = profile[i]
return lxc_init_interface
def _get_profile(key, name, **kwargs):
if isinstance(name, dict):
profilename = name.pop('name', None)
return _get_profile(key, profilename, **name)
if name is None:
profile_match = {}
else:
profile_match = \
__salt__['config.get'](
'lxc.{1}:{0}'.format(name, key),
default=None,
merge='recurse'
)
if profile_match is None:
# No matching profile, make the profile an empty dict so that
# overrides can be applied below.
profile_match = {}
if not isinstance(profile_match, dict):
raise CommandExecutionError('lxc.{0} must be a dictionary'.format(key))
# Overlay the kwargs to override matched profile data
overrides = salt.utils.args.clean_kwargs(**copy.deepcopy(kwargs))
profile_match = salt.utils.dictupdate.update(
copy.deepcopy(profile_match),
overrides
)
return profile_match
def get_container_profile(name=None, **kwargs):
'''
.. versionadded:: 2015.5.0
Gather a pre-configured set of container configuration parameters. If no
arguments are passed, an empty profile is returned.
Profiles can be defined in the minion or master config files, or in pillar
or grains, and are loaded using :mod:`config.get
<salt.modules.config.get>`. The key under which LXC profiles must be
configured is ``lxc.container_profile.profile_name``. An example container
profile would be as follows:
.. code-block:: yaml
lxc.container_profile:
ubuntu:
template: ubuntu
backing: lvm
vgname: lxc
size: 1G
Parameters set in a profile can be overridden by passing additional
container creation arguments (such as the ones passed to :mod:`lxc.create
<salt.modules.lxc.create>`) to this function.
A profile can be defined either as the name of the profile, or a dictionary
of variable names and values. See the :ref:`LXC Tutorial
<tutorial-lxc-profiles>` for more information on how to use LXC profiles.
CLI Example:
.. code-block:: bash
salt-call lxc.get_container_profile centos
salt-call lxc.get_container_profile ubuntu template=ubuntu backing=overlayfs
'''
profile = _get_profile('container_profile', name, **kwargs)
return profile
def get_network_profile(name=None, **kwargs):
'''
.. versionadded:: 2015.5.0
Gather a pre-configured set of network configuration parameters. If no
arguments are passed, the following default profile is returned:
.. code-block:: python
{'eth0': {'link': 'br0', 'type': 'veth', 'flags': 'up'}}
Profiles can be defined in the minion or master config files, or in pillar
or grains, and are loaded using :mod:`config.get
<salt.modules.config.get>`. The key under which LXC profiles must be
configured is ``lxc.network_profile``. An example network profile would be
as follows:
.. code-block:: yaml
lxc.network_profile.centos:
eth0:
link: br0
type: veth
flags: up
To disable networking entirely:
.. code-block:: yaml
lxc.network_profile.centos:
eth0:
disable: true
Parameters set in a profile can be overridden by passing additional
arguments to this function.
A profile can be passed either as the name of the profile, or a
dictionary of variable names and values. See the :ref:`LXC Tutorial
<tutorial-lxc-profiles>` for more information on how to use network
profiles.
.. warning::
The ``ipv4``, ``ipv6``, ``gateway``, and ``link`` (bridge) settings in
network profiles will only work if the container doesn't redefine the
network configuration (for example in
``/etc/sysconfig/network-scripts/ifcfg-<interface_name>`` on
RHEL/CentOS, or ``/etc/network/interfaces`` on Debian/Ubuntu/etc.)
CLI Example:
.. code-block:: bash
salt-call lxc.get_network_profile default
'''
profile = _get_profile('network_profile', name, **kwargs)
return profile
def _rand_cpu_str(cpu):
'''
Return a random subset of cpus for the cpuset config
'''
cpu = int(cpu)
avail = __salt__['status.nproc']()
if cpu < avail:
return '0-{0}'.format(avail)
to_set = set()
while len(to_set) < cpu:
choice = random.randint(0, avail - 1)
if choice not in to_set:
to_set.add(six.text_type(choice))
return ','.join(sorted(to_set))
def _network_conf(conf_tuples=None, **kwargs):
'''
Network configuration defaults
network_profile
as for containers, we can either call this function
either with a network_profile dict or network profile name
in the kwargs
nic_opts
overrides or extra nics in the form {nic_name: {set: tings}
'''
nic = kwargs.get('network_profile', None)
ret = []
nic_opts = kwargs.get('nic_opts', {})
if nic_opts is None:
# coming from elsewhere
nic_opts = {}
if not conf_tuples:
conf_tuples = []
old = _get_veths(conf_tuples)
if not old:
old = {}
# if we have a profile name, get the profile and load the network settings
# this will obviously by default look for a profile called "eth0"
# or by what is defined in nic_opts
# and complete each nic settings by sane defaults
if nic and isinstance(nic, (six.string_types, dict)):
nicp = get_network_profile(nic)
else:
nicp = {}
if DEFAULT_NIC not in nicp:
nicp[DEFAULT_NIC] = {}
kwargs = copy.deepcopy(kwargs)
gateway = kwargs.pop('gateway', None)
bridge = kwargs.get('bridge', None)
if nic_opts:
for dev, args in six.iteritems(nic_opts):
ethx = nicp.setdefault(dev, {})
try:
ethx = salt.utils.dictupdate.update(ethx, args)
except AttributeError:
raise SaltInvocationError('Invalid nic_opts configuration')
ifs = [a for a in nicp]
ifs += [a for a in old if a not in nicp]
ifs.sort()
gateway_set = False
for dev in ifs:
args = nicp.get(dev, {})
opts = nic_opts.get(dev, {}) if nic_opts else {}
old_if = old.get(dev, {})
disable = opts.get('disable', args.get('disable', False))
if disable:
continue
mac = opts.get('mac',
opts.get('hwaddr',
args.get('mac',
args.get('hwaddr', ''))))
type_ = opts.get('type', args.get('type', ''))
flags = opts.get('flags', args.get('flags', ''))
link = opts.get('link', args.get('link', ''))
ipv4 = opts.get('ipv4', args.get('ipv4', ''))
ipv6 = opts.get('ipv6', args.get('ipv6', ''))
infos = salt.utils.odict.OrderedDict([
('lxc.network.type', {
'test': not type_,
'value': type_,
'old': old_if.get('lxc.network.type'),
'default': 'veth'}),
('lxc.network.name', {
'test': False,
'value': dev,
'old': dev,
'default': dev}),
('lxc.network.flags', {
'test': not flags,
'value': flags,
'old': old_if.get('lxc.network.flags'),
'default': 'up'}),
('lxc.network.link', {
'test': not link,
'value': link,
'old': old_if.get('lxc.network.link'),
'default': search_lxc_bridge()}),
('lxc.network.hwaddr', {
'test': not mac,
'value': mac,
'old': old_if.get('lxc.network.hwaddr'),
'default': salt.utils.network.gen_mac()}),
('lxc.network.ipv4', {
'test': not ipv4,
'value': ipv4,
'old': old_if.get('lxc.network.ipv4', ''),
'default': None}),
('lxc.network.ipv6', {
'test': not ipv6,
'value': ipv6,
'old': old_if.get('lxc.network.ipv6', ''),
'default': None})])
# for each parameter, if not explicitly set, the
# config value present in the LXC configuration should
# take precedence over the profile configuration
for info in list(infos.keys()):
bundle = infos[info]
if bundle['test']:
if bundle['old']:
bundle['value'] = bundle['old']
elif bundle['default']:
bundle['value'] = bundle['default']
for info, data in six.iteritems(infos):
if data['value']:
ret.append({info: data['value']})
for key, val in six.iteritems(args):
if key == 'link' and bridge:
val = bridge
val = opts.get(key, val)
if key in [
'type', 'flags', 'name',
'gateway', 'mac', 'link', 'ipv4', 'ipv6'
]:
continue
ret.append({'lxc.network.{0}'.format(key): val})
# gateway (in automode) must be appended following network conf !
if not gateway:
gateway = args.get('gateway', None)
if gateway is not None and not gateway_set:
ret.append({'lxc.network.ipv4.gateway': gateway})
# only one network gateway ;)
gateway_set = True
# normally, this won't happen
# set the gateway if specified even if we did
# not managed the network underlying
if gateway is not None and not gateway_set:
ret.append({'lxc.network.ipv4.gateway': gateway})
# only one network gateway ;)
gateway_set = True
new = _get_veths(ret)
# verify that we did not loose the mac settings
for iface in [a for a in new]:
ndata = new[iface]
nmac = ndata.get('lxc.network.hwaddr', '')
ntype = ndata.get('lxc.network.type', '')
omac, otype = '', ''
if iface in old:
odata = old[iface]
omac = odata.get('lxc.network.hwaddr', '')
otype = odata.get('lxc.network.type', '')
# default for network type is setted here
# attention not to change the network type
# without a good and explicit reason to.
if otype and not ntype:
ntype = otype
if not ntype:
ntype = 'veth'
new[iface]['lxc.network.type'] = ntype
if omac and not nmac:
new[iface]['lxc.network.hwaddr'] = omac
ret = []
for val in six.itervalues(new):
for row in val:
ret.append(salt.utils.odict.OrderedDict([(row, val[row])]))
# on old versions of lxc, still support the gateway auto mode
# if we didn't explicitly say no to
# (lxc.network.ipv4.gateway: auto)
if _LooseVersion(version()) <= _LooseVersion('1.0.7') and \
True not in ['lxc.network.ipv4.gateway' in a for a in ret] and \
True in ['lxc.network.ipv4' in a for a in ret]:
ret.append({'lxc.network.ipv4.gateway': 'auto'})
return ret
def _get_lxc_default_data(**kwargs):
kwargs = copy.deepcopy(kwargs)
ret = {}
for k in ['utsname', 'rootfs']:
val = kwargs.get(k, None)
if val is not None:
ret['lxc.{0}'.format(k)] = val
autostart = kwargs.get('autostart')
# autostart can have made in kwargs, but with the None
# value which is invalid, we need an explicit boolean
# autostart = on is the default.
if autostart is None:
autostart = True
# we will set the regular lxc marker to restart container at
# machine (re)boot only if we did not explicitly ask
# not to touch to the autostart settings via
# autostart == 'keep'
if autostart != 'keep':
if autostart:
ret['lxc.start.auto'] = '1'
else:
ret['lxc.start.auto'] = '0'
memory = kwargs.get('memory')
if memory is not None:
# converting the config value from MB to bytes
ret['lxc.cgroup.memory.limit_in_bytes'] = memory * 1024 * 1024
cpuset = kwargs.get('cpuset')
if cpuset:
ret['lxc.cgroup.cpuset.cpus'] = cpuset
cpushare = kwargs.get('cpushare')
cpu = kwargs.get('cpu')
if cpushare:
ret['lxc.cgroup.cpu.shares'] = cpushare
if cpu and not cpuset:
ret['lxc.cgroup.cpuset.cpus'] = _rand_cpu_str(cpu)
return ret
def _config_list(conf_tuples=None, only_net=False, **kwargs):
'''
Return a list of dicts from the salt level configurations
conf_tuples
_LXCConfig compatible list of entries which can contain
- string line
- tuple (lxc config param,value)
- dict of one entry: {lxc config param: value)
only_net
by default we add to the tuples a reflection of both
the real config if avalaible and a certain amount of
default values like the cpu parameters, the memory
and etc.
On the other hand, we also no matter the case reflect
the network configuration computed from the actual config if
available and given values.
if no_default_loads is set, we will only
reflect the network configuration back to the conf tuples
list
'''
# explicit cast
only_net = bool(only_net)
if not conf_tuples:
conf_tuples = []
kwargs = copy.deepcopy(kwargs)
ret = []
if not only_net:
default_data = _get_lxc_default_data(**kwargs)
for k, val in six.iteritems(default_data):
ret.append({k: val})
net_datas = _network_conf(conf_tuples=conf_tuples, **kwargs)
ret.extend(net_datas)
return ret
def _get_veths(net_data):
'''
Parse the nic setup inside lxc conf tuples back to a dictionary indexed by
network interface
'''
if isinstance(net_data, dict):
net_data = list(net_data.items())
nics = salt.utils.odict.OrderedDict()
current_nic = salt.utils.odict.OrderedDict()
no_names = True
for item in net_data:
if item and isinstance(item, dict):
item = list(item.items())[0]
# skip LXC configuration comment lines, and play only with tuples conf
elif isinstance(item, six.string_types):
# deal with reflection of commented lxc configs
sitem = item.strip()
if sitem.startswith('#') or not sitem:
continue
elif '=' in item:
item = tuple([a.strip() for a in item.split('=', 1)])
if item[0] == 'lxc.network.type':
current_nic = salt.utils.odict.OrderedDict()
if item[0] == 'lxc.network.name':
no_names = False
nics[item[1].strip()] = current_nic
current_nic[item[0].strip()] = item[1].strip()
# if not ethernet card name has been collected, assuming we collected
# data for eth0
if no_names and current_nic:
nics[DEFAULT_NIC] = current_nic
return nics
class _LXCConfig(object):
'''
LXC configuration data
'''
pattern = re.compile(r'^(\S+)(\s*)(=)(\s*)(.*)')
non_interpretable_pattern = re.compile(r'^((#.*)|(\s*))$')
def __init__(self, **kwargs):
kwargs = copy.deepcopy(kwargs)
self.name = kwargs.pop('name', None)
path = get_root_path(kwargs.get('path', None))
self.data = []
if self.name:
self.path = os.path.join(path, self.name, 'config')
if os.path.isfile(self.path):
with salt.utils.files.fopen(self.path) as fhr:
for line in salt.utils.data.decode(fhr.readlines()):
match = self.pattern.findall((line.strip()))
if match:
self.data.append((match[0][0], match[0][-1]))
match = self.non_interpretable_pattern.findall(
(line.strip()))
if match:
self.data.append(('', match[0][0]))
else:
self.path = None
def _replace(key, val):
if val:
self._filter_data(key)
self.data.append((key, val))
default_data = _get_lxc_default_data(**kwargs)
for key, val in six.iteritems(default_data):
_replace(key, val)
old_net = self._filter_data('lxc.network')
net_datas = _network_conf(conf_tuples=old_net, **kwargs)
if net_datas:
for row in net_datas:
self.data.extend(list(row.items()))
# be sure to reset harmful settings
for idx in ['lxc.cgroup.memory.limit_in_bytes']:
if not default_data.get(idx):
self._filter_data(idx)
def as_string(self):
chunks = ('{0[0]}{1}{0[1]}'.format(item, (' = ' if item[0] else '')) for item in self.data)
return '\n'.join(chunks) + '\n'
def write(self):
if self.path:
content = self.as_string()
# 2 step rendering to be sure not to open/wipe the config
# before as_string succeeds.
with salt.utils.files.fopen(self.path, 'w') as fic:
fic.write(salt.utils.stringutils.to_str(content))
fic.flush()
def tempfile(self):
# this might look like the function name is shadowing the
# module, but it's not since the method belongs to the class
ntf = tempfile.NamedTemporaryFile()
ntf.write(self.as_string())
ntf.flush()
return ntf
def _filter_data(self, pattern):
'''
Removes parameters which match the pattern from the config data
'''
removed = []
filtered = []
for param in self.data:
if not param[0].startswith(pattern):
filtered.append(param)
else:
removed.append(param)
self.data = filtered
return removed
def _get_base(**kwargs):
'''
If the needed base does not exist, then create it, if it does exist
create nothing and return the name of the base lxc container so
it can be cloned.
'''
profile = get_container_profile(copy.deepcopy(kwargs.get('profile')))
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, _marker)
profile_match = profile.pop(key, default)
# let kwarg overrides be the preferred choice
if kw_overrides_match is _marker:
return profile_match
return kw_overrides_match
template = select('template')
image = select('image')
vgname = select('vgname')
path = kwargs.get('path', None)
# remove the above three variables from kwargs, if they exist, to avoid
# duplicates if create() is invoked below.
for param in ('path', 'image', 'vgname', 'template'):
kwargs.pop(param, None)
if image:
proto = _urlparse(image).scheme
img_tar = __salt__['cp.cache_file'](image)
img_name = os.path.basename(img_tar)
hash_ = salt.utils.hashutils.get_hash(
img_tar,
__salt__['config.get']('hash_type'))
name = '__base_{0}_{1}_{2}'.format(proto, img_name, hash_)
if not exists(name, path=path):
create(name, template=template, image=image,
path=path, vgname=vgname, **kwargs)
if vgname:
rootfs = os.path.join('/dev', vgname, name)
edit_conf(info(name, path=path)['config'],
out_format='commented', **{'lxc.rootfs': rootfs})
return name
elif template:
name = '__base_{0}'.format(template)
if not exists(name, path=path):
create(name, template=template, image=image, path=path,
vgname=vgname, **kwargs)
if vgname:
rootfs = os.path.join('/dev', vgname, name)
edit_conf(info(name, path=path)['config'],
out_format='commented', **{'lxc.rootfs': rootfs})
return name
return ''
def init(name,
config=None,
cpuset=None,
cpushare=None,
memory=None,
profile=None,
network_profile=None,
nic_opts=None,
cpu=None,
autostart=True,
password=None,
password_encrypted=None,
users=None,
dnsservers=None,
searchdomains=None,
bridge=None,
gateway=None,
pub_key=None,
priv_key=None,
force_install=False,
unconditional_install=False,
bootstrap_delay=None,
bootstrap_args=None,
bootstrap_shell=None,
bootstrap_url=None,
**kwargs):
'''
Initialize a new container.
This is a partial idempotent function as if it is already provisioned, we
will reset a bit the lxc configuration file but much of the hard work will
be escaped as markers will prevent re-execution of harmful tasks.
name
Name of the container
image
A tar archive to use as the rootfs for the container. Conflicts with
the ``template`` argument.
cpus
Select a random number of cpu cores and assign it to the cpuset, if the
cpuset option is set then this option will be ignored
cpuset
Explicitly define the cpus this container will be bound to
cpushare
cgroups cpu shares
autostart
autostart container on reboot
memory
cgroups memory limit, in MB
.. versionchanged:: 2015.5.0
If no value is passed, no limit is set. In earlier Salt versions,
not passing this value causes a 1024MB memory limit to be set, and
it was necessary to pass ``memory=0`` to set no limit.
gateway
the ipv4 gateway to use
the default does nothing more than lxcutils does
bridge
the bridge to use
the default does nothing more than lxcutils does
network_profile
Network profile to use for the container
.. versionadded:: 2015.5.0
nic_opts
Extra options for network interfaces, will override
``{"eth0": {"hwaddr": "aa:bb:cc:dd:ee:ff", "ipv4": "10.1.1.1", "ipv6": "2001:db8::ff00:42:8329"}}``
or
``{"eth0": {"hwaddr": "aa:bb:cc:dd:ee:ff", "ipv4": "10.1.1.1/24", "ipv6": "2001:db8::ff00:42:8329"}}``
users
Users for which the password defined in the ``password`` param should
be set. Can be passed as a comma separated list or a python list.
Defaults to just the ``root`` user.
password
Set the initial password for the users defined in the ``users``
parameter
password_encrypted : False
Set to ``True`` to denote a password hash instead of a plaintext
password
.. versionadded:: 2015.5.0
profile
A LXC profile (defined in config or pillar).
This can be either a real profile mapping or a string
to retrieve it in configuration
start
Start the newly-created container
dnsservers
list of dns servers to set in the container, default [] (no setting)
seed
Seed the container with the minion config. Default: ``True``
install
If salt-minion is not already installed, install it. Default: ``True``
config
Optional config parameters. By default, the id is set to
the name of the container.
master
salt master (default to minion's master)
master_port
salt master port (default to minion's master port)
pub_key
Explicit public key to preseed the minion with (optional).
This can be either a filepath or a string representing the key
priv_key
Explicit private key to preseed the minion with (optional).
This can be either a filepath or a string representing the key
approve_key
If explicit preseeding is not used;
Attempt to request key approval from the master. Default: ``True``
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
clone_from
Original from which to use a clone operation to create the container.
Default: ``None``
bootstrap_delay
Delay in seconds between end of container creation and bootstrapping.
Useful when waiting for container to obtain a DHCP lease.
.. versionadded:: 2015.5.0
bootstrap_url
See lxc.bootstrap
bootstrap_shell
See lxc.bootstrap
bootstrap_args
See lxc.bootstrap
force_install
Force installation even if salt-minion is detected,
this is the way to run vendor bootstrap scripts even
if a salt minion is already present in the container
unconditional_install
Run the script even if the container seems seeded
CLI Example:
.. code-block:: bash
salt 'minion' lxc.init name [cpuset=cgroups_cpuset] \\
[cpushare=cgroups_cpushare] [memory=cgroups_memory] \\
[nic=nic_profile] [profile=lxc_profile] \\
[nic_opts=nic_opts] [start=(True|False)] \\
[seed=(True|False)] [install=(True|False)] \\
[config=minion_config] [approve_key=(True|False) \\
[clone_from=original] [autostart=True] \\
[priv_key=/path_or_content] [pub_key=/path_or_content] \\
[bridge=lxcbr0] [gateway=10.0.3.1] \\
[dnsservers[dns1,dns2]] \\
[users=[foo]] [password='secret'] \\
[password_encrypted=(True|False)]
'''
ret = {'name': name,
'changes': {}}
profile = get_container_profile(copy.deepcopy(profile))
if not network_profile:
network_profile = profile.get('network_profile')
if not network_profile:
network_profile = DEFAULT_NIC
# Changes is a pointer to changes_dict['init']. This method is used so that
# we can have a list of changes as they are made, providing an ordered list
# of things that were changed.
changes_dict = {'init': []}
changes = changes_dict.get('init')
if users is None:
users = []
dusers = ['root']
for user in dusers:
if user not in users:
users.append(user)
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, _marker)
profile_match = profile.pop(key, default)
# let kwarg overrides be the preferred choice
if kw_overrides_match is _marker:
return profile_match
return kw_overrides_match
path = select('path')
bpath = get_root_path(path)
state_pre = state(name, path=path)
tvg = select('vgname')
vgname = tvg if tvg else __salt__['config.get']('lxc.vgname')
start_ = select('start', True)
autostart = select('autostart', autostart)
seed = select('seed', True)
install = select('install', True)
seed_cmd = select('seed_cmd')
salt_config = _get_salt_config(config, **kwargs)
approve_key = select('approve_key', True)
clone_from = select('clone_from')
# If using a volume group then set up to make snapshot cow clones
if vgname and not clone_from:
try:
kwargs['vgname'] = vgname
clone_from = _get_base(profile=profile, **kwargs)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = exc.strerror
if changes:
ret['changes'] = changes_dict
return ret
if not kwargs.get('snapshot') is False:
kwargs['snapshot'] = True
does_exist = exists(name, path=path)
to_reboot = False
remove_seed_marker = False
if does_exist:
pass
elif clone_from:
remove_seed_marker = True
try:
clone(name, clone_from, profile=profile, **kwargs)
changes.append({'create': 'Container cloned'})
except (SaltInvocationError, CommandExecutionError) as exc:
if 'already exists' in exc.strerror:
changes.append({'create': 'Container already exists'})
else:
ret['result'] = False
ret['comment'] = exc.strerror
if changes:
ret['changes'] = changes_dict
return ret
cfg = _LXCConfig(name=name, network_profile=network_profile,
nic_opts=nic_opts, bridge=bridge, path=path,
gateway=gateway, autostart=autostart,
cpuset=cpuset, cpushare=cpushare, memory=memory)
old_chunks = read_conf(cfg.path, out_format='commented')
cfg.write()
chunks = read_conf(cfg.path, out_format='commented')
if old_chunks != chunks:
to_reboot = True
else:
remove_seed_marker = True
cfg = _LXCConfig(network_profile=network_profile,
nic_opts=nic_opts, cpuset=cpuset, path=path,
bridge=bridge, gateway=gateway,
autostart=autostart,
cpushare=cpushare, memory=memory)
with cfg.tempfile() as cfile:
try:
create(name, config=cfile.name, profile=profile, **kwargs)
changes.append({'create': 'Container created'})
except (SaltInvocationError, CommandExecutionError) as exc:
if 'already exists' in exc.strerror:
changes.append({'create': 'Container already exists'})
else:
ret['comment'] = exc.strerror
if changes:
ret['changes'] = changes_dict
return ret
cpath = os.path.join(bpath, name, 'config')
old_chunks = []
if os.path.exists(cpath):
old_chunks = read_conf(cpath, out_format='commented')
new_cfg = _config_list(conf_tuples=old_chunks,
cpu=cpu,
network_profile=network_profile,
nic_opts=nic_opts, bridge=bridge,
cpuset=cpuset, cpushare=cpushare,
memory=memory)
if new_cfg:
edit_conf(cpath, out_format='commented', lxc_config=new_cfg)
chunks = read_conf(cpath, out_format='commented')
if old_chunks != chunks:
to_reboot = True
# last time to be sure any of our property is correctly applied
cfg = _LXCConfig(name=name, network_profile=network_profile,
nic_opts=nic_opts, bridge=bridge, path=path,
gateway=gateway, autostart=autostart,
cpuset=cpuset, cpushare=cpushare, memory=memory)
old_chunks = []
if os.path.exists(cfg.path):
old_chunks = read_conf(cfg.path, out_format='commented')
cfg.write()
chunks = read_conf(cfg.path, out_format='commented')
if old_chunks != chunks:
changes.append({'config': 'Container configuration updated'})
to_reboot = True
if to_reboot:
try:
stop(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
if changes:
ret['changes'] = changes_dict
return ret
if not does_exist or (does_exist and state(name, path=path) != 'running'):
try:
start(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
if changes:
ret['changes'] = changes_dict
return ret
if remove_seed_marker:
run(name,
'rm -f \'{0}\''.format(SEED_MARKER),
path=path,
chroot_fallback=False,
python_shell=False)
# set the default user/password, only the first time
if ret.get('result', True) and password:
gid = '/.lxc.initial_pass'
gids = [gid,
'/lxc.initial_pass',
'/.lxc.{0}.initial_pass'.format(name)]
if not any(retcode(name,
'test -e "{0}"'.format(x),
chroot_fallback=True,
path=path,
ignore_retcode=True) == 0
for x in gids):
# think to touch the default user generated by default templates
# which has a really unsecure passwords...
# root is defined as a member earlier in the code
for default_user in ['ubuntu']:
if (
default_user not in users and
retcode(name,
'id {0}'.format(default_user),
python_shell=False,
path=path,
chroot_fallback=True,
ignore_retcode=True) == 0
):
users.append(default_user)
for user in users:
try:
cret = set_password(name,
users=[user],
path=path,
password=password,
encrypted=password_encrypted)
except (SaltInvocationError, CommandExecutionError) as exc:
msg = '{0}: Failed to set password'.format(
user) + exc.strerror
# only hardfail in unrecoverable situation:
# root cannot be setted up
if user == 'root':
ret['comment'] = msg
ret['result'] = False
else:
log.debug(msg)
if ret.get('result', True):
changes.append({'password': 'Password(s) updated'})
if retcode(name,
('sh -c \'touch "{0}"; test -e "{0}"\''
.format(gid)),
path=path,
chroot_fallback=True,
ignore_retcode=True) != 0:
ret['comment'] = 'Failed to set password marker'
changes[-1]['password'] += '. ' + ret['comment'] + '.'
ret['result'] = False
# set dns servers if any, only the first time
if ret.get('result', True) and dnsservers:
# retro compatibility, test also old markers
gid = '/.lxc.initial_dns'
gids = [gid,
'/lxc.initial_dns',
'/lxc.{0}.initial_dns'.format(name)]
if not any(retcode(name,
'test -e "{0}"'.format(x),
chroot_fallback=True,
path=path,
ignore_retcode=True) == 0
for x in gids):
try:
set_dns(name,
path=path,
dnsservers=dnsservers,
searchdomains=searchdomains)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Failed to set DNS: ' + exc.strerror
ret['result'] = False
else:
changes.append({'dns': 'DNS updated'})
if retcode(name,
('sh -c \'touch "{0}"; test -e "{0}"\''
.format(gid)),
chroot_fallback=True,
path=path,
ignore_retcode=True) != 0:
ret['comment'] = 'Failed to set DNS marker'
changes[-1]['dns'] += '. ' + ret['comment'] + '.'
ret['result'] = False
# retro compatibility, test also old markers
if remove_seed_marker:
run(name,
'rm -f \'{0}\''.format(SEED_MARKER),
path=path,
python_shell=False)
gid = '/.lxc.initial_seed'
gids = [gid, '/lxc.initial_seed']
if (
any(retcode(name,
'test -e {0}'.format(x),
path=path,
chroot_fallback=True,
ignore_retcode=True) == 0
for x in gids) or not ret.get('result', True)
):
pass
elif seed or seed_cmd:
if seed:
try:
result = bootstrap(
name, config=salt_config, path=path,
approve_key=approve_key,
pub_key=pub_key, priv_key=priv_key,
install=install,
force_install=force_install,
unconditional_install=unconditional_install,
bootstrap_delay=bootstrap_delay,
bootstrap_url=bootstrap_url,
bootstrap_shell=bootstrap_shell,
bootstrap_args=bootstrap_args)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Bootstrap failed: ' + exc.strerror
ret['result'] = False
else:
if not result:
ret['comment'] = ('Bootstrap failed, see minion log for '
'more information')
ret['result'] = False
else:
changes.append(
{'bootstrap': 'Container successfully bootstrapped'}
)
elif seed_cmd:
try:
result = __salt__[seed_cmd](info(name, path=path)['rootfs'],
name,
salt_config)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = ('Bootstrap via seed_cmd \'{0}\' failed: {1}'
.format(seed_cmd, exc.strerror))
ret['result'] = False
else:
if not result:
ret['comment'] = ('Bootstrap via seed_cmd \'{0}\' failed, '
'see minion log for more information '
.format(seed_cmd))
ret['result'] = False
else:
changes.append(
{'bootstrap': 'Container successfully bootstrapped '
'using seed_cmd \'{0}\''
.format(seed_cmd)}
)
if ret.get('result', True) and not start_:
try:
stop(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
ret['result'] = False
state_post = state(name, path=path)
if state_pre != state_post:
changes.append({'state': {'old': state_pre, 'new': state_post}})
if ret.get('result', True):
ret['comment'] = ('Container \'{0}\' successfully initialized'
.format(name))
ret['result'] = True
if changes:
ret['changes'] = changes_dict
return ret
def cloud_init(name, vm_=None, **kwargs):
'''
Thin wrapper to lxc.init to be used from the saltcloud lxc driver
name
Name of the container
may be None and then guessed from saltcloud mapping
`vm_`
saltcloud mapping defaults for the vm
CLI Example:
.. code-block:: bash
salt '*' lxc.cloud_init foo
'''
init_interface = cloud_init_interface(name, vm_, **kwargs)
name = init_interface.pop('name', name)
return init(name, **init_interface)
def images(dist=None):
'''
.. versionadded:: 2015.5.0
List the available images for LXC's ``download`` template.
dist : None
Filter results to a single Linux distribution
CLI Examples:
.. code-block:: bash
salt myminion lxc.images
salt myminion lxc.images dist=centos
'''
out = __salt__['cmd.run_stdout'](
'lxc-create -n __imgcheck -t download -- --list',
ignore_retcode=True
)
if 'DIST' not in out:
raise CommandExecutionError(
'Unable to run the \'download\' template script. Is it installed?'
)
ret = {}
passed_header = False
for line in out.splitlines():
try:
distro, release, arch, variant, build_time = line.split()
except ValueError:
continue
if not passed_header:
if distro == 'DIST':
passed_header = True
continue
dist_list = ret.setdefault(distro, [])
dist_list.append({
'release': release,
'arch': arch,
'variant': variant,
'build_time': build_time,
})
if dist is not None:
return dict([(dist, ret.get(dist, []))])
return ret
def templates():
'''
.. versionadded:: 2015.5.0
List the available LXC template scripts installed on the minion
CLI Examples:
.. code-block:: bash
salt myminion lxc.templates
'''
try:
template_scripts = os.listdir('/usr/share/lxc/templates')
except OSError:
return []
else:
return [x[4:] for x in template_scripts if x.startswith('lxc-')]
def _after_ignition_network_profile(cmd,
ret,
name,
network_profile,
path,
nic_opts):
_clear_context()
if ret['retcode'] == 0 and exists(name, path=path):
if network_profile:
network_changes = apply_network_profile(name,
network_profile,
path=path,
nic_opts=nic_opts)
if network_changes:
log.info(
'Network changes from applying network profile \'%s\' '
'to newly-created container \'%s\':\n%s',
network_profile, name, network_changes
)
c_state = state(name, path=path)
return {'result': True,
'state': {'old': None, 'new': c_state}}
else:
if exists(name, path=path):
# destroy the container if it was partially created
cmd = 'lxc-destroy'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0}'.format(name)
__salt__['cmd.retcode'](cmd, python_shell=False)
raise CommandExecutionError(
'Container could not be created with cmd \'{0}\': {1}'
.format(cmd, ret['stderr'])
)
def clone(name,
orig,
profile=None,
network_profile=None,
nic_opts=None,
**kwargs):
'''
Create a new container as a clone of another container
name
Name of the container
orig
Name of the original container to be cloned
profile
Profile to use in container cloning (see
:mod:`lxc.get_container_profile
<salt.modules.lxc.get_container_profile>`). Values in a profile will be
overridden by the **Container Cloning Arguments** listed below.
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
**Container Cloning Arguments**
snapshot
Use Copy On Write snapshots (LVM)
size : 1G
Size of the volume to create. Only applicable if ``backing=lvm``.
backing
The type of storage to use. Set to ``lvm`` to use an LVM group.
Defaults to filesystem within /var/lib/lxc.
network_profile
Network profile to use for container
.. versionadded:: 2015.8.0
nic_opts
give extra opts overriding network profile values
.. versionadded:: 2015.8.0
CLI Examples:
.. code-block:: bash
salt '*' lxc.clone myclone orig=orig_container
salt '*' lxc.clone myclone orig=orig_container snapshot=True
'''
profile = get_container_profile(copy.deepcopy(profile))
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, None)
profile_match = profile.pop(key, default)
# let kwarg overrides be the preferred choice
if kw_overrides_match is None:
return profile_match
return kw_overrides_match
path = select('path')
if exists(name, path=path):
raise CommandExecutionError(
'Container \'{0}\' already exists'.format(name)
)
_ensure_exists(orig, path=path)
if state(orig, path=path) != 'stopped':
raise CommandExecutionError(
'Container \'{0}\' must be stopped to be cloned'.format(orig)
)
backing = select('backing')
snapshot = select('snapshot')
if backing in ('dir',):
snapshot = False
if not snapshot:
snapshot = ''
else:
snapshot = '-s'
size = select('size', '1G')
if backing in ('dir', 'overlayfs', 'btrfs'):
size = None
# LXC commands and options changed in 2.0 - CF issue #34086 for details
if _LooseVersion(version()) >= _LooseVersion('2.0'):
# https://linuxcontainers.org/lxc/manpages//man1/lxc-copy.1.html
cmd = 'lxc-copy'
cmd += ' {0} -n {1} -N {2}'.format(snapshot, orig, name)
else:
# https://linuxcontainers.org/lxc/manpages//man1/lxc-clone.1.html
cmd = 'lxc-clone'
cmd += ' {0} -o {1} -n {2}'.format(snapshot, orig, name)
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
if not os.path.exists(path):
os.makedirs(path)
if backing:
backing = backing.lower()
cmd += ' -B {0}'.format(backing)
if backing not in ('dir', 'overlayfs'):
if size:
cmd += ' -L {0}'.format(size)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
# please do not merge extra conflicting stuff
# inside those two line (ret =, return)
return _after_ignition_network_profile(cmd,
ret,
name,
network_profile,
path,
nic_opts)
def ls_(active=None, cache=True, path=None):
'''
Return a list of the containers available on the minion
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
active
If ``True``, return only active (i.e. running) containers
.. versionadded:: 2015.5.0
CLI Example:
.. code-block:: bash
salt '*' lxc.ls
salt '*' lxc.ls active=True
'''
contextvar = 'lxc.ls{0}'.format(path)
if active:
contextvar += '.active'
if cache and (contextvar in __context__):
return __context__[contextvar]
else:
ret = []
cmd = 'lxc-ls'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
if active:
cmd += ' --active'
output = __salt__['cmd.run_stdout'](cmd, python_shell=False)
for line in output.splitlines():
ret.extend(line.split())
__context__[contextvar] = ret
return ret
def list_(extra=False, limit=None, path=None):
'''
List containers classified by state
extra
Also get per-container specific info. This will change the return data.
Instead of returning a list of containers, a dictionary of containers
and each container's output from :mod:`lxc.info
<salt.modules.lxc.info>`.
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
limit
Return output matching a specific state (**frozen**, **running**, or
**stopped**).
.. versionadded:: 2015.5.0
CLI Examples:
.. code-block:: bash
salt '*' lxc.list
salt '*' lxc.list extra=True
salt '*' lxc.list limit=running
'''
ctnrs = ls_(path=path)
if extra:
stopped = {}
frozen = {}
running = {}
else:
stopped = []
frozen = []
running = []
ret = {'running': running,
'stopped': stopped,
'frozen': frozen}
for container in ctnrs:
cmd = 'lxc-info'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0}'.format(container)
c_info = __salt__['cmd.run'](
cmd,
python_shell=False,
output_loglevel='debug'
)
c_state = None
for line in c_info.splitlines():
stat = line.split(':')
if stat[0] in ('State', 'state'):
c_state = stat[1].strip()
break
if not c_state or (limit is not None and c_state.lower() != limit):
continue
if extra:
infos = info(container, path=path)
method = 'update'
value = {container: infos}
else:
method = 'append'
value = container
if c_state == 'STOPPED':
getattr(stopped, method)(value)
continue
if c_state == 'FROZEN':
getattr(frozen, method)(value)
continue
if c_state == 'RUNNING':
getattr(running, method)(value)
continue
if limit is not None:
return ret.get(limit, {} if extra else [])
return ret
def _change_state(cmd,
name,
expected,
stdin=_marker,
stdout=_marker,
stderr=_marker,
with_communicate=_marker,
use_vt=_marker,
path=None):
pre = state(name, path=path)
if pre == expected:
return {'result': True,
'state': {'old': expected, 'new': expected},
'comment': 'Container \'{0}\' already {1}'
.format(name, expected)}
if cmd == 'lxc-destroy':
# Kill the container first
scmd = 'lxc-stop'
if path:
scmd += ' -P {0}'.format(pipes.quote(path))
scmd += ' -k -n {0}'.format(name)
__salt__['cmd.run'](scmd,
python_shell=False)
if path and ' -P ' not in cmd:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0}'.format(name)
# certain lxc commands need to be taken with care (lxc-start)
# as te command itself mess with double forks; we must not
# communicate with it, but just wait for the exit status
pkwargs = {'python_shell': False,
'redirect_stderr': True,
'with_communicate': with_communicate,
'use_vt': use_vt,
'stdin': stdin,
'stdout': stdout}
for i in [a for a in pkwargs]:
val = pkwargs[i]
if val is _marker:
pkwargs.pop(i, None)
_cmdout = __salt__['cmd.run_all'](cmd, **pkwargs)
if _cmdout['retcode'] != 0:
raise CommandExecutionError(
'Error changing state for container \'{0}\' using command '
'\'{1}\': {2}'.format(name, cmd, _cmdout['stdout'])
)
if expected is not None:
# some commands do not wait, so we will
rcmd = 'lxc-wait'
if path:
rcmd += ' -P {0}'.format(pipes.quote(path))
rcmd += ' -n {0} -s {1}'.format(name, expected.upper())
__salt__['cmd.run'](rcmd, python_shell=False, timeout=30)
_clear_context()
post = state(name, path=path)
ret = {'result': post == expected,
'state': {'old': pre, 'new': post}}
return ret
def _ensure_exists(name, path=None):
'''
Raise an exception if the container does not exist
'''
if not exists(name, path=path):
raise CommandExecutionError(
'Container \'{0}\' does not exist'.format(name)
)
def _ensure_running(name, no_start=False, path=None):
'''
If the container is not currently running, start it. This function returns
the state that the container was in before changing
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
'''
_ensure_exists(name, path=path)
pre = state(name, path=path)
if pre == 'running':
# This will be a no-op but running the function will give us a pretty
# return dict.
return start(name, path=path)
elif pre == 'stopped':
if no_start:
raise CommandExecutionError(
'Container \'{0}\' is not running'.format(name)
)
return start(name, path=path)
elif pre == 'frozen':
if no_start:
raise CommandExecutionError(
'Container \'{0}\' is not running'.format(name)
)
return unfreeze(name, path=path)
def restart(name, path=None, lxc_config=None, force=False):
'''
.. versionadded:: 2015.5.0
Restart the named container. If the container was not running, the
container will merely be started.
name
The name of the container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
lxc_config
path to a lxc config file
config file will be guessed from container name otherwise
.. versionadded:: 2015.8.0
force : False
If ``True``, the container will be force-stopped instead of gracefully
shut down
CLI Example:
.. code-block:: bash
salt myminion lxc.restart name
'''
_ensure_exists(name, path=path)
orig_state = state(name, path=path)
if orig_state != 'stopped':
stop(name, kill=force, path=path)
ret = start(name, path=path, lxc_config=lxc_config)
ret['state']['old'] = orig_state
if orig_state != 'stopped':
ret['restarted'] = True
return ret
def start(name, **kwargs):
'''
Start the named container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
lxc_config
path to a lxc config file
config file will be guessed from container name otherwise
.. versionadded:: 2015.8.0
use_vt
run the command through VT
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.start name
'''
path = kwargs.get('path', None)
cpath = get_root_path(path)
lxc_config = kwargs.get('lxc_config', None)
cmd = 'lxc-start'
if not lxc_config:
lxc_config = os.path.join(cpath, name, 'config')
# we try to start, even without config, if global opts are there
if os.path.exists(lxc_config):
cmd += ' -f {0}'.format(pipes.quote(lxc_config))
cmd += ' -d'
_ensure_exists(name, path=path)
if state(name, path=path) == 'frozen':
raise CommandExecutionError(
'Container \'{0}\' is frozen, use lxc.unfreeze'.format(name)
)
# lxc-start daemonize itself violently, we must not communicate with it
use_vt = kwargs.get('use_vt', None)
with_communicate = kwargs.get('with_communicate', False)
return _change_state(cmd, name, 'running',
stdout=None,
stderr=None,
stdin=None,
with_communicate=with_communicate,
path=path,
use_vt=use_vt)
def stop(name, kill=False, path=None, use_vt=None):
'''
Stop the named container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
kill: False
Do not wait for the container to stop, kill all tasks in the container.
Older LXC versions will stop containers like this irrespective of this
argument.
.. versionchanged:: 2015.5.0
Default value changed to ``False``
use_vt
run the command through VT
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.stop name
'''
_ensure_exists(name, path=path)
orig_state = state(name, path=path)
if orig_state == 'frozen' and not kill:
# Gracefully stopping a frozen container is slower than unfreezing and
# then stopping it (at least in my testing), so if we're not
# force-stopping the container, unfreeze it first.
unfreeze(name, path=path)
cmd = 'lxc-stop'
if kill:
cmd += ' -k'
ret = _change_state(cmd, name, 'stopped', use_vt=use_vt, path=path)
ret['state']['old'] = orig_state
return ret
def freeze(name, **kwargs):
'''
Freeze the named container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
start : False
If ``True`` and the container is stopped, the container will be started
before attempting to freeze.
.. versionadded:: 2015.5.0
use_vt
run the command through VT
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.freeze name
'''
use_vt = kwargs.get('use_vt', None)
path = kwargs.get('path', None)
_ensure_exists(name, path=path)
orig_state = state(name, path=path)
start_ = kwargs.get('start', False)
if orig_state == 'stopped':
if not start_:
raise CommandExecutionError(
'Container \'{0}\' is stopped'.format(name)
)
start(name, path=path)
cmd = 'lxc-freeze'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
ret = _change_state(cmd, name, 'frozen', use_vt=use_vt, path=path)
if orig_state == 'stopped' and start_:
ret['state']['old'] = orig_state
ret['started'] = True
ret['state']['new'] = state(name, path=path)
return ret
def unfreeze(name, path=None, use_vt=None):
'''
Unfreeze the named container.
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
use_vt
run the command through VT
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.unfreeze name
'''
_ensure_exists(name, path=path)
if state(name, path=path) == 'stopped':
raise CommandExecutionError(
'Container \'{0}\' is stopped'.format(name)
)
cmd = 'lxc-unfreeze'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
return _change_state(cmd, name, 'running', path=path, use_vt=use_vt)
def destroy(name, stop=False, path=None):
'''
Destroy the named container.
.. warning::
Destroys all data associated with the container.
path
path to the container parent directory (default: /var/lib/lxc)
.. versionadded:: 2015.8.0
stop : False
If ``True``, the container will be destroyed even if it is
running/frozen.
.. versionchanged:: 2015.5.0
Default value changed to ``False``. This more closely matches the
behavior of ``lxc-destroy(1)``, and also makes it less likely that
an accidental command will destroy a running container that was
being used for important things.
CLI Examples:
.. code-block:: bash
salt '*' lxc.destroy foo
salt '*' lxc.destroy foo stop=True
'''
_ensure_exists(name, path=path)
if not stop and state(name, path=path) != 'stopped':
raise CommandExecutionError(
'Container \'{0}\' is not stopped'.format(name)
)
return _change_state('lxc-destroy', name, None, path=path)
# Compatibility between LXC and nspawn
remove = salt.utils.functools.alias_function(destroy, 'remove')
def exists(name, path=None):
'''
Returns whether the named container exists.
path
path to the container parent directory (default: /var/lib/lxc)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.exists name
'''
_exists = name in ls_(path=path)
# container may be just created but we did cached earlier the
# lxc-ls results
if not _exists:
_exists = name in ls_(cache=False, path=path)
return _exists
def state(name, path=None):
'''
Returns the state of a container.
path
path to the container parent directory (default: /var/lib/lxc)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.state name
'''
# Don't use _ensure_exists() here, it will mess with _change_state()
cachekey = 'lxc.state.{0}{1}'.format(name, path)
try:
return __context__[cachekey]
except KeyError:
if not exists(name, path=path):
__context__[cachekey] = None
else:
cmd = 'lxc-info'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0}'.format(name)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
if ret['retcode'] != 0:
_clear_context()
raise CommandExecutionError(
'Unable to get state of container \'{0}\''.format(name)
)
c_infos = ret['stdout'].splitlines()
c_state = None
for c_info in c_infos:
stat = c_info.split(':')
if stat[0].lower() == 'state':
c_state = stat[1].strip().lower()
break
__context__[cachekey] = c_state
return __context__[cachekey]
def get_parameter(name, parameter, path=None):
'''
Returns the value of a cgroup parameter for a container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.get_parameter container_name memory.limit_in_bytes
'''
_ensure_exists(name, path=path)
cmd = 'lxc-cgroup'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0} {1}'.format(name, parameter)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
if ret['retcode'] != 0:
raise CommandExecutionError(
'Unable to retrieve value for \'{0}\''.format(parameter)
)
return ret['stdout'].strip()
def set_parameter(name, parameter, value, path=None):
'''
Set the value of a cgroup parameter for a container.
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.set_parameter name parameter value
'''
if not exists(name, path=path):
return None
cmd = 'lxc-cgroup'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0} {1} {2}'.format(name, parameter, value)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
if ret['retcode'] != 0:
return False
else:
return True
def info(name, path=None):
'''
Returns information about a container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.info name
'''
cachekey = 'lxc.info.{0}{1}'.format(name, path)
try:
return __context__[cachekey]
except KeyError:
_ensure_exists(name, path=path)
cpath = get_root_path(path)
try:
conf_file = os.path.join(cpath, name, 'config')
except AttributeError:
conf_file = os.path.join(cpath, six.text_type(name), 'config')
if not os.path.isfile(conf_file):
raise CommandExecutionError(
'LXC config file {0} does not exist'.format(conf_file)
)
ret = {}
config = []
with salt.utils.files.fopen(conf_file) as fp_:
for line in fp_:
line = salt.utils.stringutils.to_unicode(line)
comps = [x.strip() for x in
line.split('#', 1)[0].strip().split('=', 1)]
if len(comps) == 2:
config.append(tuple(comps))
ifaces = []
current = None
for key, val in config:
if key == 'lxc.network.type':
current = {'type': val}
ifaces.append(current)
elif not current:
continue
elif key.startswith('lxc.network.'):
current[key.replace('lxc.network.', '', 1)] = val
if ifaces:
ret['nics'] = ifaces
ret['rootfs'] = next(
(x[1] for x in config if x[0] == 'lxc.rootfs'),
None
)
ret['state'] = state(name, path=path)
ret['ips'] = []
ret['public_ips'] = []
ret['private_ips'] = []
ret['public_ipv4_ips'] = []
ret['public_ipv6_ips'] = []
ret['private_ipv4_ips'] = []
ret['private_ipv6_ips'] = []
ret['ipv4_ips'] = []
ret['ipv6_ips'] = []
ret['size'] = None
ret['config'] = conf_file
if ret['state'] == 'running':
try:
limit = int(get_parameter(name, 'memory.limit_in_bytes'))
except (CommandExecutionError, TypeError, ValueError):
limit = 0
try:
usage = int(get_parameter(name, 'memory.usage_in_bytes'))
except (CommandExecutionError, TypeError, ValueError):
usage = 0
free = limit - usage
ret['memory_limit'] = limit
ret['memory_free'] = free
size = run_stdout(name, 'df /', path=path, python_shell=False)
# The size is the 2nd column of the last line
ret['size'] = size.splitlines()[-1].split()[1]
# First try iproute2
ip_cmd = run_all(
name, 'ip link show', path=path, python_shell=False)
if ip_cmd['retcode'] == 0:
ip_data = ip_cmd['stdout']
ip_cmd = run_all(
name, 'ip addr show', path=path, python_shell=False)
ip_data += '\n' + ip_cmd['stdout']
ip_data = salt.utils.network._interfaces_ip(ip_data)
else:
# That didn't work, try ifconfig
ip_cmd = run_all(
name, 'ifconfig', path=path, python_shell=False)
if ip_cmd['retcode'] == 0:
ip_data = \
salt.utils.network._interfaces_ifconfig(
ip_cmd['stdout'])
else:
# Neither was successful, give up
log.warning(
'Unable to run ip or ifconfig in container \'%s\'', name
)
ip_data = {}
ret['ipv4_ips'] = salt.utils.network.ip_addrs(
include_loopback=True,
interface_data=ip_data
)
ret['ipv6_ips'] = salt.utils.network.ip_addrs6(
include_loopback=True,
interface_data=ip_data
)
ret['ips'] = ret['ipv4_ips'] + ret['ipv6_ips']
for address in ret['ipv4_ips']:
if address == '127.0.0.1':
ret['private_ips'].append(address)
ret['private_ipv4_ips'].append(address)
elif salt.utils.cloud.is_public_ip(address):
ret['public_ips'].append(address)
ret['public_ipv4_ips'].append(address)
else:
ret['private_ips'].append(address)
ret['private_ipv4_ips'].append(address)
for address in ret['ipv6_ips']:
if address == '::1' or address.startswith('fe80'):
ret['private_ips'].append(address)
ret['private_ipv6_ips'].append(address)
else:
ret['public_ips'].append(address)
ret['public_ipv6_ips'].append(address)
for key in [x for x in ret if x == 'ips' or x.endswith('ips')]:
ret[key].sort(key=_ip_sort)
__context__[cachekey] = ret
return __context__[cachekey]
def set_password(name, users, password, encrypted=True, path=None):
'''
.. versionchanged:: 2015.5.0
Function renamed from ``set_pass`` to ``set_password``. Additionally,
this function now supports (and defaults to using) a password hash
instead of a plaintext password.
Set the password of one or more system users inside containers
users
Comma-separated list (or python list) of users to change password
password
Password to set for the specified user(s)
encrypted : True
If true, ``password`` must be a password hash. Set to ``False`` to set
a plaintext password (not recommended).
.. versionadded:: 2015.5.0
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.set_pass container-name root '$6$uJ2uAyLU$KoI67t8As/0fXtJOPcHKGXmUpcoYUcVR2K6x93walnShTCQvjRwq25yIkiCBOqgbfdKQSFnAo28/ek6716vEV1'
salt '*' lxc.set_pass container-name root foo encrypted=False
'''
def _bad_user_input():
raise SaltInvocationError('Invalid input for \'users\' parameter')
if not isinstance(users, list):
try:
users = users.split(',')
except AttributeError:
_bad_user_input()
if not users:
_bad_user_input()
failed_users = []
for user in users:
result = retcode(name,
'chpasswd{0}'.format(' -e' if encrypted else ''),
stdin=':'.join((user, password)),
python_shell=False,
path=path,
chroot_fallback=True,
output_loglevel='quiet')
if result != 0:
failed_users.append(user)
if failed_users:
raise CommandExecutionError(
'Password change failed for the following user(s): {0}'
.format(', '.join(failed_users))
)
return True
set_pass = salt.utils.functools.alias_function(set_password, 'set_pass')
def update_lxc_conf(name, lxc_conf, lxc_conf_unset, path=None):
'''
Edit LXC configuration options
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.update_lxc_conf ubuntu \\
lxc_conf="[{'network.ipv4.ip':'10.0.3.5'}]" \\
lxc_conf_unset="['lxc.utsname']"
'''
_ensure_exists(name, path=path)
cpath = get_root_path(path)
lxc_conf_p = os.path.join(cpath, name, 'config')
if not os.path.exists(lxc_conf_p):
raise SaltInvocationError(
'Configuration file {0} does not exist'.format(lxc_conf_p)
)
changes = {'edited': [], 'added': [], 'removed': []}
ret = {'changes': changes, 'result': True, 'comment': ''}
# do not use salt.utils.files.fopen !
with salt.utils.files.fopen(lxc_conf_p, 'r') as fic:
filtered_lxc_conf = []
for row in lxc_conf:
if not row:
continue
for conf in row:
filtered_lxc_conf.append((conf.strip(),
row[conf].strip()))
ret['comment'] = 'lxc.conf is up to date'
lines = []
orig_config = salt.utils.stringutils.to_unicode(fic.read())
for line in orig_config.splitlines():
if line.startswith('#') or not line.strip():
lines.append([line, ''])
else:
line = line.split('=')
index = line.pop(0)
val = (index.strip(), '='.join(line).strip())
if val not in lines:
lines.append(val)
for key, item in filtered_lxc_conf:
matched = False
for idx, line in enumerate(lines[:]):
if line[0] == key:
matched = True
lines[idx] = (key, item)
if '='.join(line[1:]).strip() != item.strip():
changes['edited'].append(
({line[0]: line[1:]}, {key: item}))
break
if not matched:
if (key, item) not in lines:
lines.append((key, item))
changes['added'].append({key: item})
dest_lxc_conf = []
# filter unset
if lxc_conf_unset:
for line in lines:
for opt in lxc_conf_unset:
if (
not line[0].startswith(opt) and
line not in dest_lxc_conf
):
dest_lxc_conf.append(line)
else:
changes['removed'].append(opt)
else:
dest_lxc_conf = lines
conf = ''
for key, val in dest_lxc_conf:
if not val:
conf += '{0}\n'.format(key)
else:
conf += '{0} = {1}\n'.format(key.strip(), val.strip())
conf_changed = conf != orig_config
chrono = datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S')
if conf_changed:
# DO NOT USE salt.utils.files.fopen here, i got (kiorky)
# problems with lxc configs which were wiped !
with salt.utils.files.fopen('{0}.{1}'.format(lxc_conf_p, chrono), 'w') as wfic:
wfic.write(salt.utils.stringutils.to_str(conf))
with salt.utils.files.fopen(lxc_conf_p, 'w') as wfic:
wfic.write(salt.utils.stringutils.to_str(conf))
ret['comment'] = 'Updated'
ret['result'] = True
if not any(changes[x] for x in changes):
# Ensure an empty changes dict if nothing was modified
ret['changes'] = {}
return ret
def set_dns(name, dnsservers=None, searchdomains=None, path=None):
'''
.. versionchanged:: 2015.5.0
The ``dnsservers`` and ``searchdomains`` parameters can now be passed
as a comma-separated list.
Update /etc/resolv.confo
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.set_dns ubuntu "['8.8.8.8', '4.4.4.4']"
'''
if dnsservers is None:
dnsservers = ['8.8.8.8', '4.4.4.4']
elif not isinstance(dnsservers, list):
try:
dnsservers = dnsservers.split(',')
except AttributeError:
raise SaltInvocationError(
'Invalid input for \'dnsservers\' parameter'
)
if searchdomains is None:
searchdomains = []
elif not isinstance(searchdomains, list):
try:
searchdomains = searchdomains.split(',')
except AttributeError:
raise SaltInvocationError(
'Invalid input for \'searchdomains\' parameter'
)
dns = ['nameserver {0}'.format(x) for x in dnsservers]
dns.extend(['search {0}'.format(x) for x in searchdomains])
dns = '\n'.join(dns) + '\n'
# we may be using resolvconf in the container
# We need to handle that case with care:
# - we create the resolv.conf runtime directory (the
# linked directory) as anyway it will be shadowed when the real
# runned tmpfs mountpoint will be mounted.
# ( /etc/resolv.conf -> ../run/resolvconf/resolv.conf)
# Indeed, it can save us in any other case (running, eg, in a
# bare chroot when repairing or preparing the container for
# operation.
# - We also teach resolvconf to use the aforementioned dns.
# - We finally also set /etc/resolv.conf in all cases
rstr = __salt__['test.random_hash']()
# no tmp here, apparmor won't let us execute !
script = '/sbin/{0}_dns.sh'.format(rstr)
DNS_SCRIPT = "\n".join([
# 'set -x',
'#!/usr/bin/env bash',
'if [ -h /etc/resolv.conf ];then',
' if [ "x$(readlink /etc/resolv.conf)"'
' = "x../run/resolvconf/resolv.conf" ];then',
' if [ ! -d /run/resolvconf/ ];then',
' mkdir -p /run/resolvconf',
' fi',
' cat > /etc/resolvconf/resolv.conf.d/head <<EOF',
dns,
'EOF',
'',
' fi',
'fi',
'cat > /etc/resolv.conf <<EOF',
dns,
'EOF',
''])
result = run_all(
name, 'tee {0}'.format(script), path=path,
stdin=DNS_SCRIPT, python_shell=True)
if result['retcode'] == 0:
result = run_all(
name, 'sh -c "chmod +x {0};{0}"'.format(script),
path=path, python_shell=True)
# blindly delete the setter file
run_all(name,
'sh -c \'if [ -f "{0}" ];then rm -f "{0}";fi\''.format(script),
path=path, python_shell=True)
if result['retcode'] != 0:
error = ('Unable to write to /etc/resolv.conf in container \'{0}\''
.format(name))
if result['stderr']:
error += ': {0}'.format(result['stderr'])
raise CommandExecutionError(error)
return True
def running_systemd(name, cache=True, path=None):
'''
Determine if systemD is running
path
path to the container parent
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.running_systemd ubuntu
'''
k = 'lxc.systemd.test.{0}{1}'.format(name, path)
ret = __context__.get(k, None)
if ret is None or not cache:
rstr = __salt__['test.random_hash']()
# no tmp here, apparmor won't let us execute !
script = '/sbin/{0}_testsystemd.sh'.format(rstr)
# ubuntu already had since trusty some bits of systemd but was
# still using upstart ...
# we need to be a bit more careful that just testing that systemd
# is present
_script = textwrap.dedent(
'''\
#!/usr/bin/env bash
set -x
if ! command -v systemctl 1>/dev/null 2>/dev/null;then exit 2;fi
for i in \\
/run/systemd/journal/dev-log\\
/run/systemd/journal/flushed\\
/run/systemd/journal/kernel-seqnum\\
/run/systemd/journal/socket\\
/run/systemd/journal/stdout\\
/var/run/systemd/journal/dev-log\\
/var/run/systemd/journal/flushed\\
/var/run/systemd/journal/kernel-seqnum\\
/var/run/systemd/journal/socket\\
/var/run/systemd/journal/stdout\\
;do\\
if test -e ${i};then exit 0;fi
done
if test -d /var/systemd/system;then exit 0;fi
exit 2
''')
result = run_all(
name, 'tee {0}'.format(script), path=path,
stdin=_script, python_shell=True)
if result['retcode'] == 0:
result = run_all(name,
'sh -c "chmod +x {0};{0}"'''.format(script),
path=path,
python_shell=True)
else:
raise CommandExecutionError(
'lxc {0} failed to copy initd tester'.format(name))
run_all(name,
'sh -c \'if [ -f "{0}" ];then rm -f "{0}";fi\''
''.format(script),
path=path,
ignore_retcode=True,
python_shell=True)
if result['retcode'] != 0:
error = ('Unable to determine if the container \'{0}\''
' was running systemd, assmuming it is not.'
''.format(name))
if result['stderr']:
error += ': {0}'.format(result['stderr'])
# only cache result if we got a known exit code
if result['retcode'] in (0, 2):
__context__[k] = ret = not result['retcode']
return ret
def systemd_running_state(name, path=None):
'''
Get the operational state of a systemd based container
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.systemd_running_state ubuntu
'''
try:
ret = run_all(name,
'systemctl is-system-running',
path=path,
ignore_retcode=True)['stdout']
except CommandExecutionError:
ret = ''
return ret
def test_sd_started_state(name, path=None):
'''
Test if a systemd container is fully started
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.test_sd_started_state ubuntu
'''
qstate = systemd_running_state(name, path=path)
if qstate in ('initializing', 'starting'):
return False
elif qstate == '':
return None
else:
return True
def test_bare_started_state(name, path=None):
'''
Test if a non systemd container is fully started
For now, it consists only to test if the container is attachable
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.test_bare_started_state ubuntu
'''
try:
ret = run_all(
name, 'ls', path=path, ignore_retcode=True
)['retcode'] == 0
except (CommandExecutionError,):
ret = None
return ret
def wait_started(name, path=None, timeout=300):
'''
Check that the system has fully inited
This is actually very important for systemD based containers
see https://github.com/saltstack/salt/issues/23847
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.wait_started ubuntu
'''
if not exists(name, path=path):
raise CommandExecutionError(
'Container {0} does does exists'.format(name))
if not state(name, path=path) == 'running':
raise CommandExecutionError(
'Container {0} is not running'.format(name))
ret = False
if running_systemd(name, path=path):
test_started = test_sd_started_state
logger = log.error
else:
test_started = test_bare_started_state
logger = log.debug
now = time.time()
expire = now + timeout
now = time.time()
started = test_started(name, path=path)
while time.time() < expire and not started:
time.sleep(0.3)
started = test_started(name, path=path)
if started is None:
logger(
'Assuming %s is started, although we failed to detect that'
' is fully started correctly', name)
ret = True
else:
ret = started
return ret
def _needs_install(name, path=None):
ret = 0
has_minion = retcode(name,
'which salt-minion',
path=path,
ignore_retcode=True)
# we assume that installing is when no minion is running
# but testing the executable presence is not enougth for custom
# installs where the bootstrap can do much more than installing
# the bare salt binaries.
if has_minion:
processes = run_stdout(name, "ps aux", path=path)
if 'salt-minion' not in processes:
ret = 1
else:
retcode(name, 'salt-call --local service.stop salt-minion')
else:
ret = 1
return ret
def bootstrap(name,
config=None,
approve_key=True,
install=True,
pub_key=None,
priv_key=None,
bootstrap_url=None,
force_install=False,
unconditional_install=False,
path=None,
bootstrap_delay=None,
bootstrap_args=None,
bootstrap_shell=None):
'''
Install and configure salt in a container.
config
Minion configuration options. By default, the ``master`` option is set
to the target host's master.
approve_key
Request a pre-approval of the generated minion key. Requires
that the salt-master be configured to either auto-accept all keys or
expect a signing request from the target host. Default: ``True``
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
pub_key
Explicit public key to pressed the minion with (optional).
This can be either a filepath or a string representing the key
priv_key
Explicit private key to pressed the minion with (optional).
This can be either a filepath or a string representing the key
bootstrap_delay
Delay in seconds between end of container creation and bootstrapping.
Useful when waiting for container to obtain a DHCP lease.
.. versionadded:: 2015.5.0
bootstrap_url
url, content or filepath to the salt bootstrap script
bootstrap_args
salt bootstrap script arguments
bootstrap_shell
shell to execute the script into
install
Whether to attempt a full installation of salt-minion if needed.
force_install
Force installation even if salt-minion is detected,
this is the way to run vendor bootstrap scripts even
if a salt minion is already present in the container
unconditional_install
Run the script even if the container seems seeded
CLI Examples:
.. code-block:: bash
salt 'minion' lxc.bootstrap container_name [config=config_data] \\
[approve_key=(True|False)] [install=(True|False)]
'''
wait_started(name, path=path)
if bootstrap_delay is not None:
try:
log.info('LXC %s: bootstrap_delay: %s', name, bootstrap_delay)
time.sleep(bootstrap_delay)
except TypeError:
# Bad input, but assume since a value was passed that
# a delay was desired, and sleep for 5 seconds
time.sleep(5)
c_info = info(name, path=path)
if not c_info:
return None
# default set here as we cannot set them
# in def as it can come from a chain of procedures.
if bootstrap_args:
# custom bootstrap args can be totally customized, and user could
# have inserted the placeholder for the config directory.
# For example, some salt bootstrap script do not use at all -c
if '{0}' not in bootstrap_args:
bootstrap_args += ' -c {0}'
else:
bootstrap_args = '-c {0}'
if not bootstrap_shell:
bootstrap_shell = 'sh'
orig_state = _ensure_running(name, path=path)
if not orig_state:
return orig_state
if not force_install:
needs_install = _needs_install(name, path=path)
else:
needs_install = True
seeded = retcode(name,
'test -e \'{0}\''.format(SEED_MARKER),
path=path,
chroot_fallback=True,
ignore_retcode=True) == 0
tmp = tempfile.mkdtemp()
if seeded and not unconditional_install:
ret = True
else:
ret = False
cfg_files = __salt__['seed.mkconfig'](
config, tmp=tmp, id_=name, approve_key=approve_key,
pub_key=pub_key, priv_key=priv_key)
if needs_install or force_install or unconditional_install:
if install:
rstr = __salt__['test.random_hash']()
configdir = '/var/tmp/.c_{0}'.format(rstr)
cmd = 'install -m 0700 -d {0}'.format(configdir)
if run_all(
name, cmd, path=path, python_shell=False
)['retcode'] != 0:
log.error('tmpdir %s creation failed %s', configdir, cmd)
return False
bs_ = __salt__['config.gather_bootstrap_script'](
bootstrap=bootstrap_url)
script = '/sbin/{0}_bootstrap.sh'.format(rstr)
copy_to(name, bs_, script, path=path)
result = run_all(name,
'sh -c "chmod +x {0}"'.format(script),
path=path,
python_shell=True)
copy_to(name, cfg_files['config'],
os.path.join(configdir, 'minion'),
path=path)
copy_to(name, cfg_files['privkey'],
os.path.join(configdir, 'minion.pem'),
path=path)
copy_to(name, cfg_files['pubkey'],
os.path.join(configdir, 'minion.pub'),
path=path)
bootstrap_args = bootstrap_args.format(configdir)
cmd = ('{0} {2} {1}'
.format(bootstrap_shell,
bootstrap_args.replace("'", "''"),
script))
# log ASAP the forged bootstrap command which can be wrapped
# out of the output in case of unexpected problem
log.info('Running %s in LXC container \'%s\'', cmd, name)
ret = retcode(name, cmd, output_loglevel='info',
path=path, use_vt=True) == 0
run_all(name,
'sh -c \'if [ -f "{0}" ];then rm -f "{0}";fi\''
''.format(script),
path=path,
ignore_retcode=True,
python_shell=True)
else:
ret = False
else:
minion_config = salt.config.minion_config(cfg_files['config'])
pki_dir = minion_config['pki_dir']
copy_to(name,
cfg_files['config'],
'/etc/salt/minion',
path=path)
copy_to(name,
cfg_files['privkey'],
os.path.join(pki_dir, 'minion.pem'),
path=path)
copy_to(name,
cfg_files['pubkey'],
os.path.join(pki_dir, 'minion.pub'),
path=path)
run(name,
'salt-call --local service.enable salt-minion',
path=path,
python_shell=False)
ret = True
shutil.rmtree(tmp)
if orig_state == 'stopped':
stop(name, path=path)
elif orig_state == 'frozen':
freeze(name, path=path)
# mark seeded upon successful install
if ret:
run(name,
'touch \'{0}\''.format(SEED_MARKER),
path=path,
python_shell=False)
return ret
def attachable(name, path=None):
'''
Return True if the named container can be attached to via the lxc-attach
command
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt 'minion' lxc.attachable ubuntu
'''
cachekey = 'lxc.attachable{0}{1}'.format(name, path)
try:
return __context__[cachekey]
except KeyError:
_ensure_exists(name, path=path)
# Can't use run() here because it uses attachable() and would
# endlessly recurse, resulting in a traceback
log.debug('Checking if LXC container %s is attachable', name)
cmd = 'lxc-attach'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' --clear-env -n {0} -- /usr/bin/env'.format(name)
result = __salt__['cmd.retcode'](cmd,
python_shell=False,
output_loglevel='quiet',
ignore_retcode=True) == 0
__context__[cachekey] = result
return __context__[cachekey]
def _run(name,
cmd,
output=None,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=None,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
Common logic for lxc.run functions
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
'''
orig_state = state(name, path=path)
try:
if attachable(name, path=path):
ret = __salt__['container_resource.run'](
name,
cmd,
path=path,
container_type=__virtualname__,
exec_driver=EXEC_DRIVER,
output=output,
no_start=no_start,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
ignore_retcode=ignore_retcode,
use_vt=use_vt,
keep_env=keep_env)
else:
if not chroot_fallback:
raise CommandExecutionError(
'{0} is not attachable.'.format(name))
rootfs = info(name, path=path).get('rootfs')
# Set context var to make cmd.run_chroot run cmd.run instead of
# cmd.run_all.
__context__['cmd.run_chroot.func'] = __salt__['cmd.run']
ret = __salt__['cmd.run_chroot'](rootfs,
cmd,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
ignore_retcode=ignore_retcode)
except Exception:
raise
finally:
# Make sure we honor preserve_state, even if there was an exception
new_state = state(name, path=path)
if preserve_state:
if orig_state == 'stopped' and new_state != 'stopped':
stop(name, path=path)
elif orig_state == 'frozen' and new_state != 'frozen':
freeze(name, start=True, path=path)
if output in (None, 'all'):
return ret
else:
return ret[output]
def run(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.8.0
Run :mod:`cmd.run <salt.modules.cmdmod.run>` within a container
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed in stderr if the command being run
does not exist. If no output is returned using this function, try using
:mod:`lxc.run_stderr <salt.modules.lxc.run_stderr>` or
:mod:`lxc.run_all <salt.modules.lxc.run_all>`.
name
Name of the container in which to run the command
cmd
Command to run
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console. Assumes
``output=all``.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
CLI Example:
.. code-block:: bash
salt myminion lxc.run mycontainer 'ifconfig -a'
'''
return _run(name,
cmd,
path=path,
output=None,
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def run_stdout(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.5.0
Run :mod:`cmd.run_stdout <salt.modules.cmdmod.run_stdout>` within a container
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed in stderr if the command being run
does not exist. If no output is returned using this function, try using
:mod:`lxc.run_stderr <salt.modules.lxc.run_stderr>` or
:mod:`lxc.run_all <salt.modules.lxc.run_all>`.
name
Name of the container in which to run the command
cmd
Command to run
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console
``output=all``.
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
CLI Example:
.. code-block:: bash
salt myminion lxc.run_stdout mycontainer 'ifconfig -a'
'''
return _run(name,
cmd,
path=path,
output='stdout',
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def run_stderr(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.5.0
Run :mod:`cmd.run_stderr <salt.modules.cmdmod.run_stderr>` within a container
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed if the command being run does not
exist.
name
Name of the container in which to run the command
cmd
Command to run
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console
``output=all``.
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
CLI Example:
.. code-block:: bash
salt myminion lxc.run_stderr mycontainer 'ip addr show'
'''
return _run(name,
cmd,
path=path,
output='stderr',
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def retcode(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.5.0
Run :mod:`cmd.retcode <salt.modules.cmdmod.retcode>` within a container
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed in stderr if the command being run
does not exist. If the retcode is nonzero and not what was expected,
try using :mod:`lxc.run_stderr <salt.modules.lxc.run_stderr>`
or :mod:`lxc.run_all <salt.modules.lxc.run_all>`.
name
Name of the container in which to run the command
cmd
Command to run
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console
``output=all``.
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
CLI Example:
.. code-block:: bash
salt myminion lxc.retcode mycontainer 'ip addr show'
'''
return _run(name,
cmd,
output='retcode',
path=path,
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def run_all(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.5.0
Run :mod:`cmd.run_all <salt.modules.cmdmod.run_all>` within a container
.. note::
While the command is run within the container, it is initiated from the
host. Therefore, the PID in the return dict is from the host, not from
the container.
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed in stderr if the command being run
does not exist.
name
Name of the container in which to run the command
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
cmd
Command to run
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console
``output=all``.
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
CLI Example:
.. code-block:: bash
salt myminion lxc.run_all mycontainer 'ip addr show'
'''
return _run(name,
cmd,
output='all',
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
path=path,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def _get_md5(name, path):
'''
Get the MD5 checksum of a file from a container
'''
output = run_stdout(name, 'md5sum "{0}"'.format(path),
chroot_fallback=True,
ignore_retcode=True)
try:
return output.split()[0]
except IndexError:
# Destination file does not exist or could not be accessed
return None
def copy_to(name, source, dest, overwrite=False, makedirs=False, path=None):
'''
.. versionchanged:: 2015.8.0
Function renamed from ``lxc.cp`` to ``lxc.copy_to`` for consistency
with other container types. ``lxc.cp`` will continue to work, however.
For versions 2015.2.x and earlier, use ``lxc.cp``.
Copy a file or directory from the host into a container
name
Container name
source
File to be copied to the container
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
dest
Destination on the container. Must be an absolute path.
.. versionchanged:: 2015.5.0
If the destination is a directory, the file will be copied into
that directory.
overwrite : False
Unless this option is set to ``True``, then if a file exists at the
location specified by the ``dest`` argument, an error will be raised.
.. versionadded:: 2015.8.0
makedirs : False
Create the parent directory on the container if it does not already
exist.
.. versionadded:: 2015.5.0
CLI Example:
.. code-block:: bash
salt 'minion' lxc.copy_to /tmp/foo /root/foo
salt 'minion' lxc.cp /tmp/foo /root/foo
'''
_ensure_running(name, no_start=True, path=path)
return __salt__['container_resource.copy_to'](
name,
source,
dest,
container_type=__virtualname__,
path=path,
exec_driver=EXEC_DRIVER,
overwrite=overwrite,
makedirs=makedirs)
cp = salt.utils.functools.alias_function(copy_to, 'cp')
def read_conf(conf_file, out_format='simple'):
'''
Read in an LXC configuration file. By default returns a simple, unsorted
dict, but can also return a more detailed structure including blank lines
and comments.
out_format:
set to 'simple' if you need the old and unsupported behavior.
This won't support the multiple lxc values (eg: multiple network nics)
CLI Examples:
.. code-block:: bash
salt 'minion' lxc.read_conf /etc/lxc/mycontainer.conf
salt 'minion' lxc.read_conf /etc/lxc/mycontainer.conf out_format=commented
'''
ret_commented = []
ret_simple = {}
with salt.utils.files.fopen(conf_file, 'r') as fp_:
for line in salt.utils.data.decode(fp_.readlines()):
if '=' not in line:
ret_commented.append(line)
continue
comps = line.split('=')
value = '='.join(comps[1:]).strip()
comment = None
if value.strip().startswith('#'):
vcomps = value.strip().split('#')
value = vcomps[1].strip()
comment = '#'.join(vcomps[1:]).strip()
ret_commented.append({comps[0].strip(): {
'value': value,
'comment': comment,
}})
else:
ret_commented.append({comps[0].strip(): value})
ret_simple[comps[0].strip()] = value
if out_format == 'simple':
return ret_simple
return ret_commented
def write_conf(conf_file, conf):
'''
Write out an LXC configuration file
This is normally only used internally. The format of the data structure
must match that which is returned from ``lxc.read_conf()``, with
``out_format`` set to ``commented``.
An example might look like:
.. code-block:: python
[
{'lxc.utsname': '$CONTAINER_NAME'},
'# This is a commented line\\n',
'\\n',
{'lxc.mount': '$CONTAINER_FSTAB'},
{'lxc.rootfs': {'comment': 'This is another test',
'value': 'This is another test'}},
'\\n',
{'lxc.network.type': 'veth'},
{'lxc.network.flags': 'up'},
{'lxc.network.link': 'br0'},
{'lxc.network.mac': '$CONTAINER_MACADDR'},
{'lxc.network.ipv4': '$CONTAINER_IPADDR'},
{'lxc.network.name': '$CONTAINER_DEVICENAME'},
]
CLI Example:
.. code-block:: bash
salt 'minion' lxc.write_conf /etc/lxc/mycontainer.conf \\
out_format=commented
'''
if not isinstance(conf, list):
raise SaltInvocationError('Configuration must be passed as a list')
# construct the content prior to write to the file
# to avoid half written configs
content = ''
for line in conf:
if isinstance(line, (six.text_type, six.string_types)):
content += line
elif isinstance(line, dict):
for key in list(line.keys()):
out_line = None
if isinstance(
line[key],
(six.text_type, six.string_types, six.integer_types, float)
):
out_line = ' = '.join((key, "{0}".format(line[key])))
elif isinstance(line[key], dict):
out_line = ' = '.join((key, line[key]['value']))
if 'comment' in line[key]:
out_line = ' # '.join((out_line, line[key]['comment']))
if out_line:
content += out_line
content += '\n'
with salt.utils.files.fopen(conf_file, 'w') as fp_:
fp_.write(salt.utils.stringutils.to_str(content))
return {}
def edit_conf(conf_file,
out_format='simple',
read_only=False,
lxc_config=None,
**kwargs):
'''
Edit an LXC configuration file. If a setting is already present inside the
file, its value will be replaced. If it does not exist, it will be appended
to the end of the file. Comments and blank lines will be kept in-tact if
they already exist in the file.
out_format:
Set to simple if you need backward compatibility (multiple items for a
simple key is not supported)
read_only:
return only the edited configuration without applying it
to the underlying lxc configuration file
lxc_config:
List of dict containning lxc configuration items
For network configuration, you also need to add the device it belongs
to, otherwise it will default to eth0.
Also, any change to a network parameter will result in the whole
network reconfiguration to avoid mismatchs, be aware of that !
After the file is edited, its contents will be returned. By default, it
will be returned in ``simple`` format, meaning an unordered dict (which
may not represent the actual file order). Passing in an ``out_format`` of
``commented`` will return a data structure which accurately represents the
order and content of the file.
CLI Example:
.. code-block:: bash
salt 'minion' lxc.edit_conf /etc/lxc/mycontainer.conf \\
out_format=commented lxc.network.type=veth
salt 'minion' lxc.edit_conf /etc/lxc/mycontainer.conf \\
out_format=commented \\
lxc_config="[{'lxc.network.name': 'eth0', \\
'lxc.network.ipv4': '1.2.3.4'},
{'lxc.network.name': 'eth2', \\
'lxc.network.ipv4': '1.2.3.5',\\
'lxc.network.gateway': '1.2.3.1'}]"
'''
data = []
try:
conf = read_conf(conf_file, out_format=out_format)
except Exception:
conf = []
if not lxc_config:
lxc_config = []
lxc_config = copy.deepcopy(lxc_config)
# search if we want to access net config
# in that case, we will replace all the net configuration
net_config = []
for lxc_kws in lxc_config + [kwargs]:
net_params = {}
for kwarg in [a for a in lxc_kws]:
if kwarg.startswith('__'):
continue
if kwarg.startswith('lxc.network.'):
net_params[kwarg] = lxc_kws[kwarg]
lxc_kws.pop(kwarg, None)
if net_params:
net_config.append(net_params)
nic_opts = salt.utils.odict.OrderedDict()
for params in net_config:
dev = params.get('lxc.network.name', DEFAULT_NIC)
dev_opts = nic_opts.setdefault(dev, salt.utils.odict.OrderedDict())
for param in params:
opt = param.replace('lxc.network.', '')
opt = {'hwaddr': 'mac'}.get(opt, opt)
dev_opts[opt] = params[param]
net_changes = []
if nic_opts:
net_changes = _config_list(conf, only_net=True,
**{'network_profile': DEFAULT_NIC,
'nic_opts': nic_opts})
if net_changes:
lxc_config.extend(net_changes)
for line in conf:
if not isinstance(line, dict):
data.append(line)
continue
else:
for key in list(line.keys()):
val = line[key]
if net_changes and key.startswith('lxc.network.'):
continue
found = False
for ix in range(len(lxc_config)):
kw = lxc_config[ix]
if key in kw:
found = True
data.append({key: kw[key]})
del kw[key]
if not found:
data.append({key: val})
for lxc_kws in lxc_config:
for kwarg in lxc_kws:
data.append({kwarg: lxc_kws[kwarg]})
if read_only:
return data
write_conf(conf_file, data)
return read_conf(conf_file, out_format)
def reboot(name, path=None):
'''
Reboot a container.
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Examples:
.. code-block:: bash
salt 'minion' lxc.reboot myvm
'''
ret = {'result': True,
'changes': {},
'comment': '{0} rebooted'.format(name)}
does_exist = exists(name, path=path)
if does_exist and (state(name, path=path) == 'running'):
try:
stop(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
ret['result'] = False
return ret
if does_exist and (state(name, path=path) != 'running'):
try:
start(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
ret['result'] = False
return ret
ret['changes'][name] = 'rebooted'
return ret
def reconfigure(name,
cpu=None,
cpuset=None,
cpushare=None,
memory=None,
profile=None,
network_profile=None,
nic_opts=None,
bridge=None,
gateway=None,
autostart=None,
utsname=None,
rootfs=None,
path=None,
**kwargs):
'''
Reconfigure a container.
This only applies to a few property
name
Name of the container.
utsname
utsname of the container.
.. versionadded:: 2016.3.0
rootfs
rootfs of the container.
.. versionadded:: 2016.3.0
cpu
Select a random number of cpu cores and assign it to the cpuset, if the
cpuset option is set then this option will be ignored
cpuset
Explicitly define the cpus this container will be bound to
cpushare
cgroups cpu shares.
autostart
autostart container on reboot
memory
cgroups memory limit, in MB.
(0 for nolimit, None for old default 1024MB)
gateway
the ipv4 gateway to use
the default does nothing more than lxcutils does
bridge
the bridge to use
the default does nothing more than lxcutils does
nic
Network interfaces profile (defined in config or pillar).
nic_opts
Extra options for network interfaces, will override
``{"eth0": {"mac": "aa:bb:cc:dd:ee:ff", "ipv4": "10.1.1.1", "ipv6": "2001:db8::ff00:42:8329"}}``
or
``{"eth0": {"mac": "aa:bb:cc:dd:ee:ff", "ipv4": "10.1.1.1/24", "ipv6": "2001:db8::ff00:42:8329"}}``
path
path to the container parent
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt-call -lall mc_lxc_fork.reconfigure foobar nic_opts="{'eth1': {'mac': '00:16:3e:dd:ee:44'}}" memory=4
'''
changes = {}
cpath = get_root_path(path)
path = os.path.join(cpath, name, 'config')
ret = {'name': name,
'comment': 'config for {0} up to date'.format(name),
'result': True,
'changes': changes}
profile = get_container_profile(copy.deepcopy(profile))
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, _marker)
profile_match = profile.pop(key, default)
# let kwarg overrides be the preferred choice
if kw_overrides_match is _marker:
return profile_match
return kw_overrides_match
if nic_opts is not None and not network_profile:
network_profile = DEFAULT_NIC
if autostart is not None:
autostart = select('autostart', autostart)
else:
autostart = 'keep'
if not utsname:
utsname = select('utsname', utsname)
if os.path.exists(path):
old_chunks = read_conf(path, out_format='commented')
make_kw = salt.utils.odict.OrderedDict([
('utsname', utsname),
('rootfs', rootfs),
('autostart', autostart),
('cpu', cpu),
('gateway', gateway),
('cpuset', cpuset),
('cpushare', cpushare),
('network_profile', network_profile),
('nic_opts', nic_opts),
('bridge', bridge)])
# match 0 and none as memory = 0 in lxc config is harmful
if memory:
make_kw['memory'] = memory
kw = salt.utils.odict.OrderedDict()
for key, val in six.iteritems(make_kw):
if val is not None:
kw[key] = val
new_cfg = _config_list(conf_tuples=old_chunks, **kw)
if new_cfg:
edit_conf(path, out_format='commented', lxc_config=new_cfg)
chunks = read_conf(path, out_format='commented')
if old_chunks != chunks:
ret['comment'] = '{0} lxc config updated'.format(name)
if state(name, path=path) == 'running':
cret = reboot(name, path=path)
ret['result'] = cret['result']
return ret
def apply_network_profile(name, network_profile, nic_opts=None, path=None):
'''
.. versionadded:: 2015.5.0
Apply a network profile to a container
network_profile
profile name or default values (dict)
nic_opts
values to override in defaults (dict)
indexed by nic card names
path
path to the container parent
.. versionadded:: 2015.8.0
CLI Examples:
.. code-block:: bash
salt 'minion' lxc.apply_network_profile web1 centos
salt 'minion' lxc.apply_network_profile web1 centos \\
nic_opts="{'eth0': {'mac': 'xx:xx:xx:xx:xx:xx'}}"
salt 'minion' lxc.apply_network_profile web1 \\
"{'eth0': {'mac': 'xx:xx:xx:xx:xx:yy'}}"
nic_opts="{'eth0': {'mac': 'xx:xx:xx:xx:xx:xx'}}"
The special case to disable use of ethernet nics:
.. code-block:: bash
salt 'minion' lxc.apply_network_profile web1 centos \\
"{eth0: {disable: true}}"
'''
cpath = get_root_path(path)
cfgpath = os.path.join(cpath, name, 'config')
before = []
with salt.utils.files.fopen(cfgpath, 'r') as fp_:
for line in fp_:
before.append(line)
lxcconfig = _LXCConfig(name=name, path=path)
old_net = lxcconfig._filter_data('lxc.network')
network_params = {}
for param in _network_conf(
conf_tuples=old_net,
network_profile=network_profile, nic_opts=nic_opts
):
network_params.update(param)
if network_params:
edit_conf(cfgpath, out_format='commented', **network_params)
after = []
with salt.utils.files.fopen(cfgpath, 'r') as fp_:
for line in fp_:
after.append(line)
diff = ''
for line in difflib.unified_diff(before,
after,
fromfile='before',
tofile='after'):
diff += line
return diff
def get_pid(name, path=None):
'''
Returns a container pid.
Throw an exception if the container isn't running.
CLI Example:
.. code-block:: bash
salt '*' lxc.get_pid name
'''
if name not in list_(limit='running', path=path):
raise CommandExecutionError('Container {0} is not running, can\'t determine PID'.format(name))
info = __salt__['cmd.run']('lxc-info -n {0}'.format(name)).split("\n")
pid = [line.split(':')[1].strip() for line in info if re.match(r'\s*PID', line)][0]
return pid
def add_veth(name, interface_name, bridge=None, path=None):
'''
Add a veth to a container.
Note : this function doesn't update the container config, just add the interface at runtime
name
Name of the container
interface_name
Name of the interface in the container
bridge
Name of the bridge to attach the interface to (facultative)
CLI Examples:
.. code-block:: bash
salt '*' lxc.add_veth container_name eth1 br1
salt '*' lxc.add_veth container_name eth1
'''
# Get container init PID
pid = get_pid(name, path=path)
# Generate a ramdom string for veth and ensure that is isn't present on the system
while True:
random_veth = 'veth'+''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(6))
if random_veth not in __salt__['network.interfaces']().keys():
break
# Check prerequisites
if not __salt__['file.directory_exists']('/var/run/'):
raise CommandExecutionError('Directory /var/run required for lxc.add_veth doesn\'t exists')
if not __salt__['file.file_exists']('/proc/{0}/ns/net'.format(pid)):
raise CommandExecutionError('Proc file for container {0} network namespace doesn\'t exists'.format(name))
if not __salt__['file.directory_exists']('/var/run/netns'):
__salt__['file.mkdir']('/var/run/netns')
# Ensure that the symlink is up to date (change on container restart)
if __salt__['file.is_link']('/var/run/netns/{0}'.format(name)):
__salt__['file.remove']('/var/run/netns/{0}'.format(name))
__salt__['file.symlink']('/proc/{0}/ns/net'.format(pid), '/var/run/netns/{0}'.format(name))
# Ensure that interface doesn't exists
interface_exists = 0 == __salt__['cmd.retcode']('ip netns exec {netns} ip address list {interface}'.format(
netns=name,
interface=interface_name
))
if interface_exists:
raise CommandExecutionError('Interface {interface} already exists in {container}'.format(
interface=interface_name,
container=name
))
# Create veth and bring it up
if __salt__['cmd.retcode']('ip link add name {veth} type veth peer name {veth}_c'.format(veth=random_veth)) != 0:
raise CommandExecutionError('Error while creating the veth pair {0}'.format(random_veth))
if __salt__['cmd.retcode']('ip link set dev {0} up'.format(random_veth)) != 0:
raise CommandExecutionError('Error while bringing up host-side veth {0}'.format(random_veth))
# Attach it to the container
attached = 0 == __salt__['cmd.retcode']('ip link set dev {veth}_c netns {container} name {interface_name}'.format(
veth=random_veth,
container=name,
interface_name=interface_name
))
if not attached:
raise CommandExecutionError('Error while attaching the veth {veth} to container {container}'.format(
veth=random_veth,
container=name
))
__salt__['file.remove']('/var/run/netns/{0}'.format(name))
if bridge is not None:
__salt__['bridge.addif'](bridge, random_veth)
|
saltstack/salt
|
salt/modules/lxc.py
|
clone
|
python
|
def clone(name,
orig,
profile=None,
network_profile=None,
nic_opts=None,
**kwargs):
'''
Create a new container as a clone of another container
name
Name of the container
orig
Name of the original container to be cloned
profile
Profile to use in container cloning (see
:mod:`lxc.get_container_profile
<salt.modules.lxc.get_container_profile>`). Values in a profile will be
overridden by the **Container Cloning Arguments** listed below.
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
**Container Cloning Arguments**
snapshot
Use Copy On Write snapshots (LVM)
size : 1G
Size of the volume to create. Only applicable if ``backing=lvm``.
backing
The type of storage to use. Set to ``lvm`` to use an LVM group.
Defaults to filesystem within /var/lib/lxc.
network_profile
Network profile to use for container
.. versionadded:: 2015.8.0
nic_opts
give extra opts overriding network profile values
.. versionadded:: 2015.8.0
CLI Examples:
.. code-block:: bash
salt '*' lxc.clone myclone orig=orig_container
salt '*' lxc.clone myclone orig=orig_container snapshot=True
'''
profile = get_container_profile(copy.deepcopy(profile))
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, None)
profile_match = profile.pop(key, default)
# let kwarg overrides be the preferred choice
if kw_overrides_match is None:
return profile_match
return kw_overrides_match
path = select('path')
if exists(name, path=path):
raise CommandExecutionError(
'Container \'{0}\' already exists'.format(name)
)
_ensure_exists(orig, path=path)
if state(orig, path=path) != 'stopped':
raise CommandExecutionError(
'Container \'{0}\' must be stopped to be cloned'.format(orig)
)
backing = select('backing')
snapshot = select('snapshot')
if backing in ('dir',):
snapshot = False
if not snapshot:
snapshot = ''
else:
snapshot = '-s'
size = select('size', '1G')
if backing in ('dir', 'overlayfs', 'btrfs'):
size = None
# LXC commands and options changed in 2.0 - CF issue #34086 for details
if _LooseVersion(version()) >= _LooseVersion('2.0'):
# https://linuxcontainers.org/lxc/manpages//man1/lxc-copy.1.html
cmd = 'lxc-copy'
cmd += ' {0} -n {1} -N {2}'.format(snapshot, orig, name)
else:
# https://linuxcontainers.org/lxc/manpages//man1/lxc-clone.1.html
cmd = 'lxc-clone'
cmd += ' {0} -o {1} -n {2}'.format(snapshot, orig, name)
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
if not os.path.exists(path):
os.makedirs(path)
if backing:
backing = backing.lower()
cmd += ' -B {0}'.format(backing)
if backing not in ('dir', 'overlayfs'):
if size:
cmd += ' -L {0}'.format(size)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
# please do not merge extra conflicting stuff
# inside those two line (ret =, return)
return _after_ignition_network_profile(cmd,
ret,
name,
network_profile,
path,
nic_opts)
|
Create a new container as a clone of another container
name
Name of the container
orig
Name of the original container to be cloned
profile
Profile to use in container cloning (see
:mod:`lxc.get_container_profile
<salt.modules.lxc.get_container_profile>`). Values in a profile will be
overridden by the **Container Cloning Arguments** listed below.
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
**Container Cloning Arguments**
snapshot
Use Copy On Write snapshots (LVM)
size : 1G
Size of the volume to create. Only applicable if ``backing=lvm``.
backing
The type of storage to use. Set to ``lvm`` to use an LVM group.
Defaults to filesystem within /var/lib/lxc.
network_profile
Network profile to use for container
.. versionadded:: 2015.8.0
nic_opts
give extra opts overriding network profile values
.. versionadded:: 2015.8.0
CLI Examples:
.. code-block:: bash
salt '*' lxc.clone myclone orig=orig_container
salt '*' lxc.clone myclone orig=orig_container snapshot=True
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/lxc.py#L1987-L2106
|
[
"def version():\n '''\n Return the actual lxc client version\n\n .. versionadded:: 2015.8.0\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' lxc.version\n\n '''\n k = 'lxc.version'\n if not __context__.get(k, None):\n cversion = __salt__['cmd.run_all']('lxc-info --version')\n if not cversion['retcode']:\n ver = _LooseVersion(cversion['stdout'])\n if ver < _LooseVersion('1.0'):\n raise CommandExecutionError('LXC should be at least 1.0')\n __context__[k] = \"{0}\".format(ver)\n return __context__.get(k, None)\n",
"def state(name, path=None):\n '''\n Returns the state of a container.\n\n path\n path to the container parent directory (default: /var/lib/lxc)\n\n .. versionadded:: 2015.8.0\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' lxc.state name\n '''\n # Don't use _ensure_exists() here, it will mess with _change_state()\n\n cachekey = 'lxc.state.{0}{1}'.format(name, path)\n try:\n return __context__[cachekey]\n except KeyError:\n if not exists(name, path=path):\n __context__[cachekey] = None\n else:\n cmd = 'lxc-info'\n if path:\n cmd += ' -P {0}'.format(pipes.quote(path))\n cmd += ' -n {0}'.format(name)\n ret = __salt__['cmd.run_all'](cmd, python_shell=False)\n if ret['retcode'] != 0:\n _clear_context()\n raise CommandExecutionError(\n 'Unable to get state of container \\'{0}\\''.format(name)\n )\n c_infos = ret['stdout'].splitlines()\n c_state = None\n for c_info in c_infos:\n stat = c_info.split(':')\n if stat[0].lower() == 'state':\n c_state = stat[1].strip().lower()\n break\n __context__[cachekey] = c_state\n return __context__[cachekey]\n",
"def exists(name, path=None):\n '''\n Returns whether the named container exists.\n\n path\n path to the container parent directory (default: /var/lib/lxc)\n\n .. versionadded:: 2015.8.0\n\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' lxc.exists name\n '''\n\n _exists = name in ls_(path=path)\n # container may be just created but we did cached earlier the\n # lxc-ls results\n if not _exists:\n _exists = name in ls_(cache=False, path=path)\n return _exists\n",
"def get_container_profile(name=None, **kwargs):\n '''\n .. versionadded:: 2015.5.0\n\n Gather a pre-configured set of container configuration parameters. If no\n arguments are passed, an empty profile is returned.\n\n Profiles can be defined in the minion or master config files, or in pillar\n or grains, and are loaded using :mod:`config.get\n <salt.modules.config.get>`. The key under which LXC profiles must be\n configured is ``lxc.container_profile.profile_name``. An example container\n profile would be as follows:\n\n .. code-block:: yaml\n\n lxc.container_profile:\n ubuntu:\n template: ubuntu\n backing: lvm\n vgname: lxc\n size: 1G\n\n Parameters set in a profile can be overridden by passing additional\n container creation arguments (such as the ones passed to :mod:`lxc.create\n <salt.modules.lxc.create>`) to this function.\n\n A profile can be defined either as the name of the profile, or a dictionary\n of variable names and values. See the :ref:`LXC Tutorial\n <tutorial-lxc-profiles>` for more information on how to use LXC profiles.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt-call lxc.get_container_profile centos\n salt-call lxc.get_container_profile ubuntu template=ubuntu backing=overlayfs\n '''\n profile = _get_profile('container_profile', name, **kwargs)\n return profile\n",
"def _after_ignition_network_profile(cmd,\n ret,\n name,\n network_profile,\n path,\n nic_opts):\n _clear_context()\n if ret['retcode'] == 0 and exists(name, path=path):\n if network_profile:\n network_changes = apply_network_profile(name,\n network_profile,\n path=path,\n nic_opts=nic_opts)\n\n if network_changes:\n log.info(\n 'Network changes from applying network profile \\'%s\\' '\n 'to newly-created container \\'%s\\':\\n%s',\n network_profile, name, network_changes\n )\n c_state = state(name, path=path)\n return {'result': True,\n 'state': {'old': None, 'new': c_state}}\n else:\n if exists(name, path=path):\n # destroy the container if it was partially created\n cmd = 'lxc-destroy'\n if path:\n cmd += ' -P {0}'.format(pipes.quote(path))\n cmd += ' -n {0}'.format(name)\n __salt__['cmd.retcode'](cmd, python_shell=False)\n raise CommandExecutionError(\n 'Container could not be created with cmd \\'{0}\\': {1}'\n .format(cmd, ret['stderr'])\n )\n",
"def _ensure_exists(name, path=None):\n '''\n Raise an exception if the container does not exist\n '''\n if not exists(name, path=path):\n raise CommandExecutionError(\n 'Container \\'{0}\\' does not exist'.format(name)\n )\n",
"def select(key, default=None):\n kw_overrides_match = kw_overrides.pop(key, None)\n profile_match = profile.pop(key, default)\n # let kwarg overrides be the preferred choice\n if kw_overrides_match is None:\n return profile_match\n return kw_overrides_match\n"
] |
# -*- coding: utf-8 -*-
'''
Control Linux Containers via Salt
:depends: lxc package for distribution
lxc >= 1.0 (even beta alpha) is required
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import datetime
import copy
import string
import textwrap
import difflib
import logging
import tempfile
import os
import pipes
import time
import shutil
import re
import random
# Import salt libs
import salt.utils.args
import salt.utils.cloud
import salt.utils.data
import salt.utils.dictupdate
import salt.utils.files
import salt.utils.functools
import salt.utils.hashutils
import salt.utils.network
import salt.utils.odict
import salt.utils.path
import salt.utils.stringutils
from salt.exceptions import CommandExecutionError, SaltInvocationError
import salt.config
from salt.utils.versions import LooseVersion as _LooseVersion
# Import 3rd-party libs
from salt.ext import six
# pylint: disable=import-error,no-name-in-module
from salt.ext.six.moves import range # pylint: disable=redefined-builtin
from salt.ext.six.moves.urllib.parse import urlparse as _urlparse
# pylint: enable=import-error,no-name-in-module
# Set up logging
log = logging.getLogger(__name__)
# Don't shadow built-in's.
__func_alias__ = {
'list_': 'list',
'ls_': 'ls'
}
__virtualname__ = 'lxc'
DEFAULT_NIC = 'eth0'
DEFAULT_BR = 'br0'
SEED_MARKER = '/lxc.initial_seed'
EXEC_DRIVER = 'lxc-attach'
DEFAULT_PATH = '/var/lib/lxc'
_marker = object()
def __virtual__():
if salt.utils.path.which('lxc-start'):
return __virtualname__
# To speed up the whole thing, we decided to not use the
# subshell way and assume things are in place for lxc
# Discussion made by @kiorky and @thatch45
# lxc-version presence is not sufficient, in lxc1.0 alpha
# (precise backports), we have it and it is sufficient
# for the module to execute.
# elif salt.utils.path.which('lxc-version'):
# passed = False
# try:
# passed = subprocess.check_output(
# 'lxc-version').split(':')[1].strip() >= '1.0'
# except Exception:
# pass
# if not passed:
# log.warning('Support for lxc < 1.0 may be incomplete.')
# return 'lxc'
# return False
#
return (False, 'The lxc execution module cannot be loaded: the lxc-start binary is not in the path.')
def get_root_path(path):
'''
Get the configured lxc root for containers
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.get_root_path
'''
if not path:
path = __opts__.get('lxc.root_path', DEFAULT_PATH)
return path
def version():
'''
Return the actual lxc client version
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.version
'''
k = 'lxc.version'
if not __context__.get(k, None):
cversion = __salt__['cmd.run_all']('lxc-info --version')
if not cversion['retcode']:
ver = _LooseVersion(cversion['stdout'])
if ver < _LooseVersion('1.0'):
raise CommandExecutionError('LXC should be at least 1.0')
__context__[k] = "{0}".format(ver)
return __context__.get(k, None)
def _clear_context():
'''
Clear any lxc variables set in __context__
'''
for var in [x for x in __context__ if x.startswith('lxc.')]:
log.trace('Clearing __context__[\'%s\']', var)
__context__.pop(var, None)
def _ip_sort(ip):
'''Ip sorting'''
idx = '001'
if ip == '127.0.0.1':
idx = '200'
if ip == '::1':
idx = '201'
elif '::' in ip:
idx = '100'
return '{0}___{1}'.format(idx, ip)
def search_lxc_bridges():
'''
Search which bridges are potentially available as LXC bridges
CLI Example:
.. code-block:: bash
salt '*' lxc.search_lxc_bridges
'''
bridges = __context__.get('lxc.bridges', None)
# either match not yet called or no bridges were found
# to handle the case where lxc was not installed on the first
# call
if not bridges:
bridges = set()
running_bridges = set()
bridges.add(DEFAULT_BR)
try:
output = __salt__['cmd.run_all']('brctl show')
for line in output['stdout'].splitlines()[1:]:
if not line.startswith(' '):
running_bridges.add(line.split()[0].strip())
except (SaltInvocationError, CommandExecutionError):
pass
for ifc, ip in six.iteritems(
__grains__.get('ip_interfaces', {})
):
if ifc in running_bridges:
bridges.add(ifc)
elif os.path.exists(
'/sys/devices/virtual/net/{0}/bridge'.format(ifc)
):
bridges.add(ifc)
bridges = list(bridges)
# if we found interfaces that have lxc in their names
# we filter them as being the potential lxc bridges
# we also try to default on br0 on other cases
def sort_bridges(a):
pref = 'z'
if 'lxc' in a:
pref = 'a'
elif 'br0' == a:
pref = 'c'
return '{0}_{1}'.format(pref, a)
bridges.sort(key=sort_bridges)
__context__['lxc.bridges'] = bridges
return bridges
def search_lxc_bridge():
'''
Search the first bridge which is potentially available as LXC bridge
CLI Example:
.. code-block:: bash
salt '*' lxc.search_lxc_bridge
'''
return search_lxc_bridges()[0]
def _get_salt_config(config, **kwargs):
if not config:
config = kwargs.get('minion', {})
if not config:
config = {}
config.setdefault('master',
kwargs.get('master',
__opts__.get('master',
__opts__['id'])))
config.setdefault(
'master_port',
kwargs.get('master_port',
__opts__.get('master_port',
__opts__.get('ret_port',
__opts__.get('4506')))))
if not config['master']:
config = {}
return config
def cloud_init_interface(name, vm_=None, **kwargs):
'''
Interface between salt.cloud.lxc driver and lxc.init
``vm_`` is a mapping of vm opts in the salt.cloud format
as documented for the lxc driver.
This can be used either:
- from the salt cloud driver
- because you find the argument to give easier here
than using directly lxc.init
.. warning::
BE REALLY CAREFUL CHANGING DEFAULTS !!!
IT'S A RETRO COMPATIBLE INTERFACE WITH
THE SALT CLOUD DRIVER (ask kiorky).
name
name of the lxc container to create
pub_key
public key to preseed the minion with.
Can be the keycontent or a filepath
priv_key
private key to preseed the minion with.
Can be the keycontent or a filepath
path
path to the container parent directory (default: /var/lib/lxc)
.. versionadded:: 2015.8.0
profile
:ref:`profile <tutorial-lxc-profiles-container>` selection
network_profile
:ref:`network profile <tutorial-lxc-profiles-network>` selection
nic_opts
per interface settings compatibles with
network profile (ipv4/ipv6/link/gateway/mac/netmask)
eg::
- {'eth0': {'mac': '00:16:3e:01:29:40',
'gateway': None, (default)
'link': 'br0', (default)
'gateway': None, (default)
'netmask': '', (default)
'ip': '22.1.4.25'}}
unconditional_install
given to lxc.bootstrap (see relative doc)
force_install
given to lxc.bootstrap (see relative doc)
config
any extra argument for the salt minion config
dnsservers
list of DNS servers to set inside the container
dns_via_dhcp
do not set the dns servers, let them be set by the dhcp.
autostart
autostart the container at boot time
password
administrative password for the container
bootstrap_delay
delay before launching bootstrap script at Container init
.. warning::
Legacy but still supported options:
from_container
which container we use as a template
when running lxc.clone
image
which template do we use when we
are using lxc.create. This is the default
mode unless you specify something in from_container
backing
which backing store to use.
Values can be: overlayfs, dir(default), lvm, zfs, brtfs
fstype
When using a blockdevice level backing store,
which filesystem to use on
size
When using a blockdevice level backing store,
which size for the filesystem to use on
snapshot
Use snapshot when cloning the container source
vgname
if using LVM: vgname
lvname
if using LVM: lvname
thinpool:
if using LVM: thinpool
ip
ip for the primary nic
mac
mac address for the primary nic
netmask
netmask for the primary nic (24)
= ``vm_.get('netmask', '24')``
bridge
bridge for the primary nic (lxcbr0)
gateway
network gateway for the container
additional_ips
additional ips which will be wired on the main bridge (br0)
which is connected to internet.
Be aware that you may use manual virtual mac addresses
providen by you provider (online, ovh, etc).
This is a list of mappings {ip: '', mac: '', netmask:''}
Set gateway to None and an interface with a gateway
to escape from another interface that eth0.
eg::
- {'mac': '00:16:3e:01:29:40',
'gateway': None, (default)
'link': 'br0', (default)
'netmask': '', (default)
'ip': '22.1.4.25'}
users
administrative users for the container
default: [root] and [root, ubuntu] on ubuntu
default_nic
name of the first interface, you should
really not override this
CLI Example:
.. code-block:: bash
salt '*' lxc.cloud_init_interface foo
'''
if vm_ is None:
vm_ = {}
vm_ = copy.deepcopy(vm_)
vm_ = salt.utils.dictupdate.update(vm_, kwargs)
profile_data = copy.deepcopy(
vm_.get('lxc_profile',
vm_.get('profile', {})))
if not isinstance(profile_data, (dict, six.string_types)):
profile_data = {}
profile = get_container_profile(profile_data)
def _cloud_get(k, default=None):
return vm_.get(k, profile.get(k, default))
if name is None:
name = vm_['name']
# if we are on ubuntu, default to ubuntu
default_template = ''
if __grains__.get('os', '') in ['Ubuntu']:
default_template = 'ubuntu'
image = _cloud_get('image')
if not image:
_cloud_get('template', default_template)
backing = _cloud_get('backing', 'dir')
if image:
profile['template'] = image
vgname = _cloud_get('vgname', None)
if vgname:
profile['vgname'] = vgname
if backing:
profile['backing'] = backing
snapshot = _cloud_get('snapshot', False)
autostart = bool(_cloud_get('autostart', True))
dnsservers = _cloud_get('dnsservers', [])
dns_via_dhcp = _cloud_get('dns_via_dhcp', True)
password = _cloud_get('password', 's3cr3t')
password_encrypted = _cloud_get('password_encrypted', False)
fstype = _cloud_get('fstype', None)
lvname = _cloud_get('lvname', None)
thinpool = _cloud_get('thinpool', None)
pub_key = _cloud_get('pub_key', None)
priv_key = _cloud_get('priv_key', None)
size = _cloud_get('size', '20G')
script = _cloud_get('script', None)
script_args = _cloud_get('script_args', None)
users = _cloud_get('users', None)
if users is None:
users = []
ssh_username = _cloud_get('ssh_username', None)
if ssh_username and (ssh_username not in users):
users.append(ssh_username)
network_profile = _cloud_get('network_profile', None)
nic_opts = kwargs.get('nic_opts', None)
netmask = _cloud_get('netmask', '24')
path = _cloud_get('path', None)
bridge = _cloud_get('bridge', None)
gateway = _cloud_get('gateway', None)
unconditional_install = _cloud_get('unconditional_install', False)
force_install = _cloud_get('force_install', True)
config = _get_salt_config(_cloud_get('config', {}), **vm_)
default_nic = _cloud_get('default_nic', DEFAULT_NIC)
# do the interface with lxc.init mainly via nic_opts
# to avoid extra and confusing extra use cases.
if not isinstance(nic_opts, dict):
nic_opts = salt.utils.odict.OrderedDict()
# have a reference to the default nic
eth0 = nic_opts.setdefault(default_nic,
salt.utils.odict.OrderedDict())
# lxc config is based of ifc order, be sure to use odicts.
if not isinstance(nic_opts, salt.utils.odict.OrderedDict):
bnic_opts = salt.utils.odict.OrderedDict()
bnic_opts.update(nic_opts)
nic_opts = bnic_opts
gw = None
# legacy salt.cloud scheme for network interfaces settings support
bridge = _cloud_get('bridge', None)
ip = _cloud_get('ip', None)
mac = _cloud_get('mac', None)
if ip:
fullip = ip
if netmask:
fullip += '/{0}'.format(netmask)
eth0['ipv4'] = fullip
if mac is not None:
eth0['mac'] = mac
for ix, iopts in enumerate(_cloud_get("additional_ips", [])):
ifh = "eth{0}".format(ix+1)
ethx = nic_opts.setdefault(ifh, {})
if gw is None:
gw = iopts.get('gateway', ethx.get('gateway', None))
if gw:
# only one and only one default gateway is allowed !
eth0.pop('gateway', None)
gateway = None
# even if the gateway if on default "eth0" nic
# and we popped it will work
# as we reinject or set it here.
ethx['gateway'] = gw
elink = iopts.get('link', ethx.get('link', None))
if elink:
ethx['link'] = elink
# allow dhcp
aip = iopts.get('ipv4', iopts.get('ip', None))
if aip:
ethx['ipv4'] = aip
nm = iopts.get('netmask', '')
if nm:
ethx['ipv4'] += '/{0}'.format(nm)
for i in ('mac', 'hwaddr'):
if i in iopts:
ethx['mac'] = iopts[i]
break
if 'mac' not in ethx:
ethx['mac'] = salt.utils.network.gen_mac()
# last round checking for unique gateway and such
gw = None
for ethx in [a for a in nic_opts]:
ndata = nic_opts[ethx]
if gw:
ndata.pop('gateway', None)
if 'gateway' in ndata:
gw = ndata['gateway']
gateway = None
# only use a default bridge / gateway if we configured them
# via the legacy salt cloud configuration style.
# On other cases, we should rely on settings provided by the new
# salt lxc network profile style configuration which can
# be also be overridden or a per interface basis via the nic_opts dict.
if bridge:
eth0['link'] = bridge
if gateway:
eth0['gateway'] = gateway
#
lxc_init_interface = {}
lxc_init_interface['name'] = name
lxc_init_interface['config'] = config
lxc_init_interface['memory'] = _cloud_get('memory', 0) # nolimit
lxc_init_interface['pub_key'] = pub_key
lxc_init_interface['priv_key'] = priv_key
lxc_init_interface['nic_opts'] = nic_opts
for clone_from in ['clone_from', 'clone', 'from_container']:
# clone_from should default to None if not available
lxc_init_interface['clone_from'] = _cloud_get(clone_from, None)
if lxc_init_interface['clone_from'] is not None:
break
lxc_init_interface['profile'] = profile
lxc_init_interface['snapshot'] = snapshot
lxc_init_interface['dnsservers'] = dnsservers
lxc_init_interface['fstype'] = fstype
lxc_init_interface['path'] = path
lxc_init_interface['vgname'] = vgname
lxc_init_interface['size'] = size
lxc_init_interface['lvname'] = lvname
lxc_init_interface['thinpool'] = thinpool
lxc_init_interface['force_install'] = force_install
lxc_init_interface['unconditional_install'] = (
unconditional_install
)
lxc_init_interface['bootstrap_url'] = script
lxc_init_interface['bootstrap_args'] = script_args
lxc_init_interface['bootstrap_shell'] = _cloud_get('bootstrap_shell', 'sh')
lxc_init_interface['bootstrap_delay'] = _cloud_get('bootstrap_delay', None)
lxc_init_interface['autostart'] = autostart
lxc_init_interface['users'] = users
lxc_init_interface['password'] = password
lxc_init_interface['password_encrypted'] = password_encrypted
# be sure not to let objects goes inside the return
# as this return will be msgpacked for use in the runner !
lxc_init_interface['network_profile'] = network_profile
for i in ['cpu', 'cpuset', 'cpushare']:
if _cloud_get(i, None):
try:
lxc_init_interface[i] = vm_[i]
except KeyError:
lxc_init_interface[i] = profile[i]
return lxc_init_interface
def _get_profile(key, name, **kwargs):
if isinstance(name, dict):
profilename = name.pop('name', None)
return _get_profile(key, profilename, **name)
if name is None:
profile_match = {}
else:
profile_match = \
__salt__['config.get'](
'lxc.{1}:{0}'.format(name, key),
default=None,
merge='recurse'
)
if profile_match is None:
# No matching profile, make the profile an empty dict so that
# overrides can be applied below.
profile_match = {}
if not isinstance(profile_match, dict):
raise CommandExecutionError('lxc.{0} must be a dictionary'.format(key))
# Overlay the kwargs to override matched profile data
overrides = salt.utils.args.clean_kwargs(**copy.deepcopy(kwargs))
profile_match = salt.utils.dictupdate.update(
copy.deepcopy(profile_match),
overrides
)
return profile_match
def get_container_profile(name=None, **kwargs):
'''
.. versionadded:: 2015.5.0
Gather a pre-configured set of container configuration parameters. If no
arguments are passed, an empty profile is returned.
Profiles can be defined in the minion or master config files, or in pillar
or grains, and are loaded using :mod:`config.get
<salt.modules.config.get>`. The key under which LXC profiles must be
configured is ``lxc.container_profile.profile_name``. An example container
profile would be as follows:
.. code-block:: yaml
lxc.container_profile:
ubuntu:
template: ubuntu
backing: lvm
vgname: lxc
size: 1G
Parameters set in a profile can be overridden by passing additional
container creation arguments (such as the ones passed to :mod:`lxc.create
<salt.modules.lxc.create>`) to this function.
A profile can be defined either as the name of the profile, or a dictionary
of variable names and values. See the :ref:`LXC Tutorial
<tutorial-lxc-profiles>` for more information on how to use LXC profiles.
CLI Example:
.. code-block:: bash
salt-call lxc.get_container_profile centos
salt-call lxc.get_container_profile ubuntu template=ubuntu backing=overlayfs
'''
profile = _get_profile('container_profile', name, **kwargs)
return profile
def get_network_profile(name=None, **kwargs):
'''
.. versionadded:: 2015.5.0
Gather a pre-configured set of network configuration parameters. If no
arguments are passed, the following default profile is returned:
.. code-block:: python
{'eth0': {'link': 'br0', 'type': 'veth', 'flags': 'up'}}
Profiles can be defined in the minion or master config files, or in pillar
or grains, and are loaded using :mod:`config.get
<salt.modules.config.get>`. The key under which LXC profiles must be
configured is ``lxc.network_profile``. An example network profile would be
as follows:
.. code-block:: yaml
lxc.network_profile.centos:
eth0:
link: br0
type: veth
flags: up
To disable networking entirely:
.. code-block:: yaml
lxc.network_profile.centos:
eth0:
disable: true
Parameters set in a profile can be overridden by passing additional
arguments to this function.
A profile can be passed either as the name of the profile, or a
dictionary of variable names and values. See the :ref:`LXC Tutorial
<tutorial-lxc-profiles>` for more information on how to use network
profiles.
.. warning::
The ``ipv4``, ``ipv6``, ``gateway``, and ``link`` (bridge) settings in
network profiles will only work if the container doesn't redefine the
network configuration (for example in
``/etc/sysconfig/network-scripts/ifcfg-<interface_name>`` on
RHEL/CentOS, or ``/etc/network/interfaces`` on Debian/Ubuntu/etc.)
CLI Example:
.. code-block:: bash
salt-call lxc.get_network_profile default
'''
profile = _get_profile('network_profile', name, **kwargs)
return profile
def _rand_cpu_str(cpu):
'''
Return a random subset of cpus for the cpuset config
'''
cpu = int(cpu)
avail = __salt__['status.nproc']()
if cpu < avail:
return '0-{0}'.format(avail)
to_set = set()
while len(to_set) < cpu:
choice = random.randint(0, avail - 1)
if choice not in to_set:
to_set.add(six.text_type(choice))
return ','.join(sorted(to_set))
def _network_conf(conf_tuples=None, **kwargs):
'''
Network configuration defaults
network_profile
as for containers, we can either call this function
either with a network_profile dict or network profile name
in the kwargs
nic_opts
overrides or extra nics in the form {nic_name: {set: tings}
'''
nic = kwargs.get('network_profile', None)
ret = []
nic_opts = kwargs.get('nic_opts', {})
if nic_opts is None:
# coming from elsewhere
nic_opts = {}
if not conf_tuples:
conf_tuples = []
old = _get_veths(conf_tuples)
if not old:
old = {}
# if we have a profile name, get the profile and load the network settings
# this will obviously by default look for a profile called "eth0"
# or by what is defined in nic_opts
# and complete each nic settings by sane defaults
if nic and isinstance(nic, (six.string_types, dict)):
nicp = get_network_profile(nic)
else:
nicp = {}
if DEFAULT_NIC not in nicp:
nicp[DEFAULT_NIC] = {}
kwargs = copy.deepcopy(kwargs)
gateway = kwargs.pop('gateway', None)
bridge = kwargs.get('bridge', None)
if nic_opts:
for dev, args in six.iteritems(nic_opts):
ethx = nicp.setdefault(dev, {})
try:
ethx = salt.utils.dictupdate.update(ethx, args)
except AttributeError:
raise SaltInvocationError('Invalid nic_opts configuration')
ifs = [a for a in nicp]
ifs += [a for a in old if a not in nicp]
ifs.sort()
gateway_set = False
for dev in ifs:
args = nicp.get(dev, {})
opts = nic_opts.get(dev, {}) if nic_opts else {}
old_if = old.get(dev, {})
disable = opts.get('disable', args.get('disable', False))
if disable:
continue
mac = opts.get('mac',
opts.get('hwaddr',
args.get('mac',
args.get('hwaddr', ''))))
type_ = opts.get('type', args.get('type', ''))
flags = opts.get('flags', args.get('flags', ''))
link = opts.get('link', args.get('link', ''))
ipv4 = opts.get('ipv4', args.get('ipv4', ''))
ipv6 = opts.get('ipv6', args.get('ipv6', ''))
infos = salt.utils.odict.OrderedDict([
('lxc.network.type', {
'test': not type_,
'value': type_,
'old': old_if.get('lxc.network.type'),
'default': 'veth'}),
('lxc.network.name', {
'test': False,
'value': dev,
'old': dev,
'default': dev}),
('lxc.network.flags', {
'test': not flags,
'value': flags,
'old': old_if.get('lxc.network.flags'),
'default': 'up'}),
('lxc.network.link', {
'test': not link,
'value': link,
'old': old_if.get('lxc.network.link'),
'default': search_lxc_bridge()}),
('lxc.network.hwaddr', {
'test': not mac,
'value': mac,
'old': old_if.get('lxc.network.hwaddr'),
'default': salt.utils.network.gen_mac()}),
('lxc.network.ipv4', {
'test': not ipv4,
'value': ipv4,
'old': old_if.get('lxc.network.ipv4', ''),
'default': None}),
('lxc.network.ipv6', {
'test': not ipv6,
'value': ipv6,
'old': old_if.get('lxc.network.ipv6', ''),
'default': None})])
# for each parameter, if not explicitly set, the
# config value present in the LXC configuration should
# take precedence over the profile configuration
for info in list(infos.keys()):
bundle = infos[info]
if bundle['test']:
if bundle['old']:
bundle['value'] = bundle['old']
elif bundle['default']:
bundle['value'] = bundle['default']
for info, data in six.iteritems(infos):
if data['value']:
ret.append({info: data['value']})
for key, val in six.iteritems(args):
if key == 'link' and bridge:
val = bridge
val = opts.get(key, val)
if key in [
'type', 'flags', 'name',
'gateway', 'mac', 'link', 'ipv4', 'ipv6'
]:
continue
ret.append({'lxc.network.{0}'.format(key): val})
# gateway (in automode) must be appended following network conf !
if not gateway:
gateway = args.get('gateway', None)
if gateway is not None and not gateway_set:
ret.append({'lxc.network.ipv4.gateway': gateway})
# only one network gateway ;)
gateway_set = True
# normally, this won't happen
# set the gateway if specified even if we did
# not managed the network underlying
if gateway is not None and not gateway_set:
ret.append({'lxc.network.ipv4.gateway': gateway})
# only one network gateway ;)
gateway_set = True
new = _get_veths(ret)
# verify that we did not loose the mac settings
for iface in [a for a in new]:
ndata = new[iface]
nmac = ndata.get('lxc.network.hwaddr', '')
ntype = ndata.get('lxc.network.type', '')
omac, otype = '', ''
if iface in old:
odata = old[iface]
omac = odata.get('lxc.network.hwaddr', '')
otype = odata.get('lxc.network.type', '')
# default for network type is setted here
# attention not to change the network type
# without a good and explicit reason to.
if otype and not ntype:
ntype = otype
if not ntype:
ntype = 'veth'
new[iface]['lxc.network.type'] = ntype
if omac and not nmac:
new[iface]['lxc.network.hwaddr'] = omac
ret = []
for val in six.itervalues(new):
for row in val:
ret.append(salt.utils.odict.OrderedDict([(row, val[row])]))
# on old versions of lxc, still support the gateway auto mode
# if we didn't explicitly say no to
# (lxc.network.ipv4.gateway: auto)
if _LooseVersion(version()) <= _LooseVersion('1.0.7') and \
True not in ['lxc.network.ipv4.gateway' in a for a in ret] and \
True in ['lxc.network.ipv4' in a for a in ret]:
ret.append({'lxc.network.ipv4.gateway': 'auto'})
return ret
def _get_lxc_default_data(**kwargs):
kwargs = copy.deepcopy(kwargs)
ret = {}
for k in ['utsname', 'rootfs']:
val = kwargs.get(k, None)
if val is not None:
ret['lxc.{0}'.format(k)] = val
autostart = kwargs.get('autostart')
# autostart can have made in kwargs, but with the None
# value which is invalid, we need an explicit boolean
# autostart = on is the default.
if autostart is None:
autostart = True
# we will set the regular lxc marker to restart container at
# machine (re)boot only if we did not explicitly ask
# not to touch to the autostart settings via
# autostart == 'keep'
if autostart != 'keep':
if autostart:
ret['lxc.start.auto'] = '1'
else:
ret['lxc.start.auto'] = '0'
memory = kwargs.get('memory')
if memory is not None:
# converting the config value from MB to bytes
ret['lxc.cgroup.memory.limit_in_bytes'] = memory * 1024 * 1024
cpuset = kwargs.get('cpuset')
if cpuset:
ret['lxc.cgroup.cpuset.cpus'] = cpuset
cpushare = kwargs.get('cpushare')
cpu = kwargs.get('cpu')
if cpushare:
ret['lxc.cgroup.cpu.shares'] = cpushare
if cpu and not cpuset:
ret['lxc.cgroup.cpuset.cpus'] = _rand_cpu_str(cpu)
return ret
def _config_list(conf_tuples=None, only_net=False, **kwargs):
'''
Return a list of dicts from the salt level configurations
conf_tuples
_LXCConfig compatible list of entries which can contain
- string line
- tuple (lxc config param,value)
- dict of one entry: {lxc config param: value)
only_net
by default we add to the tuples a reflection of both
the real config if avalaible and a certain amount of
default values like the cpu parameters, the memory
and etc.
On the other hand, we also no matter the case reflect
the network configuration computed from the actual config if
available and given values.
if no_default_loads is set, we will only
reflect the network configuration back to the conf tuples
list
'''
# explicit cast
only_net = bool(only_net)
if not conf_tuples:
conf_tuples = []
kwargs = copy.deepcopy(kwargs)
ret = []
if not only_net:
default_data = _get_lxc_default_data(**kwargs)
for k, val in six.iteritems(default_data):
ret.append({k: val})
net_datas = _network_conf(conf_tuples=conf_tuples, **kwargs)
ret.extend(net_datas)
return ret
def _get_veths(net_data):
'''
Parse the nic setup inside lxc conf tuples back to a dictionary indexed by
network interface
'''
if isinstance(net_data, dict):
net_data = list(net_data.items())
nics = salt.utils.odict.OrderedDict()
current_nic = salt.utils.odict.OrderedDict()
no_names = True
for item in net_data:
if item and isinstance(item, dict):
item = list(item.items())[0]
# skip LXC configuration comment lines, and play only with tuples conf
elif isinstance(item, six.string_types):
# deal with reflection of commented lxc configs
sitem = item.strip()
if sitem.startswith('#') or not sitem:
continue
elif '=' in item:
item = tuple([a.strip() for a in item.split('=', 1)])
if item[0] == 'lxc.network.type':
current_nic = salt.utils.odict.OrderedDict()
if item[0] == 'lxc.network.name':
no_names = False
nics[item[1].strip()] = current_nic
current_nic[item[0].strip()] = item[1].strip()
# if not ethernet card name has been collected, assuming we collected
# data for eth0
if no_names and current_nic:
nics[DEFAULT_NIC] = current_nic
return nics
class _LXCConfig(object):
'''
LXC configuration data
'''
pattern = re.compile(r'^(\S+)(\s*)(=)(\s*)(.*)')
non_interpretable_pattern = re.compile(r'^((#.*)|(\s*))$')
def __init__(self, **kwargs):
kwargs = copy.deepcopy(kwargs)
self.name = kwargs.pop('name', None)
path = get_root_path(kwargs.get('path', None))
self.data = []
if self.name:
self.path = os.path.join(path, self.name, 'config')
if os.path.isfile(self.path):
with salt.utils.files.fopen(self.path) as fhr:
for line in salt.utils.data.decode(fhr.readlines()):
match = self.pattern.findall((line.strip()))
if match:
self.data.append((match[0][0], match[0][-1]))
match = self.non_interpretable_pattern.findall(
(line.strip()))
if match:
self.data.append(('', match[0][0]))
else:
self.path = None
def _replace(key, val):
if val:
self._filter_data(key)
self.data.append((key, val))
default_data = _get_lxc_default_data(**kwargs)
for key, val in six.iteritems(default_data):
_replace(key, val)
old_net = self._filter_data('lxc.network')
net_datas = _network_conf(conf_tuples=old_net, **kwargs)
if net_datas:
for row in net_datas:
self.data.extend(list(row.items()))
# be sure to reset harmful settings
for idx in ['lxc.cgroup.memory.limit_in_bytes']:
if not default_data.get(idx):
self._filter_data(idx)
def as_string(self):
chunks = ('{0[0]}{1}{0[1]}'.format(item, (' = ' if item[0] else '')) for item in self.data)
return '\n'.join(chunks) + '\n'
def write(self):
if self.path:
content = self.as_string()
# 2 step rendering to be sure not to open/wipe the config
# before as_string succeeds.
with salt.utils.files.fopen(self.path, 'w') as fic:
fic.write(salt.utils.stringutils.to_str(content))
fic.flush()
def tempfile(self):
# this might look like the function name is shadowing the
# module, but it's not since the method belongs to the class
ntf = tempfile.NamedTemporaryFile()
ntf.write(self.as_string())
ntf.flush()
return ntf
def _filter_data(self, pattern):
'''
Removes parameters which match the pattern from the config data
'''
removed = []
filtered = []
for param in self.data:
if not param[0].startswith(pattern):
filtered.append(param)
else:
removed.append(param)
self.data = filtered
return removed
def _get_base(**kwargs):
'''
If the needed base does not exist, then create it, if it does exist
create nothing and return the name of the base lxc container so
it can be cloned.
'''
profile = get_container_profile(copy.deepcopy(kwargs.get('profile')))
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, _marker)
profile_match = profile.pop(key, default)
# let kwarg overrides be the preferred choice
if kw_overrides_match is _marker:
return profile_match
return kw_overrides_match
template = select('template')
image = select('image')
vgname = select('vgname')
path = kwargs.get('path', None)
# remove the above three variables from kwargs, if they exist, to avoid
# duplicates if create() is invoked below.
for param in ('path', 'image', 'vgname', 'template'):
kwargs.pop(param, None)
if image:
proto = _urlparse(image).scheme
img_tar = __salt__['cp.cache_file'](image)
img_name = os.path.basename(img_tar)
hash_ = salt.utils.hashutils.get_hash(
img_tar,
__salt__['config.get']('hash_type'))
name = '__base_{0}_{1}_{2}'.format(proto, img_name, hash_)
if not exists(name, path=path):
create(name, template=template, image=image,
path=path, vgname=vgname, **kwargs)
if vgname:
rootfs = os.path.join('/dev', vgname, name)
edit_conf(info(name, path=path)['config'],
out_format='commented', **{'lxc.rootfs': rootfs})
return name
elif template:
name = '__base_{0}'.format(template)
if not exists(name, path=path):
create(name, template=template, image=image, path=path,
vgname=vgname, **kwargs)
if vgname:
rootfs = os.path.join('/dev', vgname, name)
edit_conf(info(name, path=path)['config'],
out_format='commented', **{'lxc.rootfs': rootfs})
return name
return ''
def init(name,
config=None,
cpuset=None,
cpushare=None,
memory=None,
profile=None,
network_profile=None,
nic_opts=None,
cpu=None,
autostart=True,
password=None,
password_encrypted=None,
users=None,
dnsservers=None,
searchdomains=None,
bridge=None,
gateway=None,
pub_key=None,
priv_key=None,
force_install=False,
unconditional_install=False,
bootstrap_delay=None,
bootstrap_args=None,
bootstrap_shell=None,
bootstrap_url=None,
**kwargs):
'''
Initialize a new container.
This is a partial idempotent function as if it is already provisioned, we
will reset a bit the lxc configuration file but much of the hard work will
be escaped as markers will prevent re-execution of harmful tasks.
name
Name of the container
image
A tar archive to use as the rootfs for the container. Conflicts with
the ``template`` argument.
cpus
Select a random number of cpu cores and assign it to the cpuset, if the
cpuset option is set then this option will be ignored
cpuset
Explicitly define the cpus this container will be bound to
cpushare
cgroups cpu shares
autostart
autostart container on reboot
memory
cgroups memory limit, in MB
.. versionchanged:: 2015.5.0
If no value is passed, no limit is set. In earlier Salt versions,
not passing this value causes a 1024MB memory limit to be set, and
it was necessary to pass ``memory=0`` to set no limit.
gateway
the ipv4 gateway to use
the default does nothing more than lxcutils does
bridge
the bridge to use
the default does nothing more than lxcutils does
network_profile
Network profile to use for the container
.. versionadded:: 2015.5.0
nic_opts
Extra options for network interfaces, will override
``{"eth0": {"hwaddr": "aa:bb:cc:dd:ee:ff", "ipv4": "10.1.1.1", "ipv6": "2001:db8::ff00:42:8329"}}``
or
``{"eth0": {"hwaddr": "aa:bb:cc:dd:ee:ff", "ipv4": "10.1.1.1/24", "ipv6": "2001:db8::ff00:42:8329"}}``
users
Users for which the password defined in the ``password`` param should
be set. Can be passed as a comma separated list or a python list.
Defaults to just the ``root`` user.
password
Set the initial password for the users defined in the ``users``
parameter
password_encrypted : False
Set to ``True`` to denote a password hash instead of a plaintext
password
.. versionadded:: 2015.5.0
profile
A LXC profile (defined in config or pillar).
This can be either a real profile mapping or a string
to retrieve it in configuration
start
Start the newly-created container
dnsservers
list of dns servers to set in the container, default [] (no setting)
seed
Seed the container with the minion config. Default: ``True``
install
If salt-minion is not already installed, install it. Default: ``True``
config
Optional config parameters. By default, the id is set to
the name of the container.
master
salt master (default to minion's master)
master_port
salt master port (default to minion's master port)
pub_key
Explicit public key to preseed the minion with (optional).
This can be either a filepath or a string representing the key
priv_key
Explicit private key to preseed the minion with (optional).
This can be either a filepath or a string representing the key
approve_key
If explicit preseeding is not used;
Attempt to request key approval from the master. Default: ``True``
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
clone_from
Original from which to use a clone operation to create the container.
Default: ``None``
bootstrap_delay
Delay in seconds between end of container creation and bootstrapping.
Useful when waiting for container to obtain a DHCP lease.
.. versionadded:: 2015.5.0
bootstrap_url
See lxc.bootstrap
bootstrap_shell
See lxc.bootstrap
bootstrap_args
See lxc.bootstrap
force_install
Force installation even if salt-minion is detected,
this is the way to run vendor bootstrap scripts even
if a salt minion is already present in the container
unconditional_install
Run the script even if the container seems seeded
CLI Example:
.. code-block:: bash
salt 'minion' lxc.init name [cpuset=cgroups_cpuset] \\
[cpushare=cgroups_cpushare] [memory=cgroups_memory] \\
[nic=nic_profile] [profile=lxc_profile] \\
[nic_opts=nic_opts] [start=(True|False)] \\
[seed=(True|False)] [install=(True|False)] \\
[config=minion_config] [approve_key=(True|False) \\
[clone_from=original] [autostart=True] \\
[priv_key=/path_or_content] [pub_key=/path_or_content] \\
[bridge=lxcbr0] [gateway=10.0.3.1] \\
[dnsservers[dns1,dns2]] \\
[users=[foo]] [password='secret'] \\
[password_encrypted=(True|False)]
'''
ret = {'name': name,
'changes': {}}
profile = get_container_profile(copy.deepcopy(profile))
if not network_profile:
network_profile = profile.get('network_profile')
if not network_profile:
network_profile = DEFAULT_NIC
# Changes is a pointer to changes_dict['init']. This method is used so that
# we can have a list of changes as they are made, providing an ordered list
# of things that were changed.
changes_dict = {'init': []}
changes = changes_dict.get('init')
if users is None:
users = []
dusers = ['root']
for user in dusers:
if user not in users:
users.append(user)
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, _marker)
profile_match = profile.pop(key, default)
# let kwarg overrides be the preferred choice
if kw_overrides_match is _marker:
return profile_match
return kw_overrides_match
path = select('path')
bpath = get_root_path(path)
state_pre = state(name, path=path)
tvg = select('vgname')
vgname = tvg if tvg else __salt__['config.get']('lxc.vgname')
start_ = select('start', True)
autostart = select('autostart', autostart)
seed = select('seed', True)
install = select('install', True)
seed_cmd = select('seed_cmd')
salt_config = _get_salt_config(config, **kwargs)
approve_key = select('approve_key', True)
clone_from = select('clone_from')
# If using a volume group then set up to make snapshot cow clones
if vgname and not clone_from:
try:
kwargs['vgname'] = vgname
clone_from = _get_base(profile=profile, **kwargs)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = exc.strerror
if changes:
ret['changes'] = changes_dict
return ret
if not kwargs.get('snapshot') is False:
kwargs['snapshot'] = True
does_exist = exists(name, path=path)
to_reboot = False
remove_seed_marker = False
if does_exist:
pass
elif clone_from:
remove_seed_marker = True
try:
clone(name, clone_from, profile=profile, **kwargs)
changes.append({'create': 'Container cloned'})
except (SaltInvocationError, CommandExecutionError) as exc:
if 'already exists' in exc.strerror:
changes.append({'create': 'Container already exists'})
else:
ret['result'] = False
ret['comment'] = exc.strerror
if changes:
ret['changes'] = changes_dict
return ret
cfg = _LXCConfig(name=name, network_profile=network_profile,
nic_opts=nic_opts, bridge=bridge, path=path,
gateway=gateway, autostart=autostart,
cpuset=cpuset, cpushare=cpushare, memory=memory)
old_chunks = read_conf(cfg.path, out_format='commented')
cfg.write()
chunks = read_conf(cfg.path, out_format='commented')
if old_chunks != chunks:
to_reboot = True
else:
remove_seed_marker = True
cfg = _LXCConfig(network_profile=network_profile,
nic_opts=nic_opts, cpuset=cpuset, path=path,
bridge=bridge, gateway=gateway,
autostart=autostart,
cpushare=cpushare, memory=memory)
with cfg.tempfile() as cfile:
try:
create(name, config=cfile.name, profile=profile, **kwargs)
changes.append({'create': 'Container created'})
except (SaltInvocationError, CommandExecutionError) as exc:
if 'already exists' in exc.strerror:
changes.append({'create': 'Container already exists'})
else:
ret['comment'] = exc.strerror
if changes:
ret['changes'] = changes_dict
return ret
cpath = os.path.join(bpath, name, 'config')
old_chunks = []
if os.path.exists(cpath):
old_chunks = read_conf(cpath, out_format='commented')
new_cfg = _config_list(conf_tuples=old_chunks,
cpu=cpu,
network_profile=network_profile,
nic_opts=nic_opts, bridge=bridge,
cpuset=cpuset, cpushare=cpushare,
memory=memory)
if new_cfg:
edit_conf(cpath, out_format='commented', lxc_config=new_cfg)
chunks = read_conf(cpath, out_format='commented')
if old_chunks != chunks:
to_reboot = True
# last time to be sure any of our property is correctly applied
cfg = _LXCConfig(name=name, network_profile=network_profile,
nic_opts=nic_opts, bridge=bridge, path=path,
gateway=gateway, autostart=autostart,
cpuset=cpuset, cpushare=cpushare, memory=memory)
old_chunks = []
if os.path.exists(cfg.path):
old_chunks = read_conf(cfg.path, out_format='commented')
cfg.write()
chunks = read_conf(cfg.path, out_format='commented')
if old_chunks != chunks:
changes.append({'config': 'Container configuration updated'})
to_reboot = True
if to_reboot:
try:
stop(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
if changes:
ret['changes'] = changes_dict
return ret
if not does_exist or (does_exist and state(name, path=path) != 'running'):
try:
start(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
if changes:
ret['changes'] = changes_dict
return ret
if remove_seed_marker:
run(name,
'rm -f \'{0}\''.format(SEED_MARKER),
path=path,
chroot_fallback=False,
python_shell=False)
# set the default user/password, only the first time
if ret.get('result', True) and password:
gid = '/.lxc.initial_pass'
gids = [gid,
'/lxc.initial_pass',
'/.lxc.{0}.initial_pass'.format(name)]
if not any(retcode(name,
'test -e "{0}"'.format(x),
chroot_fallback=True,
path=path,
ignore_retcode=True) == 0
for x in gids):
# think to touch the default user generated by default templates
# which has a really unsecure passwords...
# root is defined as a member earlier in the code
for default_user in ['ubuntu']:
if (
default_user not in users and
retcode(name,
'id {0}'.format(default_user),
python_shell=False,
path=path,
chroot_fallback=True,
ignore_retcode=True) == 0
):
users.append(default_user)
for user in users:
try:
cret = set_password(name,
users=[user],
path=path,
password=password,
encrypted=password_encrypted)
except (SaltInvocationError, CommandExecutionError) as exc:
msg = '{0}: Failed to set password'.format(
user) + exc.strerror
# only hardfail in unrecoverable situation:
# root cannot be setted up
if user == 'root':
ret['comment'] = msg
ret['result'] = False
else:
log.debug(msg)
if ret.get('result', True):
changes.append({'password': 'Password(s) updated'})
if retcode(name,
('sh -c \'touch "{0}"; test -e "{0}"\''
.format(gid)),
path=path,
chroot_fallback=True,
ignore_retcode=True) != 0:
ret['comment'] = 'Failed to set password marker'
changes[-1]['password'] += '. ' + ret['comment'] + '.'
ret['result'] = False
# set dns servers if any, only the first time
if ret.get('result', True) and dnsservers:
# retro compatibility, test also old markers
gid = '/.lxc.initial_dns'
gids = [gid,
'/lxc.initial_dns',
'/lxc.{0}.initial_dns'.format(name)]
if not any(retcode(name,
'test -e "{0}"'.format(x),
chroot_fallback=True,
path=path,
ignore_retcode=True) == 0
for x in gids):
try:
set_dns(name,
path=path,
dnsservers=dnsservers,
searchdomains=searchdomains)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Failed to set DNS: ' + exc.strerror
ret['result'] = False
else:
changes.append({'dns': 'DNS updated'})
if retcode(name,
('sh -c \'touch "{0}"; test -e "{0}"\''
.format(gid)),
chroot_fallback=True,
path=path,
ignore_retcode=True) != 0:
ret['comment'] = 'Failed to set DNS marker'
changes[-1]['dns'] += '. ' + ret['comment'] + '.'
ret['result'] = False
# retro compatibility, test also old markers
if remove_seed_marker:
run(name,
'rm -f \'{0}\''.format(SEED_MARKER),
path=path,
python_shell=False)
gid = '/.lxc.initial_seed'
gids = [gid, '/lxc.initial_seed']
if (
any(retcode(name,
'test -e {0}'.format(x),
path=path,
chroot_fallback=True,
ignore_retcode=True) == 0
for x in gids) or not ret.get('result', True)
):
pass
elif seed or seed_cmd:
if seed:
try:
result = bootstrap(
name, config=salt_config, path=path,
approve_key=approve_key,
pub_key=pub_key, priv_key=priv_key,
install=install,
force_install=force_install,
unconditional_install=unconditional_install,
bootstrap_delay=bootstrap_delay,
bootstrap_url=bootstrap_url,
bootstrap_shell=bootstrap_shell,
bootstrap_args=bootstrap_args)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Bootstrap failed: ' + exc.strerror
ret['result'] = False
else:
if not result:
ret['comment'] = ('Bootstrap failed, see minion log for '
'more information')
ret['result'] = False
else:
changes.append(
{'bootstrap': 'Container successfully bootstrapped'}
)
elif seed_cmd:
try:
result = __salt__[seed_cmd](info(name, path=path)['rootfs'],
name,
salt_config)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = ('Bootstrap via seed_cmd \'{0}\' failed: {1}'
.format(seed_cmd, exc.strerror))
ret['result'] = False
else:
if not result:
ret['comment'] = ('Bootstrap via seed_cmd \'{0}\' failed, '
'see minion log for more information '
.format(seed_cmd))
ret['result'] = False
else:
changes.append(
{'bootstrap': 'Container successfully bootstrapped '
'using seed_cmd \'{0}\''
.format(seed_cmd)}
)
if ret.get('result', True) and not start_:
try:
stop(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
ret['result'] = False
state_post = state(name, path=path)
if state_pre != state_post:
changes.append({'state': {'old': state_pre, 'new': state_post}})
if ret.get('result', True):
ret['comment'] = ('Container \'{0}\' successfully initialized'
.format(name))
ret['result'] = True
if changes:
ret['changes'] = changes_dict
return ret
def cloud_init(name, vm_=None, **kwargs):
'''
Thin wrapper to lxc.init to be used from the saltcloud lxc driver
name
Name of the container
may be None and then guessed from saltcloud mapping
`vm_`
saltcloud mapping defaults for the vm
CLI Example:
.. code-block:: bash
salt '*' lxc.cloud_init foo
'''
init_interface = cloud_init_interface(name, vm_, **kwargs)
name = init_interface.pop('name', name)
return init(name, **init_interface)
def images(dist=None):
'''
.. versionadded:: 2015.5.0
List the available images for LXC's ``download`` template.
dist : None
Filter results to a single Linux distribution
CLI Examples:
.. code-block:: bash
salt myminion lxc.images
salt myminion lxc.images dist=centos
'''
out = __salt__['cmd.run_stdout'](
'lxc-create -n __imgcheck -t download -- --list',
ignore_retcode=True
)
if 'DIST' not in out:
raise CommandExecutionError(
'Unable to run the \'download\' template script. Is it installed?'
)
ret = {}
passed_header = False
for line in out.splitlines():
try:
distro, release, arch, variant, build_time = line.split()
except ValueError:
continue
if not passed_header:
if distro == 'DIST':
passed_header = True
continue
dist_list = ret.setdefault(distro, [])
dist_list.append({
'release': release,
'arch': arch,
'variant': variant,
'build_time': build_time,
})
if dist is not None:
return dict([(dist, ret.get(dist, []))])
return ret
def templates():
'''
.. versionadded:: 2015.5.0
List the available LXC template scripts installed on the minion
CLI Examples:
.. code-block:: bash
salt myminion lxc.templates
'''
try:
template_scripts = os.listdir('/usr/share/lxc/templates')
except OSError:
return []
else:
return [x[4:] for x in template_scripts if x.startswith('lxc-')]
def _after_ignition_network_profile(cmd,
ret,
name,
network_profile,
path,
nic_opts):
_clear_context()
if ret['retcode'] == 0 and exists(name, path=path):
if network_profile:
network_changes = apply_network_profile(name,
network_profile,
path=path,
nic_opts=nic_opts)
if network_changes:
log.info(
'Network changes from applying network profile \'%s\' '
'to newly-created container \'%s\':\n%s',
network_profile, name, network_changes
)
c_state = state(name, path=path)
return {'result': True,
'state': {'old': None, 'new': c_state}}
else:
if exists(name, path=path):
# destroy the container if it was partially created
cmd = 'lxc-destroy'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0}'.format(name)
__salt__['cmd.retcode'](cmd, python_shell=False)
raise CommandExecutionError(
'Container could not be created with cmd \'{0}\': {1}'
.format(cmd, ret['stderr'])
)
def create(name,
config=None,
profile=None,
network_profile=None,
nic_opts=None,
**kwargs):
'''
Create a new container.
name
Name of the container
config
The config file to use for the container. Defaults to system-wide
config (usually in /etc/lxc/lxc.conf).
profile
Profile to use in container creation (see
:mod:`lxc.get_container_profile
<salt.modules.lxc.get_container_profile>`). Values in a profile will be
overridden by the **Container Creation Arguments** listed below.
network_profile
Network profile to use for container
.. versionadded:: 2015.5.0
**Container Creation Arguments**
template
The template to use. For example, ``ubuntu`` or ``fedora``.
For a full list of available templates, check out
the :mod:`lxc.templates <salt.modules.lxc.templates>` function.
Conflicts with the ``image`` argument.
.. note::
The ``download`` template requires the following three parameters
to be defined in ``options``:
* **dist** - The name of the distribution
* **release** - Release name/version
* **arch** - Architecture of the container
The available images can be listed using the :mod:`lxc.images
<salt.modules.lxc.images>` function.
options
Template-specific options to pass to the lxc-create command. These
correspond to the long options (ones beginning with two dashes) that
the template script accepts. For example:
.. code-block:: bash
options='{"dist": "centos", "release": "6", "arch": "amd64"}'
For available template options, refer to the lxc template scripts
which are ususally located under ``/usr/share/lxc/templates``,
or run ``lxc-create -t <template> -h``.
image
A tar archive to use as the rootfs for the container. Conflicts with
the ``template`` argument.
backing
The type of storage to use. Set to ``lvm`` to use an LVM group.
Defaults to filesystem within /var/lib/lxc.
fstype
Filesystem type to use on LVM logical volume
size : 1G
Size of the volume to create. Only applicable if ``backing=lvm``.
vgname : lxc
Name of the LVM volume group in which to create the volume for this
container. Only applicable if ``backing=lvm``.
lvname
Name of the LVM logical volume in which to create the volume for this
container. Only applicable if ``backing=lvm``.
thinpool
Name of a pool volume that will be used for thin-provisioning this
container. Only applicable if ``backing=lvm``.
nic_opts
give extra opts overriding network profile values
path
parent path for the container creation (default: /var/lib/lxc)
zfsroot
Name of the ZFS root in which to create the volume for this container.
Only applicable if ``backing=zfs``. (default: tank/lxc)
.. versionadded:: 2015.8.0
'''
# Required params for 'download' template
download_template_deps = ('dist', 'release', 'arch')
cmd = 'lxc-create -n {0}'.format(name)
profile = get_container_profile(copy.deepcopy(profile))
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, None)
profile_match = profile.pop(key, default)
# Return the profile match if the the kwarg match was None, as the
# lxc.present state will pass these kwargs set to None by default.
if kw_overrides_match is None:
return profile_match
return kw_overrides_match
path = select('path')
if exists(name, path=path):
raise CommandExecutionError(
'Container \'{0}\' already exists'.format(name)
)
tvg = select('vgname')
vgname = tvg if tvg else __salt__['config.get']('lxc.vgname')
# The 'template' and 'image' params conflict
template = select('template')
image = select('image')
if template and image:
raise SaltInvocationError(
'Only one of \'template\' and \'image\' is permitted'
)
elif not any((template, image, profile)):
raise SaltInvocationError(
'At least one of \'template\', \'image\', and \'profile\' is '
'required'
)
options = select('options') or {}
backing = select('backing')
if vgname and not backing:
backing = 'lvm'
lvname = select('lvname')
thinpool = select('thinpool')
fstype = select('fstype')
size = select('size', '1G')
zfsroot = select('zfsroot')
if backing in ('dir', 'overlayfs', 'btrfs', 'zfs'):
fstype = None
size = None
# some backends won't support some parameters
if backing in ('aufs', 'dir', 'overlayfs', 'btrfs'):
lvname = vgname = thinpool = None
if image:
img_tar = __salt__['cp.cache_file'](image)
template = os.path.join(
os.path.dirname(salt.__file__),
'templates',
'lxc',
'salt_tarball')
options['imgtar'] = img_tar
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
if not os.path.exists(path):
os.makedirs(path)
if config:
cmd += ' -f {0}'.format(config)
if template:
cmd += ' -t {0}'.format(template)
if backing:
backing = backing.lower()
cmd += ' -B {0}'.format(backing)
if backing in ('zfs',):
if zfsroot:
cmd += ' --zfsroot {0}'.format(zfsroot)
if backing in ('lvm',):
if lvname:
cmd += ' --lvname {0}'.format(lvname)
if vgname:
cmd += ' --vgname {0}'.format(vgname)
if thinpool:
cmd += ' --thinpool {0}'.format(thinpool)
if backing not in ('dir', 'overlayfs'):
if fstype:
cmd += ' --fstype {0}'.format(fstype)
if size:
cmd += ' --fssize {0}'.format(size)
if options:
if template == 'download':
missing_deps = [x for x in download_template_deps
if x not in options]
if missing_deps:
raise SaltInvocationError(
'Missing params in \'options\' dict: {0}'
.format(', '.join(missing_deps))
)
cmd += ' --'
for key, val in six.iteritems(options):
cmd += ' --{0} {1}'.format(key, val)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
# please do not merge extra conflicting stuff
# inside those two line (ret =, return)
return _after_ignition_network_profile(cmd,
ret,
name,
network_profile,
path,
nic_opts)
def ls_(active=None, cache=True, path=None):
'''
Return a list of the containers available on the minion
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
active
If ``True``, return only active (i.e. running) containers
.. versionadded:: 2015.5.0
CLI Example:
.. code-block:: bash
salt '*' lxc.ls
salt '*' lxc.ls active=True
'''
contextvar = 'lxc.ls{0}'.format(path)
if active:
contextvar += '.active'
if cache and (contextvar in __context__):
return __context__[contextvar]
else:
ret = []
cmd = 'lxc-ls'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
if active:
cmd += ' --active'
output = __salt__['cmd.run_stdout'](cmd, python_shell=False)
for line in output.splitlines():
ret.extend(line.split())
__context__[contextvar] = ret
return ret
def list_(extra=False, limit=None, path=None):
'''
List containers classified by state
extra
Also get per-container specific info. This will change the return data.
Instead of returning a list of containers, a dictionary of containers
and each container's output from :mod:`lxc.info
<salt.modules.lxc.info>`.
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
limit
Return output matching a specific state (**frozen**, **running**, or
**stopped**).
.. versionadded:: 2015.5.0
CLI Examples:
.. code-block:: bash
salt '*' lxc.list
salt '*' lxc.list extra=True
salt '*' lxc.list limit=running
'''
ctnrs = ls_(path=path)
if extra:
stopped = {}
frozen = {}
running = {}
else:
stopped = []
frozen = []
running = []
ret = {'running': running,
'stopped': stopped,
'frozen': frozen}
for container in ctnrs:
cmd = 'lxc-info'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0}'.format(container)
c_info = __salt__['cmd.run'](
cmd,
python_shell=False,
output_loglevel='debug'
)
c_state = None
for line in c_info.splitlines():
stat = line.split(':')
if stat[0] in ('State', 'state'):
c_state = stat[1].strip()
break
if not c_state or (limit is not None and c_state.lower() != limit):
continue
if extra:
infos = info(container, path=path)
method = 'update'
value = {container: infos}
else:
method = 'append'
value = container
if c_state == 'STOPPED':
getattr(stopped, method)(value)
continue
if c_state == 'FROZEN':
getattr(frozen, method)(value)
continue
if c_state == 'RUNNING':
getattr(running, method)(value)
continue
if limit is not None:
return ret.get(limit, {} if extra else [])
return ret
def _change_state(cmd,
name,
expected,
stdin=_marker,
stdout=_marker,
stderr=_marker,
with_communicate=_marker,
use_vt=_marker,
path=None):
pre = state(name, path=path)
if pre == expected:
return {'result': True,
'state': {'old': expected, 'new': expected},
'comment': 'Container \'{0}\' already {1}'
.format(name, expected)}
if cmd == 'lxc-destroy':
# Kill the container first
scmd = 'lxc-stop'
if path:
scmd += ' -P {0}'.format(pipes.quote(path))
scmd += ' -k -n {0}'.format(name)
__salt__['cmd.run'](scmd,
python_shell=False)
if path and ' -P ' not in cmd:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0}'.format(name)
# certain lxc commands need to be taken with care (lxc-start)
# as te command itself mess with double forks; we must not
# communicate with it, but just wait for the exit status
pkwargs = {'python_shell': False,
'redirect_stderr': True,
'with_communicate': with_communicate,
'use_vt': use_vt,
'stdin': stdin,
'stdout': stdout}
for i in [a for a in pkwargs]:
val = pkwargs[i]
if val is _marker:
pkwargs.pop(i, None)
_cmdout = __salt__['cmd.run_all'](cmd, **pkwargs)
if _cmdout['retcode'] != 0:
raise CommandExecutionError(
'Error changing state for container \'{0}\' using command '
'\'{1}\': {2}'.format(name, cmd, _cmdout['stdout'])
)
if expected is not None:
# some commands do not wait, so we will
rcmd = 'lxc-wait'
if path:
rcmd += ' -P {0}'.format(pipes.quote(path))
rcmd += ' -n {0} -s {1}'.format(name, expected.upper())
__salt__['cmd.run'](rcmd, python_shell=False, timeout=30)
_clear_context()
post = state(name, path=path)
ret = {'result': post == expected,
'state': {'old': pre, 'new': post}}
return ret
def _ensure_exists(name, path=None):
'''
Raise an exception if the container does not exist
'''
if not exists(name, path=path):
raise CommandExecutionError(
'Container \'{0}\' does not exist'.format(name)
)
def _ensure_running(name, no_start=False, path=None):
'''
If the container is not currently running, start it. This function returns
the state that the container was in before changing
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
'''
_ensure_exists(name, path=path)
pre = state(name, path=path)
if pre == 'running':
# This will be a no-op but running the function will give us a pretty
# return dict.
return start(name, path=path)
elif pre == 'stopped':
if no_start:
raise CommandExecutionError(
'Container \'{0}\' is not running'.format(name)
)
return start(name, path=path)
elif pre == 'frozen':
if no_start:
raise CommandExecutionError(
'Container \'{0}\' is not running'.format(name)
)
return unfreeze(name, path=path)
def restart(name, path=None, lxc_config=None, force=False):
'''
.. versionadded:: 2015.5.0
Restart the named container. If the container was not running, the
container will merely be started.
name
The name of the container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
lxc_config
path to a lxc config file
config file will be guessed from container name otherwise
.. versionadded:: 2015.8.0
force : False
If ``True``, the container will be force-stopped instead of gracefully
shut down
CLI Example:
.. code-block:: bash
salt myminion lxc.restart name
'''
_ensure_exists(name, path=path)
orig_state = state(name, path=path)
if orig_state != 'stopped':
stop(name, kill=force, path=path)
ret = start(name, path=path, lxc_config=lxc_config)
ret['state']['old'] = orig_state
if orig_state != 'stopped':
ret['restarted'] = True
return ret
def start(name, **kwargs):
'''
Start the named container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
lxc_config
path to a lxc config file
config file will be guessed from container name otherwise
.. versionadded:: 2015.8.0
use_vt
run the command through VT
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.start name
'''
path = kwargs.get('path', None)
cpath = get_root_path(path)
lxc_config = kwargs.get('lxc_config', None)
cmd = 'lxc-start'
if not lxc_config:
lxc_config = os.path.join(cpath, name, 'config')
# we try to start, even without config, if global opts are there
if os.path.exists(lxc_config):
cmd += ' -f {0}'.format(pipes.quote(lxc_config))
cmd += ' -d'
_ensure_exists(name, path=path)
if state(name, path=path) == 'frozen':
raise CommandExecutionError(
'Container \'{0}\' is frozen, use lxc.unfreeze'.format(name)
)
# lxc-start daemonize itself violently, we must not communicate with it
use_vt = kwargs.get('use_vt', None)
with_communicate = kwargs.get('with_communicate', False)
return _change_state(cmd, name, 'running',
stdout=None,
stderr=None,
stdin=None,
with_communicate=with_communicate,
path=path,
use_vt=use_vt)
def stop(name, kill=False, path=None, use_vt=None):
'''
Stop the named container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
kill: False
Do not wait for the container to stop, kill all tasks in the container.
Older LXC versions will stop containers like this irrespective of this
argument.
.. versionchanged:: 2015.5.0
Default value changed to ``False``
use_vt
run the command through VT
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.stop name
'''
_ensure_exists(name, path=path)
orig_state = state(name, path=path)
if orig_state == 'frozen' and not kill:
# Gracefully stopping a frozen container is slower than unfreezing and
# then stopping it (at least in my testing), so if we're not
# force-stopping the container, unfreeze it first.
unfreeze(name, path=path)
cmd = 'lxc-stop'
if kill:
cmd += ' -k'
ret = _change_state(cmd, name, 'stopped', use_vt=use_vt, path=path)
ret['state']['old'] = orig_state
return ret
def freeze(name, **kwargs):
'''
Freeze the named container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
start : False
If ``True`` and the container is stopped, the container will be started
before attempting to freeze.
.. versionadded:: 2015.5.0
use_vt
run the command through VT
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.freeze name
'''
use_vt = kwargs.get('use_vt', None)
path = kwargs.get('path', None)
_ensure_exists(name, path=path)
orig_state = state(name, path=path)
start_ = kwargs.get('start', False)
if orig_state == 'stopped':
if not start_:
raise CommandExecutionError(
'Container \'{0}\' is stopped'.format(name)
)
start(name, path=path)
cmd = 'lxc-freeze'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
ret = _change_state(cmd, name, 'frozen', use_vt=use_vt, path=path)
if orig_state == 'stopped' and start_:
ret['state']['old'] = orig_state
ret['started'] = True
ret['state']['new'] = state(name, path=path)
return ret
def unfreeze(name, path=None, use_vt=None):
'''
Unfreeze the named container.
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
use_vt
run the command through VT
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.unfreeze name
'''
_ensure_exists(name, path=path)
if state(name, path=path) == 'stopped':
raise CommandExecutionError(
'Container \'{0}\' is stopped'.format(name)
)
cmd = 'lxc-unfreeze'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
return _change_state(cmd, name, 'running', path=path, use_vt=use_vt)
def destroy(name, stop=False, path=None):
'''
Destroy the named container.
.. warning::
Destroys all data associated with the container.
path
path to the container parent directory (default: /var/lib/lxc)
.. versionadded:: 2015.8.0
stop : False
If ``True``, the container will be destroyed even if it is
running/frozen.
.. versionchanged:: 2015.5.0
Default value changed to ``False``. This more closely matches the
behavior of ``lxc-destroy(1)``, and also makes it less likely that
an accidental command will destroy a running container that was
being used for important things.
CLI Examples:
.. code-block:: bash
salt '*' lxc.destroy foo
salt '*' lxc.destroy foo stop=True
'''
_ensure_exists(name, path=path)
if not stop and state(name, path=path) != 'stopped':
raise CommandExecutionError(
'Container \'{0}\' is not stopped'.format(name)
)
return _change_state('lxc-destroy', name, None, path=path)
# Compatibility between LXC and nspawn
remove = salt.utils.functools.alias_function(destroy, 'remove')
def exists(name, path=None):
'''
Returns whether the named container exists.
path
path to the container parent directory (default: /var/lib/lxc)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.exists name
'''
_exists = name in ls_(path=path)
# container may be just created but we did cached earlier the
# lxc-ls results
if not _exists:
_exists = name in ls_(cache=False, path=path)
return _exists
def state(name, path=None):
'''
Returns the state of a container.
path
path to the container parent directory (default: /var/lib/lxc)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.state name
'''
# Don't use _ensure_exists() here, it will mess with _change_state()
cachekey = 'lxc.state.{0}{1}'.format(name, path)
try:
return __context__[cachekey]
except KeyError:
if not exists(name, path=path):
__context__[cachekey] = None
else:
cmd = 'lxc-info'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0}'.format(name)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
if ret['retcode'] != 0:
_clear_context()
raise CommandExecutionError(
'Unable to get state of container \'{0}\''.format(name)
)
c_infos = ret['stdout'].splitlines()
c_state = None
for c_info in c_infos:
stat = c_info.split(':')
if stat[0].lower() == 'state':
c_state = stat[1].strip().lower()
break
__context__[cachekey] = c_state
return __context__[cachekey]
def get_parameter(name, parameter, path=None):
'''
Returns the value of a cgroup parameter for a container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.get_parameter container_name memory.limit_in_bytes
'''
_ensure_exists(name, path=path)
cmd = 'lxc-cgroup'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0} {1}'.format(name, parameter)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
if ret['retcode'] != 0:
raise CommandExecutionError(
'Unable to retrieve value for \'{0}\''.format(parameter)
)
return ret['stdout'].strip()
def set_parameter(name, parameter, value, path=None):
'''
Set the value of a cgroup parameter for a container.
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.set_parameter name parameter value
'''
if not exists(name, path=path):
return None
cmd = 'lxc-cgroup'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0} {1} {2}'.format(name, parameter, value)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
if ret['retcode'] != 0:
return False
else:
return True
def info(name, path=None):
'''
Returns information about a container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.info name
'''
cachekey = 'lxc.info.{0}{1}'.format(name, path)
try:
return __context__[cachekey]
except KeyError:
_ensure_exists(name, path=path)
cpath = get_root_path(path)
try:
conf_file = os.path.join(cpath, name, 'config')
except AttributeError:
conf_file = os.path.join(cpath, six.text_type(name), 'config')
if not os.path.isfile(conf_file):
raise CommandExecutionError(
'LXC config file {0} does not exist'.format(conf_file)
)
ret = {}
config = []
with salt.utils.files.fopen(conf_file) as fp_:
for line in fp_:
line = salt.utils.stringutils.to_unicode(line)
comps = [x.strip() for x in
line.split('#', 1)[0].strip().split('=', 1)]
if len(comps) == 2:
config.append(tuple(comps))
ifaces = []
current = None
for key, val in config:
if key == 'lxc.network.type':
current = {'type': val}
ifaces.append(current)
elif not current:
continue
elif key.startswith('lxc.network.'):
current[key.replace('lxc.network.', '', 1)] = val
if ifaces:
ret['nics'] = ifaces
ret['rootfs'] = next(
(x[1] for x in config if x[0] == 'lxc.rootfs'),
None
)
ret['state'] = state(name, path=path)
ret['ips'] = []
ret['public_ips'] = []
ret['private_ips'] = []
ret['public_ipv4_ips'] = []
ret['public_ipv6_ips'] = []
ret['private_ipv4_ips'] = []
ret['private_ipv6_ips'] = []
ret['ipv4_ips'] = []
ret['ipv6_ips'] = []
ret['size'] = None
ret['config'] = conf_file
if ret['state'] == 'running':
try:
limit = int(get_parameter(name, 'memory.limit_in_bytes'))
except (CommandExecutionError, TypeError, ValueError):
limit = 0
try:
usage = int(get_parameter(name, 'memory.usage_in_bytes'))
except (CommandExecutionError, TypeError, ValueError):
usage = 0
free = limit - usage
ret['memory_limit'] = limit
ret['memory_free'] = free
size = run_stdout(name, 'df /', path=path, python_shell=False)
# The size is the 2nd column of the last line
ret['size'] = size.splitlines()[-1].split()[1]
# First try iproute2
ip_cmd = run_all(
name, 'ip link show', path=path, python_shell=False)
if ip_cmd['retcode'] == 0:
ip_data = ip_cmd['stdout']
ip_cmd = run_all(
name, 'ip addr show', path=path, python_shell=False)
ip_data += '\n' + ip_cmd['stdout']
ip_data = salt.utils.network._interfaces_ip(ip_data)
else:
# That didn't work, try ifconfig
ip_cmd = run_all(
name, 'ifconfig', path=path, python_shell=False)
if ip_cmd['retcode'] == 0:
ip_data = \
salt.utils.network._interfaces_ifconfig(
ip_cmd['stdout'])
else:
# Neither was successful, give up
log.warning(
'Unable to run ip or ifconfig in container \'%s\'', name
)
ip_data = {}
ret['ipv4_ips'] = salt.utils.network.ip_addrs(
include_loopback=True,
interface_data=ip_data
)
ret['ipv6_ips'] = salt.utils.network.ip_addrs6(
include_loopback=True,
interface_data=ip_data
)
ret['ips'] = ret['ipv4_ips'] + ret['ipv6_ips']
for address in ret['ipv4_ips']:
if address == '127.0.0.1':
ret['private_ips'].append(address)
ret['private_ipv4_ips'].append(address)
elif salt.utils.cloud.is_public_ip(address):
ret['public_ips'].append(address)
ret['public_ipv4_ips'].append(address)
else:
ret['private_ips'].append(address)
ret['private_ipv4_ips'].append(address)
for address in ret['ipv6_ips']:
if address == '::1' or address.startswith('fe80'):
ret['private_ips'].append(address)
ret['private_ipv6_ips'].append(address)
else:
ret['public_ips'].append(address)
ret['public_ipv6_ips'].append(address)
for key in [x for x in ret if x == 'ips' or x.endswith('ips')]:
ret[key].sort(key=_ip_sort)
__context__[cachekey] = ret
return __context__[cachekey]
def set_password(name, users, password, encrypted=True, path=None):
'''
.. versionchanged:: 2015.5.0
Function renamed from ``set_pass`` to ``set_password``. Additionally,
this function now supports (and defaults to using) a password hash
instead of a plaintext password.
Set the password of one or more system users inside containers
users
Comma-separated list (or python list) of users to change password
password
Password to set for the specified user(s)
encrypted : True
If true, ``password`` must be a password hash. Set to ``False`` to set
a plaintext password (not recommended).
.. versionadded:: 2015.5.0
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.set_pass container-name root '$6$uJ2uAyLU$KoI67t8As/0fXtJOPcHKGXmUpcoYUcVR2K6x93walnShTCQvjRwq25yIkiCBOqgbfdKQSFnAo28/ek6716vEV1'
salt '*' lxc.set_pass container-name root foo encrypted=False
'''
def _bad_user_input():
raise SaltInvocationError('Invalid input for \'users\' parameter')
if not isinstance(users, list):
try:
users = users.split(',')
except AttributeError:
_bad_user_input()
if not users:
_bad_user_input()
failed_users = []
for user in users:
result = retcode(name,
'chpasswd{0}'.format(' -e' if encrypted else ''),
stdin=':'.join((user, password)),
python_shell=False,
path=path,
chroot_fallback=True,
output_loglevel='quiet')
if result != 0:
failed_users.append(user)
if failed_users:
raise CommandExecutionError(
'Password change failed for the following user(s): {0}'
.format(', '.join(failed_users))
)
return True
set_pass = salt.utils.functools.alias_function(set_password, 'set_pass')
def update_lxc_conf(name, lxc_conf, lxc_conf_unset, path=None):
'''
Edit LXC configuration options
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.update_lxc_conf ubuntu \\
lxc_conf="[{'network.ipv4.ip':'10.0.3.5'}]" \\
lxc_conf_unset="['lxc.utsname']"
'''
_ensure_exists(name, path=path)
cpath = get_root_path(path)
lxc_conf_p = os.path.join(cpath, name, 'config')
if not os.path.exists(lxc_conf_p):
raise SaltInvocationError(
'Configuration file {0} does not exist'.format(lxc_conf_p)
)
changes = {'edited': [], 'added': [], 'removed': []}
ret = {'changes': changes, 'result': True, 'comment': ''}
# do not use salt.utils.files.fopen !
with salt.utils.files.fopen(lxc_conf_p, 'r') as fic:
filtered_lxc_conf = []
for row in lxc_conf:
if not row:
continue
for conf in row:
filtered_lxc_conf.append((conf.strip(),
row[conf].strip()))
ret['comment'] = 'lxc.conf is up to date'
lines = []
orig_config = salt.utils.stringutils.to_unicode(fic.read())
for line in orig_config.splitlines():
if line.startswith('#') or not line.strip():
lines.append([line, ''])
else:
line = line.split('=')
index = line.pop(0)
val = (index.strip(), '='.join(line).strip())
if val not in lines:
lines.append(val)
for key, item in filtered_lxc_conf:
matched = False
for idx, line in enumerate(lines[:]):
if line[0] == key:
matched = True
lines[idx] = (key, item)
if '='.join(line[1:]).strip() != item.strip():
changes['edited'].append(
({line[0]: line[1:]}, {key: item}))
break
if not matched:
if (key, item) not in lines:
lines.append((key, item))
changes['added'].append({key: item})
dest_lxc_conf = []
# filter unset
if lxc_conf_unset:
for line in lines:
for opt in lxc_conf_unset:
if (
not line[0].startswith(opt) and
line not in dest_lxc_conf
):
dest_lxc_conf.append(line)
else:
changes['removed'].append(opt)
else:
dest_lxc_conf = lines
conf = ''
for key, val in dest_lxc_conf:
if not val:
conf += '{0}\n'.format(key)
else:
conf += '{0} = {1}\n'.format(key.strip(), val.strip())
conf_changed = conf != orig_config
chrono = datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S')
if conf_changed:
# DO NOT USE salt.utils.files.fopen here, i got (kiorky)
# problems with lxc configs which were wiped !
with salt.utils.files.fopen('{0}.{1}'.format(lxc_conf_p, chrono), 'w') as wfic:
wfic.write(salt.utils.stringutils.to_str(conf))
with salt.utils.files.fopen(lxc_conf_p, 'w') as wfic:
wfic.write(salt.utils.stringutils.to_str(conf))
ret['comment'] = 'Updated'
ret['result'] = True
if not any(changes[x] for x in changes):
# Ensure an empty changes dict if nothing was modified
ret['changes'] = {}
return ret
def set_dns(name, dnsservers=None, searchdomains=None, path=None):
'''
.. versionchanged:: 2015.5.0
The ``dnsservers`` and ``searchdomains`` parameters can now be passed
as a comma-separated list.
Update /etc/resolv.confo
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.set_dns ubuntu "['8.8.8.8', '4.4.4.4']"
'''
if dnsservers is None:
dnsservers = ['8.8.8.8', '4.4.4.4']
elif not isinstance(dnsservers, list):
try:
dnsservers = dnsservers.split(',')
except AttributeError:
raise SaltInvocationError(
'Invalid input for \'dnsservers\' parameter'
)
if searchdomains is None:
searchdomains = []
elif not isinstance(searchdomains, list):
try:
searchdomains = searchdomains.split(',')
except AttributeError:
raise SaltInvocationError(
'Invalid input for \'searchdomains\' parameter'
)
dns = ['nameserver {0}'.format(x) for x in dnsservers]
dns.extend(['search {0}'.format(x) for x in searchdomains])
dns = '\n'.join(dns) + '\n'
# we may be using resolvconf in the container
# We need to handle that case with care:
# - we create the resolv.conf runtime directory (the
# linked directory) as anyway it will be shadowed when the real
# runned tmpfs mountpoint will be mounted.
# ( /etc/resolv.conf -> ../run/resolvconf/resolv.conf)
# Indeed, it can save us in any other case (running, eg, in a
# bare chroot when repairing or preparing the container for
# operation.
# - We also teach resolvconf to use the aforementioned dns.
# - We finally also set /etc/resolv.conf in all cases
rstr = __salt__['test.random_hash']()
# no tmp here, apparmor won't let us execute !
script = '/sbin/{0}_dns.sh'.format(rstr)
DNS_SCRIPT = "\n".join([
# 'set -x',
'#!/usr/bin/env bash',
'if [ -h /etc/resolv.conf ];then',
' if [ "x$(readlink /etc/resolv.conf)"'
' = "x../run/resolvconf/resolv.conf" ];then',
' if [ ! -d /run/resolvconf/ ];then',
' mkdir -p /run/resolvconf',
' fi',
' cat > /etc/resolvconf/resolv.conf.d/head <<EOF',
dns,
'EOF',
'',
' fi',
'fi',
'cat > /etc/resolv.conf <<EOF',
dns,
'EOF',
''])
result = run_all(
name, 'tee {0}'.format(script), path=path,
stdin=DNS_SCRIPT, python_shell=True)
if result['retcode'] == 0:
result = run_all(
name, 'sh -c "chmod +x {0};{0}"'.format(script),
path=path, python_shell=True)
# blindly delete the setter file
run_all(name,
'sh -c \'if [ -f "{0}" ];then rm -f "{0}";fi\''.format(script),
path=path, python_shell=True)
if result['retcode'] != 0:
error = ('Unable to write to /etc/resolv.conf in container \'{0}\''
.format(name))
if result['stderr']:
error += ': {0}'.format(result['stderr'])
raise CommandExecutionError(error)
return True
def running_systemd(name, cache=True, path=None):
'''
Determine if systemD is running
path
path to the container parent
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.running_systemd ubuntu
'''
k = 'lxc.systemd.test.{0}{1}'.format(name, path)
ret = __context__.get(k, None)
if ret is None or not cache:
rstr = __salt__['test.random_hash']()
# no tmp here, apparmor won't let us execute !
script = '/sbin/{0}_testsystemd.sh'.format(rstr)
# ubuntu already had since trusty some bits of systemd but was
# still using upstart ...
# we need to be a bit more careful that just testing that systemd
# is present
_script = textwrap.dedent(
'''\
#!/usr/bin/env bash
set -x
if ! command -v systemctl 1>/dev/null 2>/dev/null;then exit 2;fi
for i in \\
/run/systemd/journal/dev-log\\
/run/systemd/journal/flushed\\
/run/systemd/journal/kernel-seqnum\\
/run/systemd/journal/socket\\
/run/systemd/journal/stdout\\
/var/run/systemd/journal/dev-log\\
/var/run/systemd/journal/flushed\\
/var/run/systemd/journal/kernel-seqnum\\
/var/run/systemd/journal/socket\\
/var/run/systemd/journal/stdout\\
;do\\
if test -e ${i};then exit 0;fi
done
if test -d /var/systemd/system;then exit 0;fi
exit 2
''')
result = run_all(
name, 'tee {0}'.format(script), path=path,
stdin=_script, python_shell=True)
if result['retcode'] == 0:
result = run_all(name,
'sh -c "chmod +x {0};{0}"'''.format(script),
path=path,
python_shell=True)
else:
raise CommandExecutionError(
'lxc {0} failed to copy initd tester'.format(name))
run_all(name,
'sh -c \'if [ -f "{0}" ];then rm -f "{0}";fi\''
''.format(script),
path=path,
ignore_retcode=True,
python_shell=True)
if result['retcode'] != 0:
error = ('Unable to determine if the container \'{0}\''
' was running systemd, assmuming it is not.'
''.format(name))
if result['stderr']:
error += ': {0}'.format(result['stderr'])
# only cache result if we got a known exit code
if result['retcode'] in (0, 2):
__context__[k] = ret = not result['retcode']
return ret
def systemd_running_state(name, path=None):
'''
Get the operational state of a systemd based container
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.systemd_running_state ubuntu
'''
try:
ret = run_all(name,
'systemctl is-system-running',
path=path,
ignore_retcode=True)['stdout']
except CommandExecutionError:
ret = ''
return ret
def test_sd_started_state(name, path=None):
'''
Test if a systemd container is fully started
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.test_sd_started_state ubuntu
'''
qstate = systemd_running_state(name, path=path)
if qstate in ('initializing', 'starting'):
return False
elif qstate == '':
return None
else:
return True
def test_bare_started_state(name, path=None):
'''
Test if a non systemd container is fully started
For now, it consists only to test if the container is attachable
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.test_bare_started_state ubuntu
'''
try:
ret = run_all(
name, 'ls', path=path, ignore_retcode=True
)['retcode'] == 0
except (CommandExecutionError,):
ret = None
return ret
def wait_started(name, path=None, timeout=300):
'''
Check that the system has fully inited
This is actually very important for systemD based containers
see https://github.com/saltstack/salt/issues/23847
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.wait_started ubuntu
'''
if not exists(name, path=path):
raise CommandExecutionError(
'Container {0} does does exists'.format(name))
if not state(name, path=path) == 'running':
raise CommandExecutionError(
'Container {0} is not running'.format(name))
ret = False
if running_systemd(name, path=path):
test_started = test_sd_started_state
logger = log.error
else:
test_started = test_bare_started_state
logger = log.debug
now = time.time()
expire = now + timeout
now = time.time()
started = test_started(name, path=path)
while time.time() < expire and not started:
time.sleep(0.3)
started = test_started(name, path=path)
if started is None:
logger(
'Assuming %s is started, although we failed to detect that'
' is fully started correctly', name)
ret = True
else:
ret = started
return ret
def _needs_install(name, path=None):
ret = 0
has_minion = retcode(name,
'which salt-minion',
path=path,
ignore_retcode=True)
# we assume that installing is when no minion is running
# but testing the executable presence is not enougth for custom
# installs where the bootstrap can do much more than installing
# the bare salt binaries.
if has_minion:
processes = run_stdout(name, "ps aux", path=path)
if 'salt-minion' not in processes:
ret = 1
else:
retcode(name, 'salt-call --local service.stop salt-minion')
else:
ret = 1
return ret
def bootstrap(name,
config=None,
approve_key=True,
install=True,
pub_key=None,
priv_key=None,
bootstrap_url=None,
force_install=False,
unconditional_install=False,
path=None,
bootstrap_delay=None,
bootstrap_args=None,
bootstrap_shell=None):
'''
Install and configure salt in a container.
config
Minion configuration options. By default, the ``master`` option is set
to the target host's master.
approve_key
Request a pre-approval of the generated minion key. Requires
that the salt-master be configured to either auto-accept all keys or
expect a signing request from the target host. Default: ``True``
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
pub_key
Explicit public key to pressed the minion with (optional).
This can be either a filepath or a string representing the key
priv_key
Explicit private key to pressed the minion with (optional).
This can be either a filepath or a string representing the key
bootstrap_delay
Delay in seconds between end of container creation and bootstrapping.
Useful when waiting for container to obtain a DHCP lease.
.. versionadded:: 2015.5.0
bootstrap_url
url, content or filepath to the salt bootstrap script
bootstrap_args
salt bootstrap script arguments
bootstrap_shell
shell to execute the script into
install
Whether to attempt a full installation of salt-minion if needed.
force_install
Force installation even if salt-minion is detected,
this is the way to run vendor bootstrap scripts even
if a salt minion is already present in the container
unconditional_install
Run the script even if the container seems seeded
CLI Examples:
.. code-block:: bash
salt 'minion' lxc.bootstrap container_name [config=config_data] \\
[approve_key=(True|False)] [install=(True|False)]
'''
wait_started(name, path=path)
if bootstrap_delay is not None:
try:
log.info('LXC %s: bootstrap_delay: %s', name, bootstrap_delay)
time.sleep(bootstrap_delay)
except TypeError:
# Bad input, but assume since a value was passed that
# a delay was desired, and sleep for 5 seconds
time.sleep(5)
c_info = info(name, path=path)
if not c_info:
return None
# default set here as we cannot set them
# in def as it can come from a chain of procedures.
if bootstrap_args:
# custom bootstrap args can be totally customized, and user could
# have inserted the placeholder for the config directory.
# For example, some salt bootstrap script do not use at all -c
if '{0}' not in bootstrap_args:
bootstrap_args += ' -c {0}'
else:
bootstrap_args = '-c {0}'
if not bootstrap_shell:
bootstrap_shell = 'sh'
orig_state = _ensure_running(name, path=path)
if not orig_state:
return orig_state
if not force_install:
needs_install = _needs_install(name, path=path)
else:
needs_install = True
seeded = retcode(name,
'test -e \'{0}\''.format(SEED_MARKER),
path=path,
chroot_fallback=True,
ignore_retcode=True) == 0
tmp = tempfile.mkdtemp()
if seeded and not unconditional_install:
ret = True
else:
ret = False
cfg_files = __salt__['seed.mkconfig'](
config, tmp=tmp, id_=name, approve_key=approve_key,
pub_key=pub_key, priv_key=priv_key)
if needs_install or force_install or unconditional_install:
if install:
rstr = __salt__['test.random_hash']()
configdir = '/var/tmp/.c_{0}'.format(rstr)
cmd = 'install -m 0700 -d {0}'.format(configdir)
if run_all(
name, cmd, path=path, python_shell=False
)['retcode'] != 0:
log.error('tmpdir %s creation failed %s', configdir, cmd)
return False
bs_ = __salt__['config.gather_bootstrap_script'](
bootstrap=bootstrap_url)
script = '/sbin/{0}_bootstrap.sh'.format(rstr)
copy_to(name, bs_, script, path=path)
result = run_all(name,
'sh -c "chmod +x {0}"'.format(script),
path=path,
python_shell=True)
copy_to(name, cfg_files['config'],
os.path.join(configdir, 'minion'),
path=path)
copy_to(name, cfg_files['privkey'],
os.path.join(configdir, 'minion.pem'),
path=path)
copy_to(name, cfg_files['pubkey'],
os.path.join(configdir, 'minion.pub'),
path=path)
bootstrap_args = bootstrap_args.format(configdir)
cmd = ('{0} {2} {1}'
.format(bootstrap_shell,
bootstrap_args.replace("'", "''"),
script))
# log ASAP the forged bootstrap command which can be wrapped
# out of the output in case of unexpected problem
log.info('Running %s in LXC container \'%s\'', cmd, name)
ret = retcode(name, cmd, output_loglevel='info',
path=path, use_vt=True) == 0
run_all(name,
'sh -c \'if [ -f "{0}" ];then rm -f "{0}";fi\''
''.format(script),
path=path,
ignore_retcode=True,
python_shell=True)
else:
ret = False
else:
minion_config = salt.config.minion_config(cfg_files['config'])
pki_dir = minion_config['pki_dir']
copy_to(name,
cfg_files['config'],
'/etc/salt/minion',
path=path)
copy_to(name,
cfg_files['privkey'],
os.path.join(pki_dir, 'minion.pem'),
path=path)
copy_to(name,
cfg_files['pubkey'],
os.path.join(pki_dir, 'minion.pub'),
path=path)
run(name,
'salt-call --local service.enable salt-minion',
path=path,
python_shell=False)
ret = True
shutil.rmtree(tmp)
if orig_state == 'stopped':
stop(name, path=path)
elif orig_state == 'frozen':
freeze(name, path=path)
# mark seeded upon successful install
if ret:
run(name,
'touch \'{0}\''.format(SEED_MARKER),
path=path,
python_shell=False)
return ret
def attachable(name, path=None):
'''
Return True if the named container can be attached to via the lxc-attach
command
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt 'minion' lxc.attachable ubuntu
'''
cachekey = 'lxc.attachable{0}{1}'.format(name, path)
try:
return __context__[cachekey]
except KeyError:
_ensure_exists(name, path=path)
# Can't use run() here because it uses attachable() and would
# endlessly recurse, resulting in a traceback
log.debug('Checking if LXC container %s is attachable', name)
cmd = 'lxc-attach'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' --clear-env -n {0} -- /usr/bin/env'.format(name)
result = __salt__['cmd.retcode'](cmd,
python_shell=False,
output_loglevel='quiet',
ignore_retcode=True) == 0
__context__[cachekey] = result
return __context__[cachekey]
def _run(name,
cmd,
output=None,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=None,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
Common logic for lxc.run functions
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
'''
orig_state = state(name, path=path)
try:
if attachable(name, path=path):
ret = __salt__['container_resource.run'](
name,
cmd,
path=path,
container_type=__virtualname__,
exec_driver=EXEC_DRIVER,
output=output,
no_start=no_start,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
ignore_retcode=ignore_retcode,
use_vt=use_vt,
keep_env=keep_env)
else:
if not chroot_fallback:
raise CommandExecutionError(
'{0} is not attachable.'.format(name))
rootfs = info(name, path=path).get('rootfs')
# Set context var to make cmd.run_chroot run cmd.run instead of
# cmd.run_all.
__context__['cmd.run_chroot.func'] = __salt__['cmd.run']
ret = __salt__['cmd.run_chroot'](rootfs,
cmd,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
ignore_retcode=ignore_retcode)
except Exception:
raise
finally:
# Make sure we honor preserve_state, even if there was an exception
new_state = state(name, path=path)
if preserve_state:
if orig_state == 'stopped' and new_state != 'stopped':
stop(name, path=path)
elif orig_state == 'frozen' and new_state != 'frozen':
freeze(name, start=True, path=path)
if output in (None, 'all'):
return ret
else:
return ret[output]
def run(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.8.0
Run :mod:`cmd.run <salt.modules.cmdmod.run>` within a container
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed in stderr if the command being run
does not exist. If no output is returned using this function, try using
:mod:`lxc.run_stderr <salt.modules.lxc.run_stderr>` or
:mod:`lxc.run_all <salt.modules.lxc.run_all>`.
name
Name of the container in which to run the command
cmd
Command to run
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console. Assumes
``output=all``.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
CLI Example:
.. code-block:: bash
salt myminion lxc.run mycontainer 'ifconfig -a'
'''
return _run(name,
cmd,
path=path,
output=None,
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def run_stdout(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.5.0
Run :mod:`cmd.run_stdout <salt.modules.cmdmod.run_stdout>` within a container
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed in stderr if the command being run
does not exist. If no output is returned using this function, try using
:mod:`lxc.run_stderr <salt.modules.lxc.run_stderr>` or
:mod:`lxc.run_all <salt.modules.lxc.run_all>`.
name
Name of the container in which to run the command
cmd
Command to run
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console
``output=all``.
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
CLI Example:
.. code-block:: bash
salt myminion lxc.run_stdout mycontainer 'ifconfig -a'
'''
return _run(name,
cmd,
path=path,
output='stdout',
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def run_stderr(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.5.0
Run :mod:`cmd.run_stderr <salt.modules.cmdmod.run_stderr>` within a container
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed if the command being run does not
exist.
name
Name of the container in which to run the command
cmd
Command to run
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console
``output=all``.
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
CLI Example:
.. code-block:: bash
salt myminion lxc.run_stderr mycontainer 'ip addr show'
'''
return _run(name,
cmd,
path=path,
output='stderr',
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def retcode(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.5.0
Run :mod:`cmd.retcode <salt.modules.cmdmod.retcode>` within a container
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed in stderr if the command being run
does not exist. If the retcode is nonzero and not what was expected,
try using :mod:`lxc.run_stderr <salt.modules.lxc.run_stderr>`
or :mod:`lxc.run_all <salt.modules.lxc.run_all>`.
name
Name of the container in which to run the command
cmd
Command to run
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console
``output=all``.
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
CLI Example:
.. code-block:: bash
salt myminion lxc.retcode mycontainer 'ip addr show'
'''
return _run(name,
cmd,
output='retcode',
path=path,
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def run_all(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.5.0
Run :mod:`cmd.run_all <salt.modules.cmdmod.run_all>` within a container
.. note::
While the command is run within the container, it is initiated from the
host. Therefore, the PID in the return dict is from the host, not from
the container.
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed in stderr if the command being run
does not exist.
name
Name of the container in which to run the command
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
cmd
Command to run
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console
``output=all``.
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
CLI Example:
.. code-block:: bash
salt myminion lxc.run_all mycontainer 'ip addr show'
'''
return _run(name,
cmd,
output='all',
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
path=path,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def _get_md5(name, path):
'''
Get the MD5 checksum of a file from a container
'''
output = run_stdout(name, 'md5sum "{0}"'.format(path),
chroot_fallback=True,
ignore_retcode=True)
try:
return output.split()[0]
except IndexError:
# Destination file does not exist or could not be accessed
return None
def copy_to(name, source, dest, overwrite=False, makedirs=False, path=None):
'''
.. versionchanged:: 2015.8.0
Function renamed from ``lxc.cp`` to ``lxc.copy_to`` for consistency
with other container types. ``lxc.cp`` will continue to work, however.
For versions 2015.2.x and earlier, use ``lxc.cp``.
Copy a file or directory from the host into a container
name
Container name
source
File to be copied to the container
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
dest
Destination on the container. Must be an absolute path.
.. versionchanged:: 2015.5.0
If the destination is a directory, the file will be copied into
that directory.
overwrite : False
Unless this option is set to ``True``, then if a file exists at the
location specified by the ``dest`` argument, an error will be raised.
.. versionadded:: 2015.8.0
makedirs : False
Create the parent directory on the container if it does not already
exist.
.. versionadded:: 2015.5.0
CLI Example:
.. code-block:: bash
salt 'minion' lxc.copy_to /tmp/foo /root/foo
salt 'minion' lxc.cp /tmp/foo /root/foo
'''
_ensure_running(name, no_start=True, path=path)
return __salt__['container_resource.copy_to'](
name,
source,
dest,
container_type=__virtualname__,
path=path,
exec_driver=EXEC_DRIVER,
overwrite=overwrite,
makedirs=makedirs)
cp = salt.utils.functools.alias_function(copy_to, 'cp')
def read_conf(conf_file, out_format='simple'):
'''
Read in an LXC configuration file. By default returns a simple, unsorted
dict, but can also return a more detailed structure including blank lines
and comments.
out_format:
set to 'simple' if you need the old and unsupported behavior.
This won't support the multiple lxc values (eg: multiple network nics)
CLI Examples:
.. code-block:: bash
salt 'minion' lxc.read_conf /etc/lxc/mycontainer.conf
salt 'minion' lxc.read_conf /etc/lxc/mycontainer.conf out_format=commented
'''
ret_commented = []
ret_simple = {}
with salt.utils.files.fopen(conf_file, 'r') as fp_:
for line in salt.utils.data.decode(fp_.readlines()):
if '=' not in line:
ret_commented.append(line)
continue
comps = line.split('=')
value = '='.join(comps[1:]).strip()
comment = None
if value.strip().startswith('#'):
vcomps = value.strip().split('#')
value = vcomps[1].strip()
comment = '#'.join(vcomps[1:]).strip()
ret_commented.append({comps[0].strip(): {
'value': value,
'comment': comment,
}})
else:
ret_commented.append({comps[0].strip(): value})
ret_simple[comps[0].strip()] = value
if out_format == 'simple':
return ret_simple
return ret_commented
def write_conf(conf_file, conf):
'''
Write out an LXC configuration file
This is normally only used internally. The format of the data structure
must match that which is returned from ``lxc.read_conf()``, with
``out_format`` set to ``commented``.
An example might look like:
.. code-block:: python
[
{'lxc.utsname': '$CONTAINER_NAME'},
'# This is a commented line\\n',
'\\n',
{'lxc.mount': '$CONTAINER_FSTAB'},
{'lxc.rootfs': {'comment': 'This is another test',
'value': 'This is another test'}},
'\\n',
{'lxc.network.type': 'veth'},
{'lxc.network.flags': 'up'},
{'lxc.network.link': 'br0'},
{'lxc.network.mac': '$CONTAINER_MACADDR'},
{'lxc.network.ipv4': '$CONTAINER_IPADDR'},
{'lxc.network.name': '$CONTAINER_DEVICENAME'},
]
CLI Example:
.. code-block:: bash
salt 'minion' lxc.write_conf /etc/lxc/mycontainer.conf \\
out_format=commented
'''
if not isinstance(conf, list):
raise SaltInvocationError('Configuration must be passed as a list')
# construct the content prior to write to the file
# to avoid half written configs
content = ''
for line in conf:
if isinstance(line, (six.text_type, six.string_types)):
content += line
elif isinstance(line, dict):
for key in list(line.keys()):
out_line = None
if isinstance(
line[key],
(six.text_type, six.string_types, six.integer_types, float)
):
out_line = ' = '.join((key, "{0}".format(line[key])))
elif isinstance(line[key], dict):
out_line = ' = '.join((key, line[key]['value']))
if 'comment' in line[key]:
out_line = ' # '.join((out_line, line[key]['comment']))
if out_line:
content += out_line
content += '\n'
with salt.utils.files.fopen(conf_file, 'w') as fp_:
fp_.write(salt.utils.stringutils.to_str(content))
return {}
def edit_conf(conf_file,
out_format='simple',
read_only=False,
lxc_config=None,
**kwargs):
'''
Edit an LXC configuration file. If a setting is already present inside the
file, its value will be replaced. If it does not exist, it will be appended
to the end of the file. Comments and blank lines will be kept in-tact if
they already exist in the file.
out_format:
Set to simple if you need backward compatibility (multiple items for a
simple key is not supported)
read_only:
return only the edited configuration without applying it
to the underlying lxc configuration file
lxc_config:
List of dict containning lxc configuration items
For network configuration, you also need to add the device it belongs
to, otherwise it will default to eth0.
Also, any change to a network parameter will result in the whole
network reconfiguration to avoid mismatchs, be aware of that !
After the file is edited, its contents will be returned. By default, it
will be returned in ``simple`` format, meaning an unordered dict (which
may not represent the actual file order). Passing in an ``out_format`` of
``commented`` will return a data structure which accurately represents the
order and content of the file.
CLI Example:
.. code-block:: bash
salt 'minion' lxc.edit_conf /etc/lxc/mycontainer.conf \\
out_format=commented lxc.network.type=veth
salt 'minion' lxc.edit_conf /etc/lxc/mycontainer.conf \\
out_format=commented \\
lxc_config="[{'lxc.network.name': 'eth0', \\
'lxc.network.ipv4': '1.2.3.4'},
{'lxc.network.name': 'eth2', \\
'lxc.network.ipv4': '1.2.3.5',\\
'lxc.network.gateway': '1.2.3.1'}]"
'''
data = []
try:
conf = read_conf(conf_file, out_format=out_format)
except Exception:
conf = []
if not lxc_config:
lxc_config = []
lxc_config = copy.deepcopy(lxc_config)
# search if we want to access net config
# in that case, we will replace all the net configuration
net_config = []
for lxc_kws in lxc_config + [kwargs]:
net_params = {}
for kwarg in [a for a in lxc_kws]:
if kwarg.startswith('__'):
continue
if kwarg.startswith('lxc.network.'):
net_params[kwarg] = lxc_kws[kwarg]
lxc_kws.pop(kwarg, None)
if net_params:
net_config.append(net_params)
nic_opts = salt.utils.odict.OrderedDict()
for params in net_config:
dev = params.get('lxc.network.name', DEFAULT_NIC)
dev_opts = nic_opts.setdefault(dev, salt.utils.odict.OrderedDict())
for param in params:
opt = param.replace('lxc.network.', '')
opt = {'hwaddr': 'mac'}.get(opt, opt)
dev_opts[opt] = params[param]
net_changes = []
if nic_opts:
net_changes = _config_list(conf, only_net=True,
**{'network_profile': DEFAULT_NIC,
'nic_opts': nic_opts})
if net_changes:
lxc_config.extend(net_changes)
for line in conf:
if not isinstance(line, dict):
data.append(line)
continue
else:
for key in list(line.keys()):
val = line[key]
if net_changes and key.startswith('lxc.network.'):
continue
found = False
for ix in range(len(lxc_config)):
kw = lxc_config[ix]
if key in kw:
found = True
data.append({key: kw[key]})
del kw[key]
if not found:
data.append({key: val})
for lxc_kws in lxc_config:
for kwarg in lxc_kws:
data.append({kwarg: lxc_kws[kwarg]})
if read_only:
return data
write_conf(conf_file, data)
return read_conf(conf_file, out_format)
def reboot(name, path=None):
'''
Reboot a container.
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Examples:
.. code-block:: bash
salt 'minion' lxc.reboot myvm
'''
ret = {'result': True,
'changes': {},
'comment': '{0} rebooted'.format(name)}
does_exist = exists(name, path=path)
if does_exist and (state(name, path=path) == 'running'):
try:
stop(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
ret['result'] = False
return ret
if does_exist and (state(name, path=path) != 'running'):
try:
start(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
ret['result'] = False
return ret
ret['changes'][name] = 'rebooted'
return ret
def reconfigure(name,
cpu=None,
cpuset=None,
cpushare=None,
memory=None,
profile=None,
network_profile=None,
nic_opts=None,
bridge=None,
gateway=None,
autostart=None,
utsname=None,
rootfs=None,
path=None,
**kwargs):
'''
Reconfigure a container.
This only applies to a few property
name
Name of the container.
utsname
utsname of the container.
.. versionadded:: 2016.3.0
rootfs
rootfs of the container.
.. versionadded:: 2016.3.0
cpu
Select a random number of cpu cores and assign it to the cpuset, if the
cpuset option is set then this option will be ignored
cpuset
Explicitly define the cpus this container will be bound to
cpushare
cgroups cpu shares.
autostart
autostart container on reboot
memory
cgroups memory limit, in MB.
(0 for nolimit, None for old default 1024MB)
gateway
the ipv4 gateway to use
the default does nothing more than lxcutils does
bridge
the bridge to use
the default does nothing more than lxcutils does
nic
Network interfaces profile (defined in config or pillar).
nic_opts
Extra options for network interfaces, will override
``{"eth0": {"mac": "aa:bb:cc:dd:ee:ff", "ipv4": "10.1.1.1", "ipv6": "2001:db8::ff00:42:8329"}}``
or
``{"eth0": {"mac": "aa:bb:cc:dd:ee:ff", "ipv4": "10.1.1.1/24", "ipv6": "2001:db8::ff00:42:8329"}}``
path
path to the container parent
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt-call -lall mc_lxc_fork.reconfigure foobar nic_opts="{'eth1': {'mac': '00:16:3e:dd:ee:44'}}" memory=4
'''
changes = {}
cpath = get_root_path(path)
path = os.path.join(cpath, name, 'config')
ret = {'name': name,
'comment': 'config for {0} up to date'.format(name),
'result': True,
'changes': changes}
profile = get_container_profile(copy.deepcopy(profile))
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, _marker)
profile_match = profile.pop(key, default)
# let kwarg overrides be the preferred choice
if kw_overrides_match is _marker:
return profile_match
return kw_overrides_match
if nic_opts is not None and not network_profile:
network_profile = DEFAULT_NIC
if autostart is not None:
autostart = select('autostart', autostart)
else:
autostart = 'keep'
if not utsname:
utsname = select('utsname', utsname)
if os.path.exists(path):
old_chunks = read_conf(path, out_format='commented')
make_kw = salt.utils.odict.OrderedDict([
('utsname', utsname),
('rootfs', rootfs),
('autostart', autostart),
('cpu', cpu),
('gateway', gateway),
('cpuset', cpuset),
('cpushare', cpushare),
('network_profile', network_profile),
('nic_opts', nic_opts),
('bridge', bridge)])
# match 0 and none as memory = 0 in lxc config is harmful
if memory:
make_kw['memory'] = memory
kw = salt.utils.odict.OrderedDict()
for key, val in six.iteritems(make_kw):
if val is not None:
kw[key] = val
new_cfg = _config_list(conf_tuples=old_chunks, **kw)
if new_cfg:
edit_conf(path, out_format='commented', lxc_config=new_cfg)
chunks = read_conf(path, out_format='commented')
if old_chunks != chunks:
ret['comment'] = '{0} lxc config updated'.format(name)
if state(name, path=path) == 'running':
cret = reboot(name, path=path)
ret['result'] = cret['result']
return ret
def apply_network_profile(name, network_profile, nic_opts=None, path=None):
'''
.. versionadded:: 2015.5.0
Apply a network profile to a container
network_profile
profile name or default values (dict)
nic_opts
values to override in defaults (dict)
indexed by nic card names
path
path to the container parent
.. versionadded:: 2015.8.0
CLI Examples:
.. code-block:: bash
salt 'minion' lxc.apply_network_profile web1 centos
salt 'minion' lxc.apply_network_profile web1 centos \\
nic_opts="{'eth0': {'mac': 'xx:xx:xx:xx:xx:xx'}}"
salt 'minion' lxc.apply_network_profile web1 \\
"{'eth0': {'mac': 'xx:xx:xx:xx:xx:yy'}}"
nic_opts="{'eth0': {'mac': 'xx:xx:xx:xx:xx:xx'}}"
The special case to disable use of ethernet nics:
.. code-block:: bash
salt 'minion' lxc.apply_network_profile web1 centos \\
"{eth0: {disable: true}}"
'''
cpath = get_root_path(path)
cfgpath = os.path.join(cpath, name, 'config')
before = []
with salt.utils.files.fopen(cfgpath, 'r') as fp_:
for line in fp_:
before.append(line)
lxcconfig = _LXCConfig(name=name, path=path)
old_net = lxcconfig._filter_data('lxc.network')
network_params = {}
for param in _network_conf(
conf_tuples=old_net,
network_profile=network_profile, nic_opts=nic_opts
):
network_params.update(param)
if network_params:
edit_conf(cfgpath, out_format='commented', **network_params)
after = []
with salt.utils.files.fopen(cfgpath, 'r') as fp_:
for line in fp_:
after.append(line)
diff = ''
for line in difflib.unified_diff(before,
after,
fromfile='before',
tofile='after'):
diff += line
return diff
def get_pid(name, path=None):
'''
Returns a container pid.
Throw an exception if the container isn't running.
CLI Example:
.. code-block:: bash
salt '*' lxc.get_pid name
'''
if name not in list_(limit='running', path=path):
raise CommandExecutionError('Container {0} is not running, can\'t determine PID'.format(name))
info = __salt__['cmd.run']('lxc-info -n {0}'.format(name)).split("\n")
pid = [line.split(':')[1].strip() for line in info if re.match(r'\s*PID', line)][0]
return pid
def add_veth(name, interface_name, bridge=None, path=None):
'''
Add a veth to a container.
Note : this function doesn't update the container config, just add the interface at runtime
name
Name of the container
interface_name
Name of the interface in the container
bridge
Name of the bridge to attach the interface to (facultative)
CLI Examples:
.. code-block:: bash
salt '*' lxc.add_veth container_name eth1 br1
salt '*' lxc.add_veth container_name eth1
'''
# Get container init PID
pid = get_pid(name, path=path)
# Generate a ramdom string for veth and ensure that is isn't present on the system
while True:
random_veth = 'veth'+''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(6))
if random_veth not in __salt__['network.interfaces']().keys():
break
# Check prerequisites
if not __salt__['file.directory_exists']('/var/run/'):
raise CommandExecutionError('Directory /var/run required for lxc.add_veth doesn\'t exists')
if not __salt__['file.file_exists']('/proc/{0}/ns/net'.format(pid)):
raise CommandExecutionError('Proc file for container {0} network namespace doesn\'t exists'.format(name))
if not __salt__['file.directory_exists']('/var/run/netns'):
__salt__['file.mkdir']('/var/run/netns')
# Ensure that the symlink is up to date (change on container restart)
if __salt__['file.is_link']('/var/run/netns/{0}'.format(name)):
__salt__['file.remove']('/var/run/netns/{0}'.format(name))
__salt__['file.symlink']('/proc/{0}/ns/net'.format(pid), '/var/run/netns/{0}'.format(name))
# Ensure that interface doesn't exists
interface_exists = 0 == __salt__['cmd.retcode']('ip netns exec {netns} ip address list {interface}'.format(
netns=name,
interface=interface_name
))
if interface_exists:
raise CommandExecutionError('Interface {interface} already exists in {container}'.format(
interface=interface_name,
container=name
))
# Create veth and bring it up
if __salt__['cmd.retcode']('ip link add name {veth} type veth peer name {veth}_c'.format(veth=random_veth)) != 0:
raise CommandExecutionError('Error while creating the veth pair {0}'.format(random_veth))
if __salt__['cmd.retcode']('ip link set dev {0} up'.format(random_veth)) != 0:
raise CommandExecutionError('Error while bringing up host-side veth {0}'.format(random_veth))
# Attach it to the container
attached = 0 == __salt__['cmd.retcode']('ip link set dev {veth}_c netns {container} name {interface_name}'.format(
veth=random_veth,
container=name,
interface_name=interface_name
))
if not attached:
raise CommandExecutionError('Error while attaching the veth {veth} to container {container}'.format(
veth=random_veth,
container=name
))
__salt__['file.remove']('/var/run/netns/{0}'.format(name))
if bridge is not None:
__salt__['bridge.addif'](bridge, random_veth)
|
saltstack/salt
|
salt/modules/lxc.py
|
ls_
|
python
|
def ls_(active=None, cache=True, path=None):
'''
Return a list of the containers available on the minion
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
active
If ``True``, return only active (i.e. running) containers
.. versionadded:: 2015.5.0
CLI Example:
.. code-block:: bash
salt '*' lxc.ls
salt '*' lxc.ls active=True
'''
contextvar = 'lxc.ls{0}'.format(path)
if active:
contextvar += '.active'
if cache and (contextvar in __context__):
return __context__[contextvar]
else:
ret = []
cmd = 'lxc-ls'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
if active:
cmd += ' --active'
output = __salt__['cmd.run_stdout'](cmd, python_shell=False)
for line in output.splitlines():
ret.extend(line.split())
__context__[contextvar] = ret
return ret
|
Return a list of the containers available on the minion
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
active
If ``True``, return only active (i.e. running) containers
.. versionadded:: 2015.5.0
CLI Example:
.. code-block:: bash
salt '*' lxc.ls
salt '*' lxc.ls active=True
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/lxc.py#L2109-L2147
| null |
# -*- coding: utf-8 -*-
'''
Control Linux Containers via Salt
:depends: lxc package for distribution
lxc >= 1.0 (even beta alpha) is required
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import datetime
import copy
import string
import textwrap
import difflib
import logging
import tempfile
import os
import pipes
import time
import shutil
import re
import random
# Import salt libs
import salt.utils.args
import salt.utils.cloud
import salt.utils.data
import salt.utils.dictupdate
import salt.utils.files
import salt.utils.functools
import salt.utils.hashutils
import salt.utils.network
import salt.utils.odict
import salt.utils.path
import salt.utils.stringutils
from salt.exceptions import CommandExecutionError, SaltInvocationError
import salt.config
from salt.utils.versions import LooseVersion as _LooseVersion
# Import 3rd-party libs
from salt.ext import six
# pylint: disable=import-error,no-name-in-module
from salt.ext.six.moves import range # pylint: disable=redefined-builtin
from salt.ext.six.moves.urllib.parse import urlparse as _urlparse
# pylint: enable=import-error,no-name-in-module
# Set up logging
log = logging.getLogger(__name__)
# Don't shadow built-in's.
__func_alias__ = {
'list_': 'list',
'ls_': 'ls'
}
__virtualname__ = 'lxc'
DEFAULT_NIC = 'eth0'
DEFAULT_BR = 'br0'
SEED_MARKER = '/lxc.initial_seed'
EXEC_DRIVER = 'lxc-attach'
DEFAULT_PATH = '/var/lib/lxc'
_marker = object()
def __virtual__():
if salt.utils.path.which('lxc-start'):
return __virtualname__
# To speed up the whole thing, we decided to not use the
# subshell way and assume things are in place for lxc
# Discussion made by @kiorky and @thatch45
# lxc-version presence is not sufficient, in lxc1.0 alpha
# (precise backports), we have it and it is sufficient
# for the module to execute.
# elif salt.utils.path.which('lxc-version'):
# passed = False
# try:
# passed = subprocess.check_output(
# 'lxc-version').split(':')[1].strip() >= '1.0'
# except Exception:
# pass
# if not passed:
# log.warning('Support for lxc < 1.0 may be incomplete.')
# return 'lxc'
# return False
#
return (False, 'The lxc execution module cannot be loaded: the lxc-start binary is not in the path.')
def get_root_path(path):
'''
Get the configured lxc root for containers
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.get_root_path
'''
if not path:
path = __opts__.get('lxc.root_path', DEFAULT_PATH)
return path
def version():
'''
Return the actual lxc client version
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.version
'''
k = 'lxc.version'
if not __context__.get(k, None):
cversion = __salt__['cmd.run_all']('lxc-info --version')
if not cversion['retcode']:
ver = _LooseVersion(cversion['stdout'])
if ver < _LooseVersion('1.0'):
raise CommandExecutionError('LXC should be at least 1.0')
__context__[k] = "{0}".format(ver)
return __context__.get(k, None)
def _clear_context():
'''
Clear any lxc variables set in __context__
'''
for var in [x for x in __context__ if x.startswith('lxc.')]:
log.trace('Clearing __context__[\'%s\']', var)
__context__.pop(var, None)
def _ip_sort(ip):
'''Ip sorting'''
idx = '001'
if ip == '127.0.0.1':
idx = '200'
if ip == '::1':
idx = '201'
elif '::' in ip:
idx = '100'
return '{0}___{1}'.format(idx, ip)
def search_lxc_bridges():
'''
Search which bridges are potentially available as LXC bridges
CLI Example:
.. code-block:: bash
salt '*' lxc.search_lxc_bridges
'''
bridges = __context__.get('lxc.bridges', None)
# either match not yet called or no bridges were found
# to handle the case where lxc was not installed on the first
# call
if not bridges:
bridges = set()
running_bridges = set()
bridges.add(DEFAULT_BR)
try:
output = __salt__['cmd.run_all']('brctl show')
for line in output['stdout'].splitlines()[1:]:
if not line.startswith(' '):
running_bridges.add(line.split()[0].strip())
except (SaltInvocationError, CommandExecutionError):
pass
for ifc, ip in six.iteritems(
__grains__.get('ip_interfaces', {})
):
if ifc in running_bridges:
bridges.add(ifc)
elif os.path.exists(
'/sys/devices/virtual/net/{0}/bridge'.format(ifc)
):
bridges.add(ifc)
bridges = list(bridges)
# if we found interfaces that have lxc in their names
# we filter them as being the potential lxc bridges
# we also try to default on br0 on other cases
def sort_bridges(a):
pref = 'z'
if 'lxc' in a:
pref = 'a'
elif 'br0' == a:
pref = 'c'
return '{0}_{1}'.format(pref, a)
bridges.sort(key=sort_bridges)
__context__['lxc.bridges'] = bridges
return bridges
def search_lxc_bridge():
'''
Search the first bridge which is potentially available as LXC bridge
CLI Example:
.. code-block:: bash
salt '*' lxc.search_lxc_bridge
'''
return search_lxc_bridges()[0]
def _get_salt_config(config, **kwargs):
if not config:
config = kwargs.get('minion', {})
if not config:
config = {}
config.setdefault('master',
kwargs.get('master',
__opts__.get('master',
__opts__['id'])))
config.setdefault(
'master_port',
kwargs.get('master_port',
__opts__.get('master_port',
__opts__.get('ret_port',
__opts__.get('4506')))))
if not config['master']:
config = {}
return config
def cloud_init_interface(name, vm_=None, **kwargs):
'''
Interface between salt.cloud.lxc driver and lxc.init
``vm_`` is a mapping of vm opts in the salt.cloud format
as documented for the lxc driver.
This can be used either:
- from the salt cloud driver
- because you find the argument to give easier here
than using directly lxc.init
.. warning::
BE REALLY CAREFUL CHANGING DEFAULTS !!!
IT'S A RETRO COMPATIBLE INTERFACE WITH
THE SALT CLOUD DRIVER (ask kiorky).
name
name of the lxc container to create
pub_key
public key to preseed the minion with.
Can be the keycontent or a filepath
priv_key
private key to preseed the minion with.
Can be the keycontent or a filepath
path
path to the container parent directory (default: /var/lib/lxc)
.. versionadded:: 2015.8.0
profile
:ref:`profile <tutorial-lxc-profiles-container>` selection
network_profile
:ref:`network profile <tutorial-lxc-profiles-network>` selection
nic_opts
per interface settings compatibles with
network profile (ipv4/ipv6/link/gateway/mac/netmask)
eg::
- {'eth0': {'mac': '00:16:3e:01:29:40',
'gateway': None, (default)
'link': 'br0', (default)
'gateway': None, (default)
'netmask': '', (default)
'ip': '22.1.4.25'}}
unconditional_install
given to lxc.bootstrap (see relative doc)
force_install
given to lxc.bootstrap (see relative doc)
config
any extra argument for the salt minion config
dnsservers
list of DNS servers to set inside the container
dns_via_dhcp
do not set the dns servers, let them be set by the dhcp.
autostart
autostart the container at boot time
password
administrative password for the container
bootstrap_delay
delay before launching bootstrap script at Container init
.. warning::
Legacy but still supported options:
from_container
which container we use as a template
when running lxc.clone
image
which template do we use when we
are using lxc.create. This is the default
mode unless you specify something in from_container
backing
which backing store to use.
Values can be: overlayfs, dir(default), lvm, zfs, brtfs
fstype
When using a blockdevice level backing store,
which filesystem to use on
size
When using a blockdevice level backing store,
which size for the filesystem to use on
snapshot
Use snapshot when cloning the container source
vgname
if using LVM: vgname
lvname
if using LVM: lvname
thinpool:
if using LVM: thinpool
ip
ip for the primary nic
mac
mac address for the primary nic
netmask
netmask for the primary nic (24)
= ``vm_.get('netmask', '24')``
bridge
bridge for the primary nic (lxcbr0)
gateway
network gateway for the container
additional_ips
additional ips which will be wired on the main bridge (br0)
which is connected to internet.
Be aware that you may use manual virtual mac addresses
providen by you provider (online, ovh, etc).
This is a list of mappings {ip: '', mac: '', netmask:''}
Set gateway to None and an interface with a gateway
to escape from another interface that eth0.
eg::
- {'mac': '00:16:3e:01:29:40',
'gateway': None, (default)
'link': 'br0', (default)
'netmask': '', (default)
'ip': '22.1.4.25'}
users
administrative users for the container
default: [root] and [root, ubuntu] on ubuntu
default_nic
name of the first interface, you should
really not override this
CLI Example:
.. code-block:: bash
salt '*' lxc.cloud_init_interface foo
'''
if vm_ is None:
vm_ = {}
vm_ = copy.deepcopy(vm_)
vm_ = salt.utils.dictupdate.update(vm_, kwargs)
profile_data = copy.deepcopy(
vm_.get('lxc_profile',
vm_.get('profile', {})))
if not isinstance(profile_data, (dict, six.string_types)):
profile_data = {}
profile = get_container_profile(profile_data)
def _cloud_get(k, default=None):
return vm_.get(k, profile.get(k, default))
if name is None:
name = vm_['name']
# if we are on ubuntu, default to ubuntu
default_template = ''
if __grains__.get('os', '') in ['Ubuntu']:
default_template = 'ubuntu'
image = _cloud_get('image')
if not image:
_cloud_get('template', default_template)
backing = _cloud_get('backing', 'dir')
if image:
profile['template'] = image
vgname = _cloud_get('vgname', None)
if vgname:
profile['vgname'] = vgname
if backing:
profile['backing'] = backing
snapshot = _cloud_get('snapshot', False)
autostart = bool(_cloud_get('autostart', True))
dnsservers = _cloud_get('dnsservers', [])
dns_via_dhcp = _cloud_get('dns_via_dhcp', True)
password = _cloud_get('password', 's3cr3t')
password_encrypted = _cloud_get('password_encrypted', False)
fstype = _cloud_get('fstype', None)
lvname = _cloud_get('lvname', None)
thinpool = _cloud_get('thinpool', None)
pub_key = _cloud_get('pub_key', None)
priv_key = _cloud_get('priv_key', None)
size = _cloud_get('size', '20G')
script = _cloud_get('script', None)
script_args = _cloud_get('script_args', None)
users = _cloud_get('users', None)
if users is None:
users = []
ssh_username = _cloud_get('ssh_username', None)
if ssh_username and (ssh_username not in users):
users.append(ssh_username)
network_profile = _cloud_get('network_profile', None)
nic_opts = kwargs.get('nic_opts', None)
netmask = _cloud_get('netmask', '24')
path = _cloud_get('path', None)
bridge = _cloud_get('bridge', None)
gateway = _cloud_get('gateway', None)
unconditional_install = _cloud_get('unconditional_install', False)
force_install = _cloud_get('force_install', True)
config = _get_salt_config(_cloud_get('config', {}), **vm_)
default_nic = _cloud_get('default_nic', DEFAULT_NIC)
# do the interface with lxc.init mainly via nic_opts
# to avoid extra and confusing extra use cases.
if not isinstance(nic_opts, dict):
nic_opts = salt.utils.odict.OrderedDict()
# have a reference to the default nic
eth0 = nic_opts.setdefault(default_nic,
salt.utils.odict.OrderedDict())
# lxc config is based of ifc order, be sure to use odicts.
if not isinstance(nic_opts, salt.utils.odict.OrderedDict):
bnic_opts = salt.utils.odict.OrderedDict()
bnic_opts.update(nic_opts)
nic_opts = bnic_opts
gw = None
# legacy salt.cloud scheme for network interfaces settings support
bridge = _cloud_get('bridge', None)
ip = _cloud_get('ip', None)
mac = _cloud_get('mac', None)
if ip:
fullip = ip
if netmask:
fullip += '/{0}'.format(netmask)
eth0['ipv4'] = fullip
if mac is not None:
eth0['mac'] = mac
for ix, iopts in enumerate(_cloud_get("additional_ips", [])):
ifh = "eth{0}".format(ix+1)
ethx = nic_opts.setdefault(ifh, {})
if gw is None:
gw = iopts.get('gateway', ethx.get('gateway', None))
if gw:
# only one and only one default gateway is allowed !
eth0.pop('gateway', None)
gateway = None
# even if the gateway if on default "eth0" nic
# and we popped it will work
# as we reinject or set it here.
ethx['gateway'] = gw
elink = iopts.get('link', ethx.get('link', None))
if elink:
ethx['link'] = elink
# allow dhcp
aip = iopts.get('ipv4', iopts.get('ip', None))
if aip:
ethx['ipv4'] = aip
nm = iopts.get('netmask', '')
if nm:
ethx['ipv4'] += '/{0}'.format(nm)
for i in ('mac', 'hwaddr'):
if i in iopts:
ethx['mac'] = iopts[i]
break
if 'mac' not in ethx:
ethx['mac'] = salt.utils.network.gen_mac()
# last round checking for unique gateway and such
gw = None
for ethx in [a for a in nic_opts]:
ndata = nic_opts[ethx]
if gw:
ndata.pop('gateway', None)
if 'gateway' in ndata:
gw = ndata['gateway']
gateway = None
# only use a default bridge / gateway if we configured them
# via the legacy salt cloud configuration style.
# On other cases, we should rely on settings provided by the new
# salt lxc network profile style configuration which can
# be also be overridden or a per interface basis via the nic_opts dict.
if bridge:
eth0['link'] = bridge
if gateway:
eth0['gateway'] = gateway
#
lxc_init_interface = {}
lxc_init_interface['name'] = name
lxc_init_interface['config'] = config
lxc_init_interface['memory'] = _cloud_get('memory', 0) # nolimit
lxc_init_interface['pub_key'] = pub_key
lxc_init_interface['priv_key'] = priv_key
lxc_init_interface['nic_opts'] = nic_opts
for clone_from in ['clone_from', 'clone', 'from_container']:
# clone_from should default to None if not available
lxc_init_interface['clone_from'] = _cloud_get(clone_from, None)
if lxc_init_interface['clone_from'] is not None:
break
lxc_init_interface['profile'] = profile
lxc_init_interface['snapshot'] = snapshot
lxc_init_interface['dnsservers'] = dnsservers
lxc_init_interface['fstype'] = fstype
lxc_init_interface['path'] = path
lxc_init_interface['vgname'] = vgname
lxc_init_interface['size'] = size
lxc_init_interface['lvname'] = lvname
lxc_init_interface['thinpool'] = thinpool
lxc_init_interface['force_install'] = force_install
lxc_init_interface['unconditional_install'] = (
unconditional_install
)
lxc_init_interface['bootstrap_url'] = script
lxc_init_interface['bootstrap_args'] = script_args
lxc_init_interface['bootstrap_shell'] = _cloud_get('bootstrap_shell', 'sh')
lxc_init_interface['bootstrap_delay'] = _cloud_get('bootstrap_delay', None)
lxc_init_interface['autostart'] = autostart
lxc_init_interface['users'] = users
lxc_init_interface['password'] = password
lxc_init_interface['password_encrypted'] = password_encrypted
# be sure not to let objects goes inside the return
# as this return will be msgpacked for use in the runner !
lxc_init_interface['network_profile'] = network_profile
for i in ['cpu', 'cpuset', 'cpushare']:
if _cloud_get(i, None):
try:
lxc_init_interface[i] = vm_[i]
except KeyError:
lxc_init_interface[i] = profile[i]
return lxc_init_interface
def _get_profile(key, name, **kwargs):
if isinstance(name, dict):
profilename = name.pop('name', None)
return _get_profile(key, profilename, **name)
if name is None:
profile_match = {}
else:
profile_match = \
__salt__['config.get'](
'lxc.{1}:{0}'.format(name, key),
default=None,
merge='recurse'
)
if profile_match is None:
# No matching profile, make the profile an empty dict so that
# overrides can be applied below.
profile_match = {}
if not isinstance(profile_match, dict):
raise CommandExecutionError('lxc.{0} must be a dictionary'.format(key))
# Overlay the kwargs to override matched profile data
overrides = salt.utils.args.clean_kwargs(**copy.deepcopy(kwargs))
profile_match = salt.utils.dictupdate.update(
copy.deepcopy(profile_match),
overrides
)
return profile_match
def get_container_profile(name=None, **kwargs):
'''
.. versionadded:: 2015.5.0
Gather a pre-configured set of container configuration parameters. If no
arguments are passed, an empty profile is returned.
Profiles can be defined in the minion or master config files, or in pillar
or grains, and are loaded using :mod:`config.get
<salt.modules.config.get>`. The key under which LXC profiles must be
configured is ``lxc.container_profile.profile_name``. An example container
profile would be as follows:
.. code-block:: yaml
lxc.container_profile:
ubuntu:
template: ubuntu
backing: lvm
vgname: lxc
size: 1G
Parameters set in a profile can be overridden by passing additional
container creation arguments (such as the ones passed to :mod:`lxc.create
<salt.modules.lxc.create>`) to this function.
A profile can be defined either as the name of the profile, or a dictionary
of variable names and values. See the :ref:`LXC Tutorial
<tutorial-lxc-profiles>` for more information on how to use LXC profiles.
CLI Example:
.. code-block:: bash
salt-call lxc.get_container_profile centos
salt-call lxc.get_container_profile ubuntu template=ubuntu backing=overlayfs
'''
profile = _get_profile('container_profile', name, **kwargs)
return profile
def get_network_profile(name=None, **kwargs):
'''
.. versionadded:: 2015.5.0
Gather a pre-configured set of network configuration parameters. If no
arguments are passed, the following default profile is returned:
.. code-block:: python
{'eth0': {'link': 'br0', 'type': 'veth', 'flags': 'up'}}
Profiles can be defined in the minion or master config files, or in pillar
or grains, and are loaded using :mod:`config.get
<salt.modules.config.get>`. The key under which LXC profiles must be
configured is ``lxc.network_profile``. An example network profile would be
as follows:
.. code-block:: yaml
lxc.network_profile.centos:
eth0:
link: br0
type: veth
flags: up
To disable networking entirely:
.. code-block:: yaml
lxc.network_profile.centos:
eth0:
disable: true
Parameters set in a profile can be overridden by passing additional
arguments to this function.
A profile can be passed either as the name of the profile, or a
dictionary of variable names and values. See the :ref:`LXC Tutorial
<tutorial-lxc-profiles>` for more information on how to use network
profiles.
.. warning::
The ``ipv4``, ``ipv6``, ``gateway``, and ``link`` (bridge) settings in
network profiles will only work if the container doesn't redefine the
network configuration (for example in
``/etc/sysconfig/network-scripts/ifcfg-<interface_name>`` on
RHEL/CentOS, or ``/etc/network/interfaces`` on Debian/Ubuntu/etc.)
CLI Example:
.. code-block:: bash
salt-call lxc.get_network_profile default
'''
profile = _get_profile('network_profile', name, **kwargs)
return profile
def _rand_cpu_str(cpu):
'''
Return a random subset of cpus for the cpuset config
'''
cpu = int(cpu)
avail = __salt__['status.nproc']()
if cpu < avail:
return '0-{0}'.format(avail)
to_set = set()
while len(to_set) < cpu:
choice = random.randint(0, avail - 1)
if choice not in to_set:
to_set.add(six.text_type(choice))
return ','.join(sorted(to_set))
def _network_conf(conf_tuples=None, **kwargs):
'''
Network configuration defaults
network_profile
as for containers, we can either call this function
either with a network_profile dict or network profile name
in the kwargs
nic_opts
overrides or extra nics in the form {nic_name: {set: tings}
'''
nic = kwargs.get('network_profile', None)
ret = []
nic_opts = kwargs.get('nic_opts', {})
if nic_opts is None:
# coming from elsewhere
nic_opts = {}
if not conf_tuples:
conf_tuples = []
old = _get_veths(conf_tuples)
if not old:
old = {}
# if we have a profile name, get the profile and load the network settings
# this will obviously by default look for a profile called "eth0"
# or by what is defined in nic_opts
# and complete each nic settings by sane defaults
if nic and isinstance(nic, (six.string_types, dict)):
nicp = get_network_profile(nic)
else:
nicp = {}
if DEFAULT_NIC not in nicp:
nicp[DEFAULT_NIC] = {}
kwargs = copy.deepcopy(kwargs)
gateway = kwargs.pop('gateway', None)
bridge = kwargs.get('bridge', None)
if nic_opts:
for dev, args in six.iteritems(nic_opts):
ethx = nicp.setdefault(dev, {})
try:
ethx = salt.utils.dictupdate.update(ethx, args)
except AttributeError:
raise SaltInvocationError('Invalid nic_opts configuration')
ifs = [a for a in nicp]
ifs += [a for a in old if a not in nicp]
ifs.sort()
gateway_set = False
for dev in ifs:
args = nicp.get(dev, {})
opts = nic_opts.get(dev, {}) if nic_opts else {}
old_if = old.get(dev, {})
disable = opts.get('disable', args.get('disable', False))
if disable:
continue
mac = opts.get('mac',
opts.get('hwaddr',
args.get('mac',
args.get('hwaddr', ''))))
type_ = opts.get('type', args.get('type', ''))
flags = opts.get('flags', args.get('flags', ''))
link = opts.get('link', args.get('link', ''))
ipv4 = opts.get('ipv4', args.get('ipv4', ''))
ipv6 = opts.get('ipv6', args.get('ipv6', ''))
infos = salt.utils.odict.OrderedDict([
('lxc.network.type', {
'test': not type_,
'value': type_,
'old': old_if.get('lxc.network.type'),
'default': 'veth'}),
('lxc.network.name', {
'test': False,
'value': dev,
'old': dev,
'default': dev}),
('lxc.network.flags', {
'test': not flags,
'value': flags,
'old': old_if.get('lxc.network.flags'),
'default': 'up'}),
('lxc.network.link', {
'test': not link,
'value': link,
'old': old_if.get('lxc.network.link'),
'default': search_lxc_bridge()}),
('lxc.network.hwaddr', {
'test': not mac,
'value': mac,
'old': old_if.get('lxc.network.hwaddr'),
'default': salt.utils.network.gen_mac()}),
('lxc.network.ipv4', {
'test': not ipv4,
'value': ipv4,
'old': old_if.get('lxc.network.ipv4', ''),
'default': None}),
('lxc.network.ipv6', {
'test': not ipv6,
'value': ipv6,
'old': old_if.get('lxc.network.ipv6', ''),
'default': None})])
# for each parameter, if not explicitly set, the
# config value present in the LXC configuration should
# take precedence over the profile configuration
for info in list(infos.keys()):
bundle = infos[info]
if bundle['test']:
if bundle['old']:
bundle['value'] = bundle['old']
elif bundle['default']:
bundle['value'] = bundle['default']
for info, data in six.iteritems(infos):
if data['value']:
ret.append({info: data['value']})
for key, val in six.iteritems(args):
if key == 'link' and bridge:
val = bridge
val = opts.get(key, val)
if key in [
'type', 'flags', 'name',
'gateway', 'mac', 'link', 'ipv4', 'ipv6'
]:
continue
ret.append({'lxc.network.{0}'.format(key): val})
# gateway (in automode) must be appended following network conf !
if not gateway:
gateway = args.get('gateway', None)
if gateway is not None and not gateway_set:
ret.append({'lxc.network.ipv4.gateway': gateway})
# only one network gateway ;)
gateway_set = True
# normally, this won't happen
# set the gateway if specified even if we did
# not managed the network underlying
if gateway is not None and not gateway_set:
ret.append({'lxc.network.ipv4.gateway': gateway})
# only one network gateway ;)
gateway_set = True
new = _get_veths(ret)
# verify that we did not loose the mac settings
for iface in [a for a in new]:
ndata = new[iface]
nmac = ndata.get('lxc.network.hwaddr', '')
ntype = ndata.get('lxc.network.type', '')
omac, otype = '', ''
if iface in old:
odata = old[iface]
omac = odata.get('lxc.network.hwaddr', '')
otype = odata.get('lxc.network.type', '')
# default for network type is setted here
# attention not to change the network type
# without a good and explicit reason to.
if otype and not ntype:
ntype = otype
if not ntype:
ntype = 'veth'
new[iface]['lxc.network.type'] = ntype
if omac and not nmac:
new[iface]['lxc.network.hwaddr'] = omac
ret = []
for val in six.itervalues(new):
for row in val:
ret.append(salt.utils.odict.OrderedDict([(row, val[row])]))
# on old versions of lxc, still support the gateway auto mode
# if we didn't explicitly say no to
# (lxc.network.ipv4.gateway: auto)
if _LooseVersion(version()) <= _LooseVersion('1.0.7') and \
True not in ['lxc.network.ipv4.gateway' in a for a in ret] and \
True in ['lxc.network.ipv4' in a for a in ret]:
ret.append({'lxc.network.ipv4.gateway': 'auto'})
return ret
def _get_lxc_default_data(**kwargs):
kwargs = copy.deepcopy(kwargs)
ret = {}
for k in ['utsname', 'rootfs']:
val = kwargs.get(k, None)
if val is not None:
ret['lxc.{0}'.format(k)] = val
autostart = kwargs.get('autostart')
# autostart can have made in kwargs, but with the None
# value which is invalid, we need an explicit boolean
# autostart = on is the default.
if autostart is None:
autostart = True
# we will set the regular lxc marker to restart container at
# machine (re)boot only if we did not explicitly ask
# not to touch to the autostart settings via
# autostart == 'keep'
if autostart != 'keep':
if autostart:
ret['lxc.start.auto'] = '1'
else:
ret['lxc.start.auto'] = '0'
memory = kwargs.get('memory')
if memory is not None:
# converting the config value from MB to bytes
ret['lxc.cgroup.memory.limit_in_bytes'] = memory * 1024 * 1024
cpuset = kwargs.get('cpuset')
if cpuset:
ret['lxc.cgroup.cpuset.cpus'] = cpuset
cpushare = kwargs.get('cpushare')
cpu = kwargs.get('cpu')
if cpushare:
ret['lxc.cgroup.cpu.shares'] = cpushare
if cpu and not cpuset:
ret['lxc.cgroup.cpuset.cpus'] = _rand_cpu_str(cpu)
return ret
def _config_list(conf_tuples=None, only_net=False, **kwargs):
'''
Return a list of dicts from the salt level configurations
conf_tuples
_LXCConfig compatible list of entries which can contain
- string line
- tuple (lxc config param,value)
- dict of one entry: {lxc config param: value)
only_net
by default we add to the tuples a reflection of both
the real config if avalaible and a certain amount of
default values like the cpu parameters, the memory
and etc.
On the other hand, we also no matter the case reflect
the network configuration computed from the actual config if
available and given values.
if no_default_loads is set, we will only
reflect the network configuration back to the conf tuples
list
'''
# explicit cast
only_net = bool(only_net)
if not conf_tuples:
conf_tuples = []
kwargs = copy.deepcopy(kwargs)
ret = []
if not only_net:
default_data = _get_lxc_default_data(**kwargs)
for k, val in six.iteritems(default_data):
ret.append({k: val})
net_datas = _network_conf(conf_tuples=conf_tuples, **kwargs)
ret.extend(net_datas)
return ret
def _get_veths(net_data):
'''
Parse the nic setup inside lxc conf tuples back to a dictionary indexed by
network interface
'''
if isinstance(net_data, dict):
net_data = list(net_data.items())
nics = salt.utils.odict.OrderedDict()
current_nic = salt.utils.odict.OrderedDict()
no_names = True
for item in net_data:
if item and isinstance(item, dict):
item = list(item.items())[0]
# skip LXC configuration comment lines, and play only with tuples conf
elif isinstance(item, six.string_types):
# deal with reflection of commented lxc configs
sitem = item.strip()
if sitem.startswith('#') or not sitem:
continue
elif '=' in item:
item = tuple([a.strip() for a in item.split('=', 1)])
if item[0] == 'lxc.network.type':
current_nic = salt.utils.odict.OrderedDict()
if item[0] == 'lxc.network.name':
no_names = False
nics[item[1].strip()] = current_nic
current_nic[item[0].strip()] = item[1].strip()
# if not ethernet card name has been collected, assuming we collected
# data for eth0
if no_names and current_nic:
nics[DEFAULT_NIC] = current_nic
return nics
class _LXCConfig(object):
'''
LXC configuration data
'''
pattern = re.compile(r'^(\S+)(\s*)(=)(\s*)(.*)')
non_interpretable_pattern = re.compile(r'^((#.*)|(\s*))$')
def __init__(self, **kwargs):
kwargs = copy.deepcopy(kwargs)
self.name = kwargs.pop('name', None)
path = get_root_path(kwargs.get('path', None))
self.data = []
if self.name:
self.path = os.path.join(path, self.name, 'config')
if os.path.isfile(self.path):
with salt.utils.files.fopen(self.path) as fhr:
for line in salt.utils.data.decode(fhr.readlines()):
match = self.pattern.findall((line.strip()))
if match:
self.data.append((match[0][0], match[0][-1]))
match = self.non_interpretable_pattern.findall(
(line.strip()))
if match:
self.data.append(('', match[0][0]))
else:
self.path = None
def _replace(key, val):
if val:
self._filter_data(key)
self.data.append((key, val))
default_data = _get_lxc_default_data(**kwargs)
for key, val in six.iteritems(default_data):
_replace(key, val)
old_net = self._filter_data('lxc.network')
net_datas = _network_conf(conf_tuples=old_net, **kwargs)
if net_datas:
for row in net_datas:
self.data.extend(list(row.items()))
# be sure to reset harmful settings
for idx in ['lxc.cgroup.memory.limit_in_bytes']:
if not default_data.get(idx):
self._filter_data(idx)
def as_string(self):
chunks = ('{0[0]}{1}{0[1]}'.format(item, (' = ' if item[0] else '')) for item in self.data)
return '\n'.join(chunks) + '\n'
def write(self):
if self.path:
content = self.as_string()
# 2 step rendering to be sure not to open/wipe the config
# before as_string succeeds.
with salt.utils.files.fopen(self.path, 'w') as fic:
fic.write(salt.utils.stringutils.to_str(content))
fic.flush()
def tempfile(self):
# this might look like the function name is shadowing the
# module, but it's not since the method belongs to the class
ntf = tempfile.NamedTemporaryFile()
ntf.write(self.as_string())
ntf.flush()
return ntf
def _filter_data(self, pattern):
'''
Removes parameters which match the pattern from the config data
'''
removed = []
filtered = []
for param in self.data:
if not param[0].startswith(pattern):
filtered.append(param)
else:
removed.append(param)
self.data = filtered
return removed
def _get_base(**kwargs):
'''
If the needed base does not exist, then create it, if it does exist
create nothing and return the name of the base lxc container so
it can be cloned.
'''
profile = get_container_profile(copy.deepcopy(kwargs.get('profile')))
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, _marker)
profile_match = profile.pop(key, default)
# let kwarg overrides be the preferred choice
if kw_overrides_match is _marker:
return profile_match
return kw_overrides_match
template = select('template')
image = select('image')
vgname = select('vgname')
path = kwargs.get('path', None)
# remove the above three variables from kwargs, if they exist, to avoid
# duplicates if create() is invoked below.
for param in ('path', 'image', 'vgname', 'template'):
kwargs.pop(param, None)
if image:
proto = _urlparse(image).scheme
img_tar = __salt__['cp.cache_file'](image)
img_name = os.path.basename(img_tar)
hash_ = salt.utils.hashutils.get_hash(
img_tar,
__salt__['config.get']('hash_type'))
name = '__base_{0}_{1}_{2}'.format(proto, img_name, hash_)
if not exists(name, path=path):
create(name, template=template, image=image,
path=path, vgname=vgname, **kwargs)
if vgname:
rootfs = os.path.join('/dev', vgname, name)
edit_conf(info(name, path=path)['config'],
out_format='commented', **{'lxc.rootfs': rootfs})
return name
elif template:
name = '__base_{0}'.format(template)
if not exists(name, path=path):
create(name, template=template, image=image, path=path,
vgname=vgname, **kwargs)
if vgname:
rootfs = os.path.join('/dev', vgname, name)
edit_conf(info(name, path=path)['config'],
out_format='commented', **{'lxc.rootfs': rootfs})
return name
return ''
def init(name,
config=None,
cpuset=None,
cpushare=None,
memory=None,
profile=None,
network_profile=None,
nic_opts=None,
cpu=None,
autostart=True,
password=None,
password_encrypted=None,
users=None,
dnsservers=None,
searchdomains=None,
bridge=None,
gateway=None,
pub_key=None,
priv_key=None,
force_install=False,
unconditional_install=False,
bootstrap_delay=None,
bootstrap_args=None,
bootstrap_shell=None,
bootstrap_url=None,
**kwargs):
'''
Initialize a new container.
This is a partial idempotent function as if it is already provisioned, we
will reset a bit the lxc configuration file but much of the hard work will
be escaped as markers will prevent re-execution of harmful tasks.
name
Name of the container
image
A tar archive to use as the rootfs for the container. Conflicts with
the ``template`` argument.
cpus
Select a random number of cpu cores and assign it to the cpuset, if the
cpuset option is set then this option will be ignored
cpuset
Explicitly define the cpus this container will be bound to
cpushare
cgroups cpu shares
autostart
autostart container on reboot
memory
cgroups memory limit, in MB
.. versionchanged:: 2015.5.0
If no value is passed, no limit is set. In earlier Salt versions,
not passing this value causes a 1024MB memory limit to be set, and
it was necessary to pass ``memory=0`` to set no limit.
gateway
the ipv4 gateway to use
the default does nothing more than lxcutils does
bridge
the bridge to use
the default does nothing more than lxcutils does
network_profile
Network profile to use for the container
.. versionadded:: 2015.5.0
nic_opts
Extra options for network interfaces, will override
``{"eth0": {"hwaddr": "aa:bb:cc:dd:ee:ff", "ipv4": "10.1.1.1", "ipv6": "2001:db8::ff00:42:8329"}}``
or
``{"eth0": {"hwaddr": "aa:bb:cc:dd:ee:ff", "ipv4": "10.1.1.1/24", "ipv6": "2001:db8::ff00:42:8329"}}``
users
Users for which the password defined in the ``password`` param should
be set. Can be passed as a comma separated list or a python list.
Defaults to just the ``root`` user.
password
Set the initial password for the users defined in the ``users``
parameter
password_encrypted : False
Set to ``True`` to denote a password hash instead of a plaintext
password
.. versionadded:: 2015.5.0
profile
A LXC profile (defined in config or pillar).
This can be either a real profile mapping or a string
to retrieve it in configuration
start
Start the newly-created container
dnsservers
list of dns servers to set in the container, default [] (no setting)
seed
Seed the container with the minion config. Default: ``True``
install
If salt-minion is not already installed, install it. Default: ``True``
config
Optional config parameters. By default, the id is set to
the name of the container.
master
salt master (default to minion's master)
master_port
salt master port (default to minion's master port)
pub_key
Explicit public key to preseed the minion with (optional).
This can be either a filepath or a string representing the key
priv_key
Explicit private key to preseed the minion with (optional).
This can be either a filepath or a string representing the key
approve_key
If explicit preseeding is not used;
Attempt to request key approval from the master. Default: ``True``
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
clone_from
Original from which to use a clone operation to create the container.
Default: ``None``
bootstrap_delay
Delay in seconds between end of container creation and bootstrapping.
Useful when waiting for container to obtain a DHCP lease.
.. versionadded:: 2015.5.0
bootstrap_url
See lxc.bootstrap
bootstrap_shell
See lxc.bootstrap
bootstrap_args
See lxc.bootstrap
force_install
Force installation even if salt-minion is detected,
this is the way to run vendor bootstrap scripts even
if a salt minion is already present in the container
unconditional_install
Run the script even if the container seems seeded
CLI Example:
.. code-block:: bash
salt 'minion' lxc.init name [cpuset=cgroups_cpuset] \\
[cpushare=cgroups_cpushare] [memory=cgroups_memory] \\
[nic=nic_profile] [profile=lxc_profile] \\
[nic_opts=nic_opts] [start=(True|False)] \\
[seed=(True|False)] [install=(True|False)] \\
[config=minion_config] [approve_key=(True|False) \\
[clone_from=original] [autostart=True] \\
[priv_key=/path_or_content] [pub_key=/path_or_content] \\
[bridge=lxcbr0] [gateway=10.0.3.1] \\
[dnsservers[dns1,dns2]] \\
[users=[foo]] [password='secret'] \\
[password_encrypted=(True|False)]
'''
ret = {'name': name,
'changes': {}}
profile = get_container_profile(copy.deepcopy(profile))
if not network_profile:
network_profile = profile.get('network_profile')
if not network_profile:
network_profile = DEFAULT_NIC
# Changes is a pointer to changes_dict['init']. This method is used so that
# we can have a list of changes as they are made, providing an ordered list
# of things that were changed.
changes_dict = {'init': []}
changes = changes_dict.get('init')
if users is None:
users = []
dusers = ['root']
for user in dusers:
if user not in users:
users.append(user)
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, _marker)
profile_match = profile.pop(key, default)
# let kwarg overrides be the preferred choice
if kw_overrides_match is _marker:
return profile_match
return kw_overrides_match
path = select('path')
bpath = get_root_path(path)
state_pre = state(name, path=path)
tvg = select('vgname')
vgname = tvg if tvg else __salt__['config.get']('lxc.vgname')
start_ = select('start', True)
autostart = select('autostart', autostart)
seed = select('seed', True)
install = select('install', True)
seed_cmd = select('seed_cmd')
salt_config = _get_salt_config(config, **kwargs)
approve_key = select('approve_key', True)
clone_from = select('clone_from')
# If using a volume group then set up to make snapshot cow clones
if vgname and not clone_from:
try:
kwargs['vgname'] = vgname
clone_from = _get_base(profile=profile, **kwargs)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = exc.strerror
if changes:
ret['changes'] = changes_dict
return ret
if not kwargs.get('snapshot') is False:
kwargs['snapshot'] = True
does_exist = exists(name, path=path)
to_reboot = False
remove_seed_marker = False
if does_exist:
pass
elif clone_from:
remove_seed_marker = True
try:
clone(name, clone_from, profile=profile, **kwargs)
changes.append({'create': 'Container cloned'})
except (SaltInvocationError, CommandExecutionError) as exc:
if 'already exists' in exc.strerror:
changes.append({'create': 'Container already exists'})
else:
ret['result'] = False
ret['comment'] = exc.strerror
if changes:
ret['changes'] = changes_dict
return ret
cfg = _LXCConfig(name=name, network_profile=network_profile,
nic_opts=nic_opts, bridge=bridge, path=path,
gateway=gateway, autostart=autostart,
cpuset=cpuset, cpushare=cpushare, memory=memory)
old_chunks = read_conf(cfg.path, out_format='commented')
cfg.write()
chunks = read_conf(cfg.path, out_format='commented')
if old_chunks != chunks:
to_reboot = True
else:
remove_seed_marker = True
cfg = _LXCConfig(network_profile=network_profile,
nic_opts=nic_opts, cpuset=cpuset, path=path,
bridge=bridge, gateway=gateway,
autostart=autostart,
cpushare=cpushare, memory=memory)
with cfg.tempfile() as cfile:
try:
create(name, config=cfile.name, profile=profile, **kwargs)
changes.append({'create': 'Container created'})
except (SaltInvocationError, CommandExecutionError) as exc:
if 'already exists' in exc.strerror:
changes.append({'create': 'Container already exists'})
else:
ret['comment'] = exc.strerror
if changes:
ret['changes'] = changes_dict
return ret
cpath = os.path.join(bpath, name, 'config')
old_chunks = []
if os.path.exists(cpath):
old_chunks = read_conf(cpath, out_format='commented')
new_cfg = _config_list(conf_tuples=old_chunks,
cpu=cpu,
network_profile=network_profile,
nic_opts=nic_opts, bridge=bridge,
cpuset=cpuset, cpushare=cpushare,
memory=memory)
if new_cfg:
edit_conf(cpath, out_format='commented', lxc_config=new_cfg)
chunks = read_conf(cpath, out_format='commented')
if old_chunks != chunks:
to_reboot = True
# last time to be sure any of our property is correctly applied
cfg = _LXCConfig(name=name, network_profile=network_profile,
nic_opts=nic_opts, bridge=bridge, path=path,
gateway=gateway, autostart=autostart,
cpuset=cpuset, cpushare=cpushare, memory=memory)
old_chunks = []
if os.path.exists(cfg.path):
old_chunks = read_conf(cfg.path, out_format='commented')
cfg.write()
chunks = read_conf(cfg.path, out_format='commented')
if old_chunks != chunks:
changes.append({'config': 'Container configuration updated'})
to_reboot = True
if to_reboot:
try:
stop(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
if changes:
ret['changes'] = changes_dict
return ret
if not does_exist or (does_exist and state(name, path=path) != 'running'):
try:
start(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
if changes:
ret['changes'] = changes_dict
return ret
if remove_seed_marker:
run(name,
'rm -f \'{0}\''.format(SEED_MARKER),
path=path,
chroot_fallback=False,
python_shell=False)
# set the default user/password, only the first time
if ret.get('result', True) and password:
gid = '/.lxc.initial_pass'
gids = [gid,
'/lxc.initial_pass',
'/.lxc.{0}.initial_pass'.format(name)]
if not any(retcode(name,
'test -e "{0}"'.format(x),
chroot_fallback=True,
path=path,
ignore_retcode=True) == 0
for x in gids):
# think to touch the default user generated by default templates
# which has a really unsecure passwords...
# root is defined as a member earlier in the code
for default_user in ['ubuntu']:
if (
default_user not in users and
retcode(name,
'id {0}'.format(default_user),
python_shell=False,
path=path,
chroot_fallback=True,
ignore_retcode=True) == 0
):
users.append(default_user)
for user in users:
try:
cret = set_password(name,
users=[user],
path=path,
password=password,
encrypted=password_encrypted)
except (SaltInvocationError, CommandExecutionError) as exc:
msg = '{0}: Failed to set password'.format(
user) + exc.strerror
# only hardfail in unrecoverable situation:
# root cannot be setted up
if user == 'root':
ret['comment'] = msg
ret['result'] = False
else:
log.debug(msg)
if ret.get('result', True):
changes.append({'password': 'Password(s) updated'})
if retcode(name,
('sh -c \'touch "{0}"; test -e "{0}"\''
.format(gid)),
path=path,
chroot_fallback=True,
ignore_retcode=True) != 0:
ret['comment'] = 'Failed to set password marker'
changes[-1]['password'] += '. ' + ret['comment'] + '.'
ret['result'] = False
# set dns servers if any, only the first time
if ret.get('result', True) and dnsservers:
# retro compatibility, test also old markers
gid = '/.lxc.initial_dns'
gids = [gid,
'/lxc.initial_dns',
'/lxc.{0}.initial_dns'.format(name)]
if not any(retcode(name,
'test -e "{0}"'.format(x),
chroot_fallback=True,
path=path,
ignore_retcode=True) == 0
for x in gids):
try:
set_dns(name,
path=path,
dnsservers=dnsservers,
searchdomains=searchdomains)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Failed to set DNS: ' + exc.strerror
ret['result'] = False
else:
changes.append({'dns': 'DNS updated'})
if retcode(name,
('sh -c \'touch "{0}"; test -e "{0}"\''
.format(gid)),
chroot_fallback=True,
path=path,
ignore_retcode=True) != 0:
ret['comment'] = 'Failed to set DNS marker'
changes[-1]['dns'] += '. ' + ret['comment'] + '.'
ret['result'] = False
# retro compatibility, test also old markers
if remove_seed_marker:
run(name,
'rm -f \'{0}\''.format(SEED_MARKER),
path=path,
python_shell=False)
gid = '/.lxc.initial_seed'
gids = [gid, '/lxc.initial_seed']
if (
any(retcode(name,
'test -e {0}'.format(x),
path=path,
chroot_fallback=True,
ignore_retcode=True) == 0
for x in gids) or not ret.get('result', True)
):
pass
elif seed or seed_cmd:
if seed:
try:
result = bootstrap(
name, config=salt_config, path=path,
approve_key=approve_key,
pub_key=pub_key, priv_key=priv_key,
install=install,
force_install=force_install,
unconditional_install=unconditional_install,
bootstrap_delay=bootstrap_delay,
bootstrap_url=bootstrap_url,
bootstrap_shell=bootstrap_shell,
bootstrap_args=bootstrap_args)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Bootstrap failed: ' + exc.strerror
ret['result'] = False
else:
if not result:
ret['comment'] = ('Bootstrap failed, see minion log for '
'more information')
ret['result'] = False
else:
changes.append(
{'bootstrap': 'Container successfully bootstrapped'}
)
elif seed_cmd:
try:
result = __salt__[seed_cmd](info(name, path=path)['rootfs'],
name,
salt_config)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = ('Bootstrap via seed_cmd \'{0}\' failed: {1}'
.format(seed_cmd, exc.strerror))
ret['result'] = False
else:
if not result:
ret['comment'] = ('Bootstrap via seed_cmd \'{0}\' failed, '
'see minion log for more information '
.format(seed_cmd))
ret['result'] = False
else:
changes.append(
{'bootstrap': 'Container successfully bootstrapped '
'using seed_cmd \'{0}\''
.format(seed_cmd)}
)
if ret.get('result', True) and not start_:
try:
stop(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
ret['result'] = False
state_post = state(name, path=path)
if state_pre != state_post:
changes.append({'state': {'old': state_pre, 'new': state_post}})
if ret.get('result', True):
ret['comment'] = ('Container \'{0}\' successfully initialized'
.format(name))
ret['result'] = True
if changes:
ret['changes'] = changes_dict
return ret
def cloud_init(name, vm_=None, **kwargs):
'''
Thin wrapper to lxc.init to be used from the saltcloud lxc driver
name
Name of the container
may be None and then guessed from saltcloud mapping
`vm_`
saltcloud mapping defaults for the vm
CLI Example:
.. code-block:: bash
salt '*' lxc.cloud_init foo
'''
init_interface = cloud_init_interface(name, vm_, **kwargs)
name = init_interface.pop('name', name)
return init(name, **init_interface)
def images(dist=None):
'''
.. versionadded:: 2015.5.0
List the available images for LXC's ``download`` template.
dist : None
Filter results to a single Linux distribution
CLI Examples:
.. code-block:: bash
salt myminion lxc.images
salt myminion lxc.images dist=centos
'''
out = __salt__['cmd.run_stdout'](
'lxc-create -n __imgcheck -t download -- --list',
ignore_retcode=True
)
if 'DIST' not in out:
raise CommandExecutionError(
'Unable to run the \'download\' template script. Is it installed?'
)
ret = {}
passed_header = False
for line in out.splitlines():
try:
distro, release, arch, variant, build_time = line.split()
except ValueError:
continue
if not passed_header:
if distro == 'DIST':
passed_header = True
continue
dist_list = ret.setdefault(distro, [])
dist_list.append({
'release': release,
'arch': arch,
'variant': variant,
'build_time': build_time,
})
if dist is not None:
return dict([(dist, ret.get(dist, []))])
return ret
def templates():
'''
.. versionadded:: 2015.5.0
List the available LXC template scripts installed on the minion
CLI Examples:
.. code-block:: bash
salt myminion lxc.templates
'''
try:
template_scripts = os.listdir('/usr/share/lxc/templates')
except OSError:
return []
else:
return [x[4:] for x in template_scripts if x.startswith('lxc-')]
def _after_ignition_network_profile(cmd,
ret,
name,
network_profile,
path,
nic_opts):
_clear_context()
if ret['retcode'] == 0 and exists(name, path=path):
if network_profile:
network_changes = apply_network_profile(name,
network_profile,
path=path,
nic_opts=nic_opts)
if network_changes:
log.info(
'Network changes from applying network profile \'%s\' '
'to newly-created container \'%s\':\n%s',
network_profile, name, network_changes
)
c_state = state(name, path=path)
return {'result': True,
'state': {'old': None, 'new': c_state}}
else:
if exists(name, path=path):
# destroy the container if it was partially created
cmd = 'lxc-destroy'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0}'.format(name)
__salt__['cmd.retcode'](cmd, python_shell=False)
raise CommandExecutionError(
'Container could not be created with cmd \'{0}\': {1}'
.format(cmd, ret['stderr'])
)
def create(name,
config=None,
profile=None,
network_profile=None,
nic_opts=None,
**kwargs):
'''
Create a new container.
name
Name of the container
config
The config file to use for the container. Defaults to system-wide
config (usually in /etc/lxc/lxc.conf).
profile
Profile to use in container creation (see
:mod:`lxc.get_container_profile
<salt.modules.lxc.get_container_profile>`). Values in a profile will be
overridden by the **Container Creation Arguments** listed below.
network_profile
Network profile to use for container
.. versionadded:: 2015.5.0
**Container Creation Arguments**
template
The template to use. For example, ``ubuntu`` or ``fedora``.
For a full list of available templates, check out
the :mod:`lxc.templates <salt.modules.lxc.templates>` function.
Conflicts with the ``image`` argument.
.. note::
The ``download`` template requires the following three parameters
to be defined in ``options``:
* **dist** - The name of the distribution
* **release** - Release name/version
* **arch** - Architecture of the container
The available images can be listed using the :mod:`lxc.images
<salt.modules.lxc.images>` function.
options
Template-specific options to pass to the lxc-create command. These
correspond to the long options (ones beginning with two dashes) that
the template script accepts. For example:
.. code-block:: bash
options='{"dist": "centos", "release": "6", "arch": "amd64"}'
For available template options, refer to the lxc template scripts
which are ususally located under ``/usr/share/lxc/templates``,
or run ``lxc-create -t <template> -h``.
image
A tar archive to use as the rootfs for the container. Conflicts with
the ``template`` argument.
backing
The type of storage to use. Set to ``lvm`` to use an LVM group.
Defaults to filesystem within /var/lib/lxc.
fstype
Filesystem type to use on LVM logical volume
size : 1G
Size of the volume to create. Only applicable if ``backing=lvm``.
vgname : lxc
Name of the LVM volume group in which to create the volume for this
container. Only applicable if ``backing=lvm``.
lvname
Name of the LVM logical volume in which to create the volume for this
container. Only applicable if ``backing=lvm``.
thinpool
Name of a pool volume that will be used for thin-provisioning this
container. Only applicable if ``backing=lvm``.
nic_opts
give extra opts overriding network profile values
path
parent path for the container creation (default: /var/lib/lxc)
zfsroot
Name of the ZFS root in which to create the volume for this container.
Only applicable if ``backing=zfs``. (default: tank/lxc)
.. versionadded:: 2015.8.0
'''
# Required params for 'download' template
download_template_deps = ('dist', 'release', 'arch')
cmd = 'lxc-create -n {0}'.format(name)
profile = get_container_profile(copy.deepcopy(profile))
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, None)
profile_match = profile.pop(key, default)
# Return the profile match if the the kwarg match was None, as the
# lxc.present state will pass these kwargs set to None by default.
if kw_overrides_match is None:
return profile_match
return kw_overrides_match
path = select('path')
if exists(name, path=path):
raise CommandExecutionError(
'Container \'{0}\' already exists'.format(name)
)
tvg = select('vgname')
vgname = tvg if tvg else __salt__['config.get']('lxc.vgname')
# The 'template' and 'image' params conflict
template = select('template')
image = select('image')
if template and image:
raise SaltInvocationError(
'Only one of \'template\' and \'image\' is permitted'
)
elif not any((template, image, profile)):
raise SaltInvocationError(
'At least one of \'template\', \'image\', and \'profile\' is '
'required'
)
options = select('options') or {}
backing = select('backing')
if vgname and not backing:
backing = 'lvm'
lvname = select('lvname')
thinpool = select('thinpool')
fstype = select('fstype')
size = select('size', '1G')
zfsroot = select('zfsroot')
if backing in ('dir', 'overlayfs', 'btrfs', 'zfs'):
fstype = None
size = None
# some backends won't support some parameters
if backing in ('aufs', 'dir', 'overlayfs', 'btrfs'):
lvname = vgname = thinpool = None
if image:
img_tar = __salt__['cp.cache_file'](image)
template = os.path.join(
os.path.dirname(salt.__file__),
'templates',
'lxc',
'salt_tarball')
options['imgtar'] = img_tar
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
if not os.path.exists(path):
os.makedirs(path)
if config:
cmd += ' -f {0}'.format(config)
if template:
cmd += ' -t {0}'.format(template)
if backing:
backing = backing.lower()
cmd += ' -B {0}'.format(backing)
if backing in ('zfs',):
if zfsroot:
cmd += ' --zfsroot {0}'.format(zfsroot)
if backing in ('lvm',):
if lvname:
cmd += ' --lvname {0}'.format(lvname)
if vgname:
cmd += ' --vgname {0}'.format(vgname)
if thinpool:
cmd += ' --thinpool {0}'.format(thinpool)
if backing not in ('dir', 'overlayfs'):
if fstype:
cmd += ' --fstype {0}'.format(fstype)
if size:
cmd += ' --fssize {0}'.format(size)
if options:
if template == 'download':
missing_deps = [x for x in download_template_deps
if x not in options]
if missing_deps:
raise SaltInvocationError(
'Missing params in \'options\' dict: {0}'
.format(', '.join(missing_deps))
)
cmd += ' --'
for key, val in six.iteritems(options):
cmd += ' --{0} {1}'.format(key, val)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
# please do not merge extra conflicting stuff
# inside those two line (ret =, return)
return _after_ignition_network_profile(cmd,
ret,
name,
network_profile,
path,
nic_opts)
def clone(name,
orig,
profile=None,
network_profile=None,
nic_opts=None,
**kwargs):
'''
Create a new container as a clone of another container
name
Name of the container
orig
Name of the original container to be cloned
profile
Profile to use in container cloning (see
:mod:`lxc.get_container_profile
<salt.modules.lxc.get_container_profile>`). Values in a profile will be
overridden by the **Container Cloning Arguments** listed below.
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
**Container Cloning Arguments**
snapshot
Use Copy On Write snapshots (LVM)
size : 1G
Size of the volume to create. Only applicable if ``backing=lvm``.
backing
The type of storage to use. Set to ``lvm`` to use an LVM group.
Defaults to filesystem within /var/lib/lxc.
network_profile
Network profile to use for container
.. versionadded:: 2015.8.0
nic_opts
give extra opts overriding network profile values
.. versionadded:: 2015.8.0
CLI Examples:
.. code-block:: bash
salt '*' lxc.clone myclone orig=orig_container
salt '*' lxc.clone myclone orig=orig_container snapshot=True
'''
profile = get_container_profile(copy.deepcopy(profile))
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, None)
profile_match = profile.pop(key, default)
# let kwarg overrides be the preferred choice
if kw_overrides_match is None:
return profile_match
return kw_overrides_match
path = select('path')
if exists(name, path=path):
raise CommandExecutionError(
'Container \'{0}\' already exists'.format(name)
)
_ensure_exists(orig, path=path)
if state(orig, path=path) != 'stopped':
raise CommandExecutionError(
'Container \'{0}\' must be stopped to be cloned'.format(orig)
)
backing = select('backing')
snapshot = select('snapshot')
if backing in ('dir',):
snapshot = False
if not snapshot:
snapshot = ''
else:
snapshot = '-s'
size = select('size', '1G')
if backing in ('dir', 'overlayfs', 'btrfs'):
size = None
# LXC commands and options changed in 2.0 - CF issue #34086 for details
if _LooseVersion(version()) >= _LooseVersion('2.0'):
# https://linuxcontainers.org/lxc/manpages//man1/lxc-copy.1.html
cmd = 'lxc-copy'
cmd += ' {0} -n {1} -N {2}'.format(snapshot, orig, name)
else:
# https://linuxcontainers.org/lxc/manpages//man1/lxc-clone.1.html
cmd = 'lxc-clone'
cmd += ' {0} -o {1} -n {2}'.format(snapshot, orig, name)
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
if not os.path.exists(path):
os.makedirs(path)
if backing:
backing = backing.lower()
cmd += ' -B {0}'.format(backing)
if backing not in ('dir', 'overlayfs'):
if size:
cmd += ' -L {0}'.format(size)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
# please do not merge extra conflicting stuff
# inside those two line (ret =, return)
return _after_ignition_network_profile(cmd,
ret,
name,
network_profile,
path,
nic_opts)
def list_(extra=False, limit=None, path=None):
'''
List containers classified by state
extra
Also get per-container specific info. This will change the return data.
Instead of returning a list of containers, a dictionary of containers
and each container's output from :mod:`lxc.info
<salt.modules.lxc.info>`.
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
limit
Return output matching a specific state (**frozen**, **running**, or
**stopped**).
.. versionadded:: 2015.5.0
CLI Examples:
.. code-block:: bash
salt '*' lxc.list
salt '*' lxc.list extra=True
salt '*' lxc.list limit=running
'''
ctnrs = ls_(path=path)
if extra:
stopped = {}
frozen = {}
running = {}
else:
stopped = []
frozen = []
running = []
ret = {'running': running,
'stopped': stopped,
'frozen': frozen}
for container in ctnrs:
cmd = 'lxc-info'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0}'.format(container)
c_info = __salt__['cmd.run'](
cmd,
python_shell=False,
output_loglevel='debug'
)
c_state = None
for line in c_info.splitlines():
stat = line.split(':')
if stat[0] in ('State', 'state'):
c_state = stat[1].strip()
break
if not c_state or (limit is not None and c_state.lower() != limit):
continue
if extra:
infos = info(container, path=path)
method = 'update'
value = {container: infos}
else:
method = 'append'
value = container
if c_state == 'STOPPED':
getattr(stopped, method)(value)
continue
if c_state == 'FROZEN':
getattr(frozen, method)(value)
continue
if c_state == 'RUNNING':
getattr(running, method)(value)
continue
if limit is not None:
return ret.get(limit, {} if extra else [])
return ret
def _change_state(cmd,
name,
expected,
stdin=_marker,
stdout=_marker,
stderr=_marker,
with_communicate=_marker,
use_vt=_marker,
path=None):
pre = state(name, path=path)
if pre == expected:
return {'result': True,
'state': {'old': expected, 'new': expected},
'comment': 'Container \'{0}\' already {1}'
.format(name, expected)}
if cmd == 'lxc-destroy':
# Kill the container first
scmd = 'lxc-stop'
if path:
scmd += ' -P {0}'.format(pipes.quote(path))
scmd += ' -k -n {0}'.format(name)
__salt__['cmd.run'](scmd,
python_shell=False)
if path and ' -P ' not in cmd:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0}'.format(name)
# certain lxc commands need to be taken with care (lxc-start)
# as te command itself mess with double forks; we must not
# communicate with it, but just wait for the exit status
pkwargs = {'python_shell': False,
'redirect_stderr': True,
'with_communicate': with_communicate,
'use_vt': use_vt,
'stdin': stdin,
'stdout': stdout}
for i in [a for a in pkwargs]:
val = pkwargs[i]
if val is _marker:
pkwargs.pop(i, None)
_cmdout = __salt__['cmd.run_all'](cmd, **pkwargs)
if _cmdout['retcode'] != 0:
raise CommandExecutionError(
'Error changing state for container \'{0}\' using command '
'\'{1}\': {2}'.format(name, cmd, _cmdout['stdout'])
)
if expected is not None:
# some commands do not wait, so we will
rcmd = 'lxc-wait'
if path:
rcmd += ' -P {0}'.format(pipes.quote(path))
rcmd += ' -n {0} -s {1}'.format(name, expected.upper())
__salt__['cmd.run'](rcmd, python_shell=False, timeout=30)
_clear_context()
post = state(name, path=path)
ret = {'result': post == expected,
'state': {'old': pre, 'new': post}}
return ret
def _ensure_exists(name, path=None):
'''
Raise an exception if the container does not exist
'''
if not exists(name, path=path):
raise CommandExecutionError(
'Container \'{0}\' does not exist'.format(name)
)
def _ensure_running(name, no_start=False, path=None):
'''
If the container is not currently running, start it. This function returns
the state that the container was in before changing
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
'''
_ensure_exists(name, path=path)
pre = state(name, path=path)
if pre == 'running':
# This will be a no-op but running the function will give us a pretty
# return dict.
return start(name, path=path)
elif pre == 'stopped':
if no_start:
raise CommandExecutionError(
'Container \'{0}\' is not running'.format(name)
)
return start(name, path=path)
elif pre == 'frozen':
if no_start:
raise CommandExecutionError(
'Container \'{0}\' is not running'.format(name)
)
return unfreeze(name, path=path)
def restart(name, path=None, lxc_config=None, force=False):
'''
.. versionadded:: 2015.5.0
Restart the named container. If the container was not running, the
container will merely be started.
name
The name of the container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
lxc_config
path to a lxc config file
config file will be guessed from container name otherwise
.. versionadded:: 2015.8.0
force : False
If ``True``, the container will be force-stopped instead of gracefully
shut down
CLI Example:
.. code-block:: bash
salt myminion lxc.restart name
'''
_ensure_exists(name, path=path)
orig_state = state(name, path=path)
if orig_state != 'stopped':
stop(name, kill=force, path=path)
ret = start(name, path=path, lxc_config=lxc_config)
ret['state']['old'] = orig_state
if orig_state != 'stopped':
ret['restarted'] = True
return ret
def start(name, **kwargs):
'''
Start the named container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
lxc_config
path to a lxc config file
config file will be guessed from container name otherwise
.. versionadded:: 2015.8.0
use_vt
run the command through VT
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.start name
'''
path = kwargs.get('path', None)
cpath = get_root_path(path)
lxc_config = kwargs.get('lxc_config', None)
cmd = 'lxc-start'
if not lxc_config:
lxc_config = os.path.join(cpath, name, 'config')
# we try to start, even without config, if global opts are there
if os.path.exists(lxc_config):
cmd += ' -f {0}'.format(pipes.quote(lxc_config))
cmd += ' -d'
_ensure_exists(name, path=path)
if state(name, path=path) == 'frozen':
raise CommandExecutionError(
'Container \'{0}\' is frozen, use lxc.unfreeze'.format(name)
)
# lxc-start daemonize itself violently, we must not communicate with it
use_vt = kwargs.get('use_vt', None)
with_communicate = kwargs.get('with_communicate', False)
return _change_state(cmd, name, 'running',
stdout=None,
stderr=None,
stdin=None,
with_communicate=with_communicate,
path=path,
use_vt=use_vt)
def stop(name, kill=False, path=None, use_vt=None):
'''
Stop the named container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
kill: False
Do not wait for the container to stop, kill all tasks in the container.
Older LXC versions will stop containers like this irrespective of this
argument.
.. versionchanged:: 2015.5.0
Default value changed to ``False``
use_vt
run the command through VT
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.stop name
'''
_ensure_exists(name, path=path)
orig_state = state(name, path=path)
if orig_state == 'frozen' and not kill:
# Gracefully stopping a frozen container is slower than unfreezing and
# then stopping it (at least in my testing), so if we're not
# force-stopping the container, unfreeze it first.
unfreeze(name, path=path)
cmd = 'lxc-stop'
if kill:
cmd += ' -k'
ret = _change_state(cmd, name, 'stopped', use_vt=use_vt, path=path)
ret['state']['old'] = orig_state
return ret
def freeze(name, **kwargs):
'''
Freeze the named container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
start : False
If ``True`` and the container is stopped, the container will be started
before attempting to freeze.
.. versionadded:: 2015.5.0
use_vt
run the command through VT
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.freeze name
'''
use_vt = kwargs.get('use_vt', None)
path = kwargs.get('path', None)
_ensure_exists(name, path=path)
orig_state = state(name, path=path)
start_ = kwargs.get('start', False)
if orig_state == 'stopped':
if not start_:
raise CommandExecutionError(
'Container \'{0}\' is stopped'.format(name)
)
start(name, path=path)
cmd = 'lxc-freeze'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
ret = _change_state(cmd, name, 'frozen', use_vt=use_vt, path=path)
if orig_state == 'stopped' and start_:
ret['state']['old'] = orig_state
ret['started'] = True
ret['state']['new'] = state(name, path=path)
return ret
def unfreeze(name, path=None, use_vt=None):
'''
Unfreeze the named container.
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
use_vt
run the command through VT
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.unfreeze name
'''
_ensure_exists(name, path=path)
if state(name, path=path) == 'stopped':
raise CommandExecutionError(
'Container \'{0}\' is stopped'.format(name)
)
cmd = 'lxc-unfreeze'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
return _change_state(cmd, name, 'running', path=path, use_vt=use_vt)
def destroy(name, stop=False, path=None):
'''
Destroy the named container.
.. warning::
Destroys all data associated with the container.
path
path to the container parent directory (default: /var/lib/lxc)
.. versionadded:: 2015.8.0
stop : False
If ``True``, the container will be destroyed even if it is
running/frozen.
.. versionchanged:: 2015.5.0
Default value changed to ``False``. This more closely matches the
behavior of ``lxc-destroy(1)``, and also makes it less likely that
an accidental command will destroy a running container that was
being used for important things.
CLI Examples:
.. code-block:: bash
salt '*' lxc.destroy foo
salt '*' lxc.destroy foo stop=True
'''
_ensure_exists(name, path=path)
if not stop and state(name, path=path) != 'stopped':
raise CommandExecutionError(
'Container \'{0}\' is not stopped'.format(name)
)
return _change_state('lxc-destroy', name, None, path=path)
# Compatibility between LXC and nspawn
remove = salt.utils.functools.alias_function(destroy, 'remove')
def exists(name, path=None):
'''
Returns whether the named container exists.
path
path to the container parent directory (default: /var/lib/lxc)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.exists name
'''
_exists = name in ls_(path=path)
# container may be just created but we did cached earlier the
# lxc-ls results
if not _exists:
_exists = name in ls_(cache=False, path=path)
return _exists
def state(name, path=None):
'''
Returns the state of a container.
path
path to the container parent directory (default: /var/lib/lxc)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.state name
'''
# Don't use _ensure_exists() here, it will mess with _change_state()
cachekey = 'lxc.state.{0}{1}'.format(name, path)
try:
return __context__[cachekey]
except KeyError:
if not exists(name, path=path):
__context__[cachekey] = None
else:
cmd = 'lxc-info'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0}'.format(name)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
if ret['retcode'] != 0:
_clear_context()
raise CommandExecutionError(
'Unable to get state of container \'{0}\''.format(name)
)
c_infos = ret['stdout'].splitlines()
c_state = None
for c_info in c_infos:
stat = c_info.split(':')
if stat[0].lower() == 'state':
c_state = stat[1].strip().lower()
break
__context__[cachekey] = c_state
return __context__[cachekey]
def get_parameter(name, parameter, path=None):
'''
Returns the value of a cgroup parameter for a container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.get_parameter container_name memory.limit_in_bytes
'''
_ensure_exists(name, path=path)
cmd = 'lxc-cgroup'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0} {1}'.format(name, parameter)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
if ret['retcode'] != 0:
raise CommandExecutionError(
'Unable to retrieve value for \'{0}\''.format(parameter)
)
return ret['stdout'].strip()
def set_parameter(name, parameter, value, path=None):
'''
Set the value of a cgroup parameter for a container.
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.set_parameter name parameter value
'''
if not exists(name, path=path):
return None
cmd = 'lxc-cgroup'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0} {1} {2}'.format(name, parameter, value)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
if ret['retcode'] != 0:
return False
else:
return True
def info(name, path=None):
'''
Returns information about a container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.info name
'''
cachekey = 'lxc.info.{0}{1}'.format(name, path)
try:
return __context__[cachekey]
except KeyError:
_ensure_exists(name, path=path)
cpath = get_root_path(path)
try:
conf_file = os.path.join(cpath, name, 'config')
except AttributeError:
conf_file = os.path.join(cpath, six.text_type(name), 'config')
if not os.path.isfile(conf_file):
raise CommandExecutionError(
'LXC config file {0} does not exist'.format(conf_file)
)
ret = {}
config = []
with salt.utils.files.fopen(conf_file) as fp_:
for line in fp_:
line = salt.utils.stringutils.to_unicode(line)
comps = [x.strip() for x in
line.split('#', 1)[0].strip().split('=', 1)]
if len(comps) == 2:
config.append(tuple(comps))
ifaces = []
current = None
for key, val in config:
if key == 'lxc.network.type':
current = {'type': val}
ifaces.append(current)
elif not current:
continue
elif key.startswith('lxc.network.'):
current[key.replace('lxc.network.', '', 1)] = val
if ifaces:
ret['nics'] = ifaces
ret['rootfs'] = next(
(x[1] for x in config if x[0] == 'lxc.rootfs'),
None
)
ret['state'] = state(name, path=path)
ret['ips'] = []
ret['public_ips'] = []
ret['private_ips'] = []
ret['public_ipv4_ips'] = []
ret['public_ipv6_ips'] = []
ret['private_ipv4_ips'] = []
ret['private_ipv6_ips'] = []
ret['ipv4_ips'] = []
ret['ipv6_ips'] = []
ret['size'] = None
ret['config'] = conf_file
if ret['state'] == 'running':
try:
limit = int(get_parameter(name, 'memory.limit_in_bytes'))
except (CommandExecutionError, TypeError, ValueError):
limit = 0
try:
usage = int(get_parameter(name, 'memory.usage_in_bytes'))
except (CommandExecutionError, TypeError, ValueError):
usage = 0
free = limit - usage
ret['memory_limit'] = limit
ret['memory_free'] = free
size = run_stdout(name, 'df /', path=path, python_shell=False)
# The size is the 2nd column of the last line
ret['size'] = size.splitlines()[-1].split()[1]
# First try iproute2
ip_cmd = run_all(
name, 'ip link show', path=path, python_shell=False)
if ip_cmd['retcode'] == 0:
ip_data = ip_cmd['stdout']
ip_cmd = run_all(
name, 'ip addr show', path=path, python_shell=False)
ip_data += '\n' + ip_cmd['stdout']
ip_data = salt.utils.network._interfaces_ip(ip_data)
else:
# That didn't work, try ifconfig
ip_cmd = run_all(
name, 'ifconfig', path=path, python_shell=False)
if ip_cmd['retcode'] == 0:
ip_data = \
salt.utils.network._interfaces_ifconfig(
ip_cmd['stdout'])
else:
# Neither was successful, give up
log.warning(
'Unable to run ip or ifconfig in container \'%s\'', name
)
ip_data = {}
ret['ipv4_ips'] = salt.utils.network.ip_addrs(
include_loopback=True,
interface_data=ip_data
)
ret['ipv6_ips'] = salt.utils.network.ip_addrs6(
include_loopback=True,
interface_data=ip_data
)
ret['ips'] = ret['ipv4_ips'] + ret['ipv6_ips']
for address in ret['ipv4_ips']:
if address == '127.0.0.1':
ret['private_ips'].append(address)
ret['private_ipv4_ips'].append(address)
elif salt.utils.cloud.is_public_ip(address):
ret['public_ips'].append(address)
ret['public_ipv4_ips'].append(address)
else:
ret['private_ips'].append(address)
ret['private_ipv4_ips'].append(address)
for address in ret['ipv6_ips']:
if address == '::1' or address.startswith('fe80'):
ret['private_ips'].append(address)
ret['private_ipv6_ips'].append(address)
else:
ret['public_ips'].append(address)
ret['public_ipv6_ips'].append(address)
for key in [x for x in ret if x == 'ips' or x.endswith('ips')]:
ret[key].sort(key=_ip_sort)
__context__[cachekey] = ret
return __context__[cachekey]
def set_password(name, users, password, encrypted=True, path=None):
'''
.. versionchanged:: 2015.5.0
Function renamed from ``set_pass`` to ``set_password``. Additionally,
this function now supports (and defaults to using) a password hash
instead of a plaintext password.
Set the password of one or more system users inside containers
users
Comma-separated list (or python list) of users to change password
password
Password to set for the specified user(s)
encrypted : True
If true, ``password`` must be a password hash. Set to ``False`` to set
a plaintext password (not recommended).
.. versionadded:: 2015.5.0
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.set_pass container-name root '$6$uJ2uAyLU$KoI67t8As/0fXtJOPcHKGXmUpcoYUcVR2K6x93walnShTCQvjRwq25yIkiCBOqgbfdKQSFnAo28/ek6716vEV1'
salt '*' lxc.set_pass container-name root foo encrypted=False
'''
def _bad_user_input():
raise SaltInvocationError('Invalid input for \'users\' parameter')
if not isinstance(users, list):
try:
users = users.split(',')
except AttributeError:
_bad_user_input()
if not users:
_bad_user_input()
failed_users = []
for user in users:
result = retcode(name,
'chpasswd{0}'.format(' -e' if encrypted else ''),
stdin=':'.join((user, password)),
python_shell=False,
path=path,
chroot_fallback=True,
output_loglevel='quiet')
if result != 0:
failed_users.append(user)
if failed_users:
raise CommandExecutionError(
'Password change failed for the following user(s): {0}'
.format(', '.join(failed_users))
)
return True
set_pass = salt.utils.functools.alias_function(set_password, 'set_pass')
def update_lxc_conf(name, lxc_conf, lxc_conf_unset, path=None):
'''
Edit LXC configuration options
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.update_lxc_conf ubuntu \\
lxc_conf="[{'network.ipv4.ip':'10.0.3.5'}]" \\
lxc_conf_unset="['lxc.utsname']"
'''
_ensure_exists(name, path=path)
cpath = get_root_path(path)
lxc_conf_p = os.path.join(cpath, name, 'config')
if not os.path.exists(lxc_conf_p):
raise SaltInvocationError(
'Configuration file {0} does not exist'.format(lxc_conf_p)
)
changes = {'edited': [], 'added': [], 'removed': []}
ret = {'changes': changes, 'result': True, 'comment': ''}
# do not use salt.utils.files.fopen !
with salt.utils.files.fopen(lxc_conf_p, 'r') as fic:
filtered_lxc_conf = []
for row in lxc_conf:
if not row:
continue
for conf in row:
filtered_lxc_conf.append((conf.strip(),
row[conf].strip()))
ret['comment'] = 'lxc.conf is up to date'
lines = []
orig_config = salt.utils.stringutils.to_unicode(fic.read())
for line in orig_config.splitlines():
if line.startswith('#') or not line.strip():
lines.append([line, ''])
else:
line = line.split('=')
index = line.pop(0)
val = (index.strip(), '='.join(line).strip())
if val not in lines:
lines.append(val)
for key, item in filtered_lxc_conf:
matched = False
for idx, line in enumerate(lines[:]):
if line[0] == key:
matched = True
lines[idx] = (key, item)
if '='.join(line[1:]).strip() != item.strip():
changes['edited'].append(
({line[0]: line[1:]}, {key: item}))
break
if not matched:
if (key, item) not in lines:
lines.append((key, item))
changes['added'].append({key: item})
dest_lxc_conf = []
# filter unset
if lxc_conf_unset:
for line in lines:
for opt in lxc_conf_unset:
if (
not line[0].startswith(opt) and
line not in dest_lxc_conf
):
dest_lxc_conf.append(line)
else:
changes['removed'].append(opt)
else:
dest_lxc_conf = lines
conf = ''
for key, val in dest_lxc_conf:
if not val:
conf += '{0}\n'.format(key)
else:
conf += '{0} = {1}\n'.format(key.strip(), val.strip())
conf_changed = conf != orig_config
chrono = datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S')
if conf_changed:
# DO NOT USE salt.utils.files.fopen here, i got (kiorky)
# problems with lxc configs which were wiped !
with salt.utils.files.fopen('{0}.{1}'.format(lxc_conf_p, chrono), 'w') as wfic:
wfic.write(salt.utils.stringutils.to_str(conf))
with salt.utils.files.fopen(lxc_conf_p, 'w') as wfic:
wfic.write(salt.utils.stringutils.to_str(conf))
ret['comment'] = 'Updated'
ret['result'] = True
if not any(changes[x] for x in changes):
# Ensure an empty changes dict if nothing was modified
ret['changes'] = {}
return ret
def set_dns(name, dnsservers=None, searchdomains=None, path=None):
'''
.. versionchanged:: 2015.5.0
The ``dnsservers`` and ``searchdomains`` parameters can now be passed
as a comma-separated list.
Update /etc/resolv.confo
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.set_dns ubuntu "['8.8.8.8', '4.4.4.4']"
'''
if dnsservers is None:
dnsservers = ['8.8.8.8', '4.4.4.4']
elif not isinstance(dnsservers, list):
try:
dnsservers = dnsservers.split(',')
except AttributeError:
raise SaltInvocationError(
'Invalid input for \'dnsservers\' parameter'
)
if searchdomains is None:
searchdomains = []
elif not isinstance(searchdomains, list):
try:
searchdomains = searchdomains.split(',')
except AttributeError:
raise SaltInvocationError(
'Invalid input for \'searchdomains\' parameter'
)
dns = ['nameserver {0}'.format(x) for x in dnsservers]
dns.extend(['search {0}'.format(x) for x in searchdomains])
dns = '\n'.join(dns) + '\n'
# we may be using resolvconf in the container
# We need to handle that case with care:
# - we create the resolv.conf runtime directory (the
# linked directory) as anyway it will be shadowed when the real
# runned tmpfs mountpoint will be mounted.
# ( /etc/resolv.conf -> ../run/resolvconf/resolv.conf)
# Indeed, it can save us in any other case (running, eg, in a
# bare chroot when repairing or preparing the container for
# operation.
# - We also teach resolvconf to use the aforementioned dns.
# - We finally also set /etc/resolv.conf in all cases
rstr = __salt__['test.random_hash']()
# no tmp here, apparmor won't let us execute !
script = '/sbin/{0}_dns.sh'.format(rstr)
DNS_SCRIPT = "\n".join([
# 'set -x',
'#!/usr/bin/env bash',
'if [ -h /etc/resolv.conf ];then',
' if [ "x$(readlink /etc/resolv.conf)"'
' = "x../run/resolvconf/resolv.conf" ];then',
' if [ ! -d /run/resolvconf/ ];then',
' mkdir -p /run/resolvconf',
' fi',
' cat > /etc/resolvconf/resolv.conf.d/head <<EOF',
dns,
'EOF',
'',
' fi',
'fi',
'cat > /etc/resolv.conf <<EOF',
dns,
'EOF',
''])
result = run_all(
name, 'tee {0}'.format(script), path=path,
stdin=DNS_SCRIPT, python_shell=True)
if result['retcode'] == 0:
result = run_all(
name, 'sh -c "chmod +x {0};{0}"'.format(script),
path=path, python_shell=True)
# blindly delete the setter file
run_all(name,
'sh -c \'if [ -f "{0}" ];then rm -f "{0}";fi\''.format(script),
path=path, python_shell=True)
if result['retcode'] != 0:
error = ('Unable to write to /etc/resolv.conf in container \'{0}\''
.format(name))
if result['stderr']:
error += ': {0}'.format(result['stderr'])
raise CommandExecutionError(error)
return True
def running_systemd(name, cache=True, path=None):
'''
Determine if systemD is running
path
path to the container parent
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.running_systemd ubuntu
'''
k = 'lxc.systemd.test.{0}{1}'.format(name, path)
ret = __context__.get(k, None)
if ret is None or not cache:
rstr = __salt__['test.random_hash']()
# no tmp here, apparmor won't let us execute !
script = '/sbin/{0}_testsystemd.sh'.format(rstr)
# ubuntu already had since trusty some bits of systemd but was
# still using upstart ...
# we need to be a bit more careful that just testing that systemd
# is present
_script = textwrap.dedent(
'''\
#!/usr/bin/env bash
set -x
if ! command -v systemctl 1>/dev/null 2>/dev/null;then exit 2;fi
for i in \\
/run/systemd/journal/dev-log\\
/run/systemd/journal/flushed\\
/run/systemd/journal/kernel-seqnum\\
/run/systemd/journal/socket\\
/run/systemd/journal/stdout\\
/var/run/systemd/journal/dev-log\\
/var/run/systemd/journal/flushed\\
/var/run/systemd/journal/kernel-seqnum\\
/var/run/systemd/journal/socket\\
/var/run/systemd/journal/stdout\\
;do\\
if test -e ${i};then exit 0;fi
done
if test -d /var/systemd/system;then exit 0;fi
exit 2
''')
result = run_all(
name, 'tee {0}'.format(script), path=path,
stdin=_script, python_shell=True)
if result['retcode'] == 0:
result = run_all(name,
'sh -c "chmod +x {0};{0}"'''.format(script),
path=path,
python_shell=True)
else:
raise CommandExecutionError(
'lxc {0} failed to copy initd tester'.format(name))
run_all(name,
'sh -c \'if [ -f "{0}" ];then rm -f "{0}";fi\''
''.format(script),
path=path,
ignore_retcode=True,
python_shell=True)
if result['retcode'] != 0:
error = ('Unable to determine if the container \'{0}\''
' was running systemd, assmuming it is not.'
''.format(name))
if result['stderr']:
error += ': {0}'.format(result['stderr'])
# only cache result if we got a known exit code
if result['retcode'] in (0, 2):
__context__[k] = ret = not result['retcode']
return ret
def systemd_running_state(name, path=None):
'''
Get the operational state of a systemd based container
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.systemd_running_state ubuntu
'''
try:
ret = run_all(name,
'systemctl is-system-running',
path=path,
ignore_retcode=True)['stdout']
except CommandExecutionError:
ret = ''
return ret
def test_sd_started_state(name, path=None):
'''
Test if a systemd container is fully started
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.test_sd_started_state ubuntu
'''
qstate = systemd_running_state(name, path=path)
if qstate in ('initializing', 'starting'):
return False
elif qstate == '':
return None
else:
return True
def test_bare_started_state(name, path=None):
'''
Test if a non systemd container is fully started
For now, it consists only to test if the container is attachable
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.test_bare_started_state ubuntu
'''
try:
ret = run_all(
name, 'ls', path=path, ignore_retcode=True
)['retcode'] == 0
except (CommandExecutionError,):
ret = None
return ret
def wait_started(name, path=None, timeout=300):
'''
Check that the system has fully inited
This is actually very important for systemD based containers
see https://github.com/saltstack/salt/issues/23847
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.wait_started ubuntu
'''
if not exists(name, path=path):
raise CommandExecutionError(
'Container {0} does does exists'.format(name))
if not state(name, path=path) == 'running':
raise CommandExecutionError(
'Container {0} is not running'.format(name))
ret = False
if running_systemd(name, path=path):
test_started = test_sd_started_state
logger = log.error
else:
test_started = test_bare_started_state
logger = log.debug
now = time.time()
expire = now + timeout
now = time.time()
started = test_started(name, path=path)
while time.time() < expire and not started:
time.sleep(0.3)
started = test_started(name, path=path)
if started is None:
logger(
'Assuming %s is started, although we failed to detect that'
' is fully started correctly', name)
ret = True
else:
ret = started
return ret
def _needs_install(name, path=None):
ret = 0
has_minion = retcode(name,
'which salt-minion',
path=path,
ignore_retcode=True)
# we assume that installing is when no minion is running
# but testing the executable presence is not enougth for custom
# installs where the bootstrap can do much more than installing
# the bare salt binaries.
if has_minion:
processes = run_stdout(name, "ps aux", path=path)
if 'salt-minion' not in processes:
ret = 1
else:
retcode(name, 'salt-call --local service.stop salt-minion')
else:
ret = 1
return ret
def bootstrap(name,
config=None,
approve_key=True,
install=True,
pub_key=None,
priv_key=None,
bootstrap_url=None,
force_install=False,
unconditional_install=False,
path=None,
bootstrap_delay=None,
bootstrap_args=None,
bootstrap_shell=None):
'''
Install and configure salt in a container.
config
Minion configuration options. By default, the ``master`` option is set
to the target host's master.
approve_key
Request a pre-approval of the generated minion key. Requires
that the salt-master be configured to either auto-accept all keys or
expect a signing request from the target host. Default: ``True``
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
pub_key
Explicit public key to pressed the minion with (optional).
This can be either a filepath or a string representing the key
priv_key
Explicit private key to pressed the minion with (optional).
This can be either a filepath or a string representing the key
bootstrap_delay
Delay in seconds between end of container creation and bootstrapping.
Useful when waiting for container to obtain a DHCP lease.
.. versionadded:: 2015.5.0
bootstrap_url
url, content or filepath to the salt bootstrap script
bootstrap_args
salt bootstrap script arguments
bootstrap_shell
shell to execute the script into
install
Whether to attempt a full installation of salt-minion if needed.
force_install
Force installation even if salt-minion is detected,
this is the way to run vendor bootstrap scripts even
if a salt minion is already present in the container
unconditional_install
Run the script even if the container seems seeded
CLI Examples:
.. code-block:: bash
salt 'minion' lxc.bootstrap container_name [config=config_data] \\
[approve_key=(True|False)] [install=(True|False)]
'''
wait_started(name, path=path)
if bootstrap_delay is not None:
try:
log.info('LXC %s: bootstrap_delay: %s', name, bootstrap_delay)
time.sleep(bootstrap_delay)
except TypeError:
# Bad input, but assume since a value was passed that
# a delay was desired, and sleep for 5 seconds
time.sleep(5)
c_info = info(name, path=path)
if not c_info:
return None
# default set here as we cannot set them
# in def as it can come from a chain of procedures.
if bootstrap_args:
# custom bootstrap args can be totally customized, and user could
# have inserted the placeholder for the config directory.
# For example, some salt bootstrap script do not use at all -c
if '{0}' not in bootstrap_args:
bootstrap_args += ' -c {0}'
else:
bootstrap_args = '-c {0}'
if not bootstrap_shell:
bootstrap_shell = 'sh'
orig_state = _ensure_running(name, path=path)
if not orig_state:
return orig_state
if not force_install:
needs_install = _needs_install(name, path=path)
else:
needs_install = True
seeded = retcode(name,
'test -e \'{0}\''.format(SEED_MARKER),
path=path,
chroot_fallback=True,
ignore_retcode=True) == 0
tmp = tempfile.mkdtemp()
if seeded and not unconditional_install:
ret = True
else:
ret = False
cfg_files = __salt__['seed.mkconfig'](
config, tmp=tmp, id_=name, approve_key=approve_key,
pub_key=pub_key, priv_key=priv_key)
if needs_install or force_install or unconditional_install:
if install:
rstr = __salt__['test.random_hash']()
configdir = '/var/tmp/.c_{0}'.format(rstr)
cmd = 'install -m 0700 -d {0}'.format(configdir)
if run_all(
name, cmd, path=path, python_shell=False
)['retcode'] != 0:
log.error('tmpdir %s creation failed %s', configdir, cmd)
return False
bs_ = __salt__['config.gather_bootstrap_script'](
bootstrap=bootstrap_url)
script = '/sbin/{0}_bootstrap.sh'.format(rstr)
copy_to(name, bs_, script, path=path)
result = run_all(name,
'sh -c "chmod +x {0}"'.format(script),
path=path,
python_shell=True)
copy_to(name, cfg_files['config'],
os.path.join(configdir, 'minion'),
path=path)
copy_to(name, cfg_files['privkey'],
os.path.join(configdir, 'minion.pem'),
path=path)
copy_to(name, cfg_files['pubkey'],
os.path.join(configdir, 'minion.pub'),
path=path)
bootstrap_args = bootstrap_args.format(configdir)
cmd = ('{0} {2} {1}'
.format(bootstrap_shell,
bootstrap_args.replace("'", "''"),
script))
# log ASAP the forged bootstrap command which can be wrapped
# out of the output in case of unexpected problem
log.info('Running %s in LXC container \'%s\'', cmd, name)
ret = retcode(name, cmd, output_loglevel='info',
path=path, use_vt=True) == 0
run_all(name,
'sh -c \'if [ -f "{0}" ];then rm -f "{0}";fi\''
''.format(script),
path=path,
ignore_retcode=True,
python_shell=True)
else:
ret = False
else:
minion_config = salt.config.minion_config(cfg_files['config'])
pki_dir = minion_config['pki_dir']
copy_to(name,
cfg_files['config'],
'/etc/salt/minion',
path=path)
copy_to(name,
cfg_files['privkey'],
os.path.join(pki_dir, 'minion.pem'),
path=path)
copy_to(name,
cfg_files['pubkey'],
os.path.join(pki_dir, 'minion.pub'),
path=path)
run(name,
'salt-call --local service.enable salt-minion',
path=path,
python_shell=False)
ret = True
shutil.rmtree(tmp)
if orig_state == 'stopped':
stop(name, path=path)
elif orig_state == 'frozen':
freeze(name, path=path)
# mark seeded upon successful install
if ret:
run(name,
'touch \'{0}\''.format(SEED_MARKER),
path=path,
python_shell=False)
return ret
def attachable(name, path=None):
'''
Return True if the named container can be attached to via the lxc-attach
command
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt 'minion' lxc.attachable ubuntu
'''
cachekey = 'lxc.attachable{0}{1}'.format(name, path)
try:
return __context__[cachekey]
except KeyError:
_ensure_exists(name, path=path)
# Can't use run() here because it uses attachable() and would
# endlessly recurse, resulting in a traceback
log.debug('Checking if LXC container %s is attachable', name)
cmd = 'lxc-attach'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' --clear-env -n {0} -- /usr/bin/env'.format(name)
result = __salt__['cmd.retcode'](cmd,
python_shell=False,
output_loglevel='quiet',
ignore_retcode=True) == 0
__context__[cachekey] = result
return __context__[cachekey]
def _run(name,
cmd,
output=None,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=None,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
Common logic for lxc.run functions
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
'''
orig_state = state(name, path=path)
try:
if attachable(name, path=path):
ret = __salt__['container_resource.run'](
name,
cmd,
path=path,
container_type=__virtualname__,
exec_driver=EXEC_DRIVER,
output=output,
no_start=no_start,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
ignore_retcode=ignore_retcode,
use_vt=use_vt,
keep_env=keep_env)
else:
if not chroot_fallback:
raise CommandExecutionError(
'{0} is not attachable.'.format(name))
rootfs = info(name, path=path).get('rootfs')
# Set context var to make cmd.run_chroot run cmd.run instead of
# cmd.run_all.
__context__['cmd.run_chroot.func'] = __salt__['cmd.run']
ret = __salt__['cmd.run_chroot'](rootfs,
cmd,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
ignore_retcode=ignore_retcode)
except Exception:
raise
finally:
# Make sure we honor preserve_state, even if there was an exception
new_state = state(name, path=path)
if preserve_state:
if orig_state == 'stopped' and new_state != 'stopped':
stop(name, path=path)
elif orig_state == 'frozen' and new_state != 'frozen':
freeze(name, start=True, path=path)
if output in (None, 'all'):
return ret
else:
return ret[output]
def run(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.8.0
Run :mod:`cmd.run <salt.modules.cmdmod.run>` within a container
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed in stderr if the command being run
does not exist. If no output is returned using this function, try using
:mod:`lxc.run_stderr <salt.modules.lxc.run_stderr>` or
:mod:`lxc.run_all <salt.modules.lxc.run_all>`.
name
Name of the container in which to run the command
cmd
Command to run
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console. Assumes
``output=all``.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
CLI Example:
.. code-block:: bash
salt myminion lxc.run mycontainer 'ifconfig -a'
'''
return _run(name,
cmd,
path=path,
output=None,
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def run_stdout(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.5.0
Run :mod:`cmd.run_stdout <salt.modules.cmdmod.run_stdout>` within a container
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed in stderr if the command being run
does not exist. If no output is returned using this function, try using
:mod:`lxc.run_stderr <salt.modules.lxc.run_stderr>` or
:mod:`lxc.run_all <salt.modules.lxc.run_all>`.
name
Name of the container in which to run the command
cmd
Command to run
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console
``output=all``.
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
CLI Example:
.. code-block:: bash
salt myminion lxc.run_stdout mycontainer 'ifconfig -a'
'''
return _run(name,
cmd,
path=path,
output='stdout',
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def run_stderr(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.5.0
Run :mod:`cmd.run_stderr <salt.modules.cmdmod.run_stderr>` within a container
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed if the command being run does not
exist.
name
Name of the container in which to run the command
cmd
Command to run
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console
``output=all``.
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
CLI Example:
.. code-block:: bash
salt myminion lxc.run_stderr mycontainer 'ip addr show'
'''
return _run(name,
cmd,
path=path,
output='stderr',
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def retcode(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.5.0
Run :mod:`cmd.retcode <salt.modules.cmdmod.retcode>` within a container
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed in stderr if the command being run
does not exist. If the retcode is nonzero and not what was expected,
try using :mod:`lxc.run_stderr <salt.modules.lxc.run_stderr>`
or :mod:`lxc.run_all <salt.modules.lxc.run_all>`.
name
Name of the container in which to run the command
cmd
Command to run
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console
``output=all``.
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
CLI Example:
.. code-block:: bash
salt myminion lxc.retcode mycontainer 'ip addr show'
'''
return _run(name,
cmd,
output='retcode',
path=path,
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def run_all(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.5.0
Run :mod:`cmd.run_all <salt.modules.cmdmod.run_all>` within a container
.. note::
While the command is run within the container, it is initiated from the
host. Therefore, the PID in the return dict is from the host, not from
the container.
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed in stderr if the command being run
does not exist.
name
Name of the container in which to run the command
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
cmd
Command to run
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console
``output=all``.
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
CLI Example:
.. code-block:: bash
salt myminion lxc.run_all mycontainer 'ip addr show'
'''
return _run(name,
cmd,
output='all',
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
path=path,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def _get_md5(name, path):
'''
Get the MD5 checksum of a file from a container
'''
output = run_stdout(name, 'md5sum "{0}"'.format(path),
chroot_fallback=True,
ignore_retcode=True)
try:
return output.split()[0]
except IndexError:
# Destination file does not exist or could not be accessed
return None
def copy_to(name, source, dest, overwrite=False, makedirs=False, path=None):
'''
.. versionchanged:: 2015.8.0
Function renamed from ``lxc.cp`` to ``lxc.copy_to`` for consistency
with other container types. ``lxc.cp`` will continue to work, however.
For versions 2015.2.x and earlier, use ``lxc.cp``.
Copy a file or directory from the host into a container
name
Container name
source
File to be copied to the container
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
dest
Destination on the container. Must be an absolute path.
.. versionchanged:: 2015.5.0
If the destination is a directory, the file will be copied into
that directory.
overwrite : False
Unless this option is set to ``True``, then if a file exists at the
location specified by the ``dest`` argument, an error will be raised.
.. versionadded:: 2015.8.0
makedirs : False
Create the parent directory on the container if it does not already
exist.
.. versionadded:: 2015.5.0
CLI Example:
.. code-block:: bash
salt 'minion' lxc.copy_to /tmp/foo /root/foo
salt 'minion' lxc.cp /tmp/foo /root/foo
'''
_ensure_running(name, no_start=True, path=path)
return __salt__['container_resource.copy_to'](
name,
source,
dest,
container_type=__virtualname__,
path=path,
exec_driver=EXEC_DRIVER,
overwrite=overwrite,
makedirs=makedirs)
cp = salt.utils.functools.alias_function(copy_to, 'cp')
def read_conf(conf_file, out_format='simple'):
'''
Read in an LXC configuration file. By default returns a simple, unsorted
dict, but can also return a more detailed structure including blank lines
and comments.
out_format:
set to 'simple' if you need the old and unsupported behavior.
This won't support the multiple lxc values (eg: multiple network nics)
CLI Examples:
.. code-block:: bash
salt 'minion' lxc.read_conf /etc/lxc/mycontainer.conf
salt 'minion' lxc.read_conf /etc/lxc/mycontainer.conf out_format=commented
'''
ret_commented = []
ret_simple = {}
with salt.utils.files.fopen(conf_file, 'r') as fp_:
for line in salt.utils.data.decode(fp_.readlines()):
if '=' not in line:
ret_commented.append(line)
continue
comps = line.split('=')
value = '='.join(comps[1:]).strip()
comment = None
if value.strip().startswith('#'):
vcomps = value.strip().split('#')
value = vcomps[1].strip()
comment = '#'.join(vcomps[1:]).strip()
ret_commented.append({comps[0].strip(): {
'value': value,
'comment': comment,
}})
else:
ret_commented.append({comps[0].strip(): value})
ret_simple[comps[0].strip()] = value
if out_format == 'simple':
return ret_simple
return ret_commented
def write_conf(conf_file, conf):
'''
Write out an LXC configuration file
This is normally only used internally. The format of the data structure
must match that which is returned from ``lxc.read_conf()``, with
``out_format`` set to ``commented``.
An example might look like:
.. code-block:: python
[
{'lxc.utsname': '$CONTAINER_NAME'},
'# This is a commented line\\n',
'\\n',
{'lxc.mount': '$CONTAINER_FSTAB'},
{'lxc.rootfs': {'comment': 'This is another test',
'value': 'This is another test'}},
'\\n',
{'lxc.network.type': 'veth'},
{'lxc.network.flags': 'up'},
{'lxc.network.link': 'br0'},
{'lxc.network.mac': '$CONTAINER_MACADDR'},
{'lxc.network.ipv4': '$CONTAINER_IPADDR'},
{'lxc.network.name': '$CONTAINER_DEVICENAME'},
]
CLI Example:
.. code-block:: bash
salt 'minion' lxc.write_conf /etc/lxc/mycontainer.conf \\
out_format=commented
'''
if not isinstance(conf, list):
raise SaltInvocationError('Configuration must be passed as a list')
# construct the content prior to write to the file
# to avoid half written configs
content = ''
for line in conf:
if isinstance(line, (six.text_type, six.string_types)):
content += line
elif isinstance(line, dict):
for key in list(line.keys()):
out_line = None
if isinstance(
line[key],
(six.text_type, six.string_types, six.integer_types, float)
):
out_line = ' = '.join((key, "{0}".format(line[key])))
elif isinstance(line[key], dict):
out_line = ' = '.join((key, line[key]['value']))
if 'comment' in line[key]:
out_line = ' # '.join((out_line, line[key]['comment']))
if out_line:
content += out_line
content += '\n'
with salt.utils.files.fopen(conf_file, 'w') as fp_:
fp_.write(salt.utils.stringutils.to_str(content))
return {}
def edit_conf(conf_file,
out_format='simple',
read_only=False,
lxc_config=None,
**kwargs):
'''
Edit an LXC configuration file. If a setting is already present inside the
file, its value will be replaced. If it does not exist, it will be appended
to the end of the file. Comments and blank lines will be kept in-tact if
they already exist in the file.
out_format:
Set to simple if you need backward compatibility (multiple items for a
simple key is not supported)
read_only:
return only the edited configuration without applying it
to the underlying lxc configuration file
lxc_config:
List of dict containning lxc configuration items
For network configuration, you also need to add the device it belongs
to, otherwise it will default to eth0.
Also, any change to a network parameter will result in the whole
network reconfiguration to avoid mismatchs, be aware of that !
After the file is edited, its contents will be returned. By default, it
will be returned in ``simple`` format, meaning an unordered dict (which
may not represent the actual file order). Passing in an ``out_format`` of
``commented`` will return a data structure which accurately represents the
order and content of the file.
CLI Example:
.. code-block:: bash
salt 'minion' lxc.edit_conf /etc/lxc/mycontainer.conf \\
out_format=commented lxc.network.type=veth
salt 'minion' lxc.edit_conf /etc/lxc/mycontainer.conf \\
out_format=commented \\
lxc_config="[{'lxc.network.name': 'eth0', \\
'lxc.network.ipv4': '1.2.3.4'},
{'lxc.network.name': 'eth2', \\
'lxc.network.ipv4': '1.2.3.5',\\
'lxc.network.gateway': '1.2.3.1'}]"
'''
data = []
try:
conf = read_conf(conf_file, out_format=out_format)
except Exception:
conf = []
if not lxc_config:
lxc_config = []
lxc_config = copy.deepcopy(lxc_config)
# search if we want to access net config
# in that case, we will replace all the net configuration
net_config = []
for lxc_kws in lxc_config + [kwargs]:
net_params = {}
for kwarg in [a for a in lxc_kws]:
if kwarg.startswith('__'):
continue
if kwarg.startswith('lxc.network.'):
net_params[kwarg] = lxc_kws[kwarg]
lxc_kws.pop(kwarg, None)
if net_params:
net_config.append(net_params)
nic_opts = salt.utils.odict.OrderedDict()
for params in net_config:
dev = params.get('lxc.network.name', DEFAULT_NIC)
dev_opts = nic_opts.setdefault(dev, salt.utils.odict.OrderedDict())
for param in params:
opt = param.replace('lxc.network.', '')
opt = {'hwaddr': 'mac'}.get(opt, opt)
dev_opts[opt] = params[param]
net_changes = []
if nic_opts:
net_changes = _config_list(conf, only_net=True,
**{'network_profile': DEFAULT_NIC,
'nic_opts': nic_opts})
if net_changes:
lxc_config.extend(net_changes)
for line in conf:
if not isinstance(line, dict):
data.append(line)
continue
else:
for key in list(line.keys()):
val = line[key]
if net_changes and key.startswith('lxc.network.'):
continue
found = False
for ix in range(len(lxc_config)):
kw = lxc_config[ix]
if key in kw:
found = True
data.append({key: kw[key]})
del kw[key]
if not found:
data.append({key: val})
for lxc_kws in lxc_config:
for kwarg in lxc_kws:
data.append({kwarg: lxc_kws[kwarg]})
if read_only:
return data
write_conf(conf_file, data)
return read_conf(conf_file, out_format)
def reboot(name, path=None):
'''
Reboot a container.
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Examples:
.. code-block:: bash
salt 'minion' lxc.reboot myvm
'''
ret = {'result': True,
'changes': {},
'comment': '{0} rebooted'.format(name)}
does_exist = exists(name, path=path)
if does_exist and (state(name, path=path) == 'running'):
try:
stop(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
ret['result'] = False
return ret
if does_exist and (state(name, path=path) != 'running'):
try:
start(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
ret['result'] = False
return ret
ret['changes'][name] = 'rebooted'
return ret
def reconfigure(name,
cpu=None,
cpuset=None,
cpushare=None,
memory=None,
profile=None,
network_profile=None,
nic_opts=None,
bridge=None,
gateway=None,
autostart=None,
utsname=None,
rootfs=None,
path=None,
**kwargs):
'''
Reconfigure a container.
This only applies to a few property
name
Name of the container.
utsname
utsname of the container.
.. versionadded:: 2016.3.0
rootfs
rootfs of the container.
.. versionadded:: 2016.3.0
cpu
Select a random number of cpu cores and assign it to the cpuset, if the
cpuset option is set then this option will be ignored
cpuset
Explicitly define the cpus this container will be bound to
cpushare
cgroups cpu shares.
autostart
autostart container on reboot
memory
cgroups memory limit, in MB.
(0 for nolimit, None for old default 1024MB)
gateway
the ipv4 gateway to use
the default does nothing more than lxcutils does
bridge
the bridge to use
the default does nothing more than lxcutils does
nic
Network interfaces profile (defined in config or pillar).
nic_opts
Extra options for network interfaces, will override
``{"eth0": {"mac": "aa:bb:cc:dd:ee:ff", "ipv4": "10.1.1.1", "ipv6": "2001:db8::ff00:42:8329"}}``
or
``{"eth0": {"mac": "aa:bb:cc:dd:ee:ff", "ipv4": "10.1.1.1/24", "ipv6": "2001:db8::ff00:42:8329"}}``
path
path to the container parent
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt-call -lall mc_lxc_fork.reconfigure foobar nic_opts="{'eth1': {'mac': '00:16:3e:dd:ee:44'}}" memory=4
'''
changes = {}
cpath = get_root_path(path)
path = os.path.join(cpath, name, 'config')
ret = {'name': name,
'comment': 'config for {0} up to date'.format(name),
'result': True,
'changes': changes}
profile = get_container_profile(copy.deepcopy(profile))
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, _marker)
profile_match = profile.pop(key, default)
# let kwarg overrides be the preferred choice
if kw_overrides_match is _marker:
return profile_match
return kw_overrides_match
if nic_opts is not None and not network_profile:
network_profile = DEFAULT_NIC
if autostart is not None:
autostart = select('autostart', autostart)
else:
autostart = 'keep'
if not utsname:
utsname = select('utsname', utsname)
if os.path.exists(path):
old_chunks = read_conf(path, out_format='commented')
make_kw = salt.utils.odict.OrderedDict([
('utsname', utsname),
('rootfs', rootfs),
('autostart', autostart),
('cpu', cpu),
('gateway', gateway),
('cpuset', cpuset),
('cpushare', cpushare),
('network_profile', network_profile),
('nic_opts', nic_opts),
('bridge', bridge)])
# match 0 and none as memory = 0 in lxc config is harmful
if memory:
make_kw['memory'] = memory
kw = salt.utils.odict.OrderedDict()
for key, val in six.iteritems(make_kw):
if val is not None:
kw[key] = val
new_cfg = _config_list(conf_tuples=old_chunks, **kw)
if new_cfg:
edit_conf(path, out_format='commented', lxc_config=new_cfg)
chunks = read_conf(path, out_format='commented')
if old_chunks != chunks:
ret['comment'] = '{0} lxc config updated'.format(name)
if state(name, path=path) == 'running':
cret = reboot(name, path=path)
ret['result'] = cret['result']
return ret
def apply_network_profile(name, network_profile, nic_opts=None, path=None):
'''
.. versionadded:: 2015.5.0
Apply a network profile to a container
network_profile
profile name or default values (dict)
nic_opts
values to override in defaults (dict)
indexed by nic card names
path
path to the container parent
.. versionadded:: 2015.8.0
CLI Examples:
.. code-block:: bash
salt 'minion' lxc.apply_network_profile web1 centos
salt 'minion' lxc.apply_network_profile web1 centos \\
nic_opts="{'eth0': {'mac': 'xx:xx:xx:xx:xx:xx'}}"
salt 'minion' lxc.apply_network_profile web1 \\
"{'eth0': {'mac': 'xx:xx:xx:xx:xx:yy'}}"
nic_opts="{'eth0': {'mac': 'xx:xx:xx:xx:xx:xx'}}"
The special case to disable use of ethernet nics:
.. code-block:: bash
salt 'minion' lxc.apply_network_profile web1 centos \\
"{eth0: {disable: true}}"
'''
cpath = get_root_path(path)
cfgpath = os.path.join(cpath, name, 'config')
before = []
with salt.utils.files.fopen(cfgpath, 'r') as fp_:
for line in fp_:
before.append(line)
lxcconfig = _LXCConfig(name=name, path=path)
old_net = lxcconfig._filter_data('lxc.network')
network_params = {}
for param in _network_conf(
conf_tuples=old_net,
network_profile=network_profile, nic_opts=nic_opts
):
network_params.update(param)
if network_params:
edit_conf(cfgpath, out_format='commented', **network_params)
after = []
with salt.utils.files.fopen(cfgpath, 'r') as fp_:
for line in fp_:
after.append(line)
diff = ''
for line in difflib.unified_diff(before,
after,
fromfile='before',
tofile='after'):
diff += line
return diff
def get_pid(name, path=None):
'''
Returns a container pid.
Throw an exception if the container isn't running.
CLI Example:
.. code-block:: bash
salt '*' lxc.get_pid name
'''
if name not in list_(limit='running', path=path):
raise CommandExecutionError('Container {0} is not running, can\'t determine PID'.format(name))
info = __salt__['cmd.run']('lxc-info -n {0}'.format(name)).split("\n")
pid = [line.split(':')[1].strip() for line in info if re.match(r'\s*PID', line)][0]
return pid
def add_veth(name, interface_name, bridge=None, path=None):
'''
Add a veth to a container.
Note : this function doesn't update the container config, just add the interface at runtime
name
Name of the container
interface_name
Name of the interface in the container
bridge
Name of the bridge to attach the interface to (facultative)
CLI Examples:
.. code-block:: bash
salt '*' lxc.add_veth container_name eth1 br1
salt '*' lxc.add_veth container_name eth1
'''
# Get container init PID
pid = get_pid(name, path=path)
# Generate a ramdom string for veth and ensure that is isn't present on the system
while True:
random_veth = 'veth'+''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(6))
if random_veth not in __salt__['network.interfaces']().keys():
break
# Check prerequisites
if not __salt__['file.directory_exists']('/var/run/'):
raise CommandExecutionError('Directory /var/run required for lxc.add_veth doesn\'t exists')
if not __salt__['file.file_exists']('/proc/{0}/ns/net'.format(pid)):
raise CommandExecutionError('Proc file for container {0} network namespace doesn\'t exists'.format(name))
if not __salt__['file.directory_exists']('/var/run/netns'):
__salt__['file.mkdir']('/var/run/netns')
# Ensure that the symlink is up to date (change on container restart)
if __salt__['file.is_link']('/var/run/netns/{0}'.format(name)):
__salt__['file.remove']('/var/run/netns/{0}'.format(name))
__salt__['file.symlink']('/proc/{0}/ns/net'.format(pid), '/var/run/netns/{0}'.format(name))
# Ensure that interface doesn't exists
interface_exists = 0 == __salt__['cmd.retcode']('ip netns exec {netns} ip address list {interface}'.format(
netns=name,
interface=interface_name
))
if interface_exists:
raise CommandExecutionError('Interface {interface} already exists in {container}'.format(
interface=interface_name,
container=name
))
# Create veth and bring it up
if __salt__['cmd.retcode']('ip link add name {veth} type veth peer name {veth}_c'.format(veth=random_veth)) != 0:
raise CommandExecutionError('Error while creating the veth pair {0}'.format(random_veth))
if __salt__['cmd.retcode']('ip link set dev {0} up'.format(random_veth)) != 0:
raise CommandExecutionError('Error while bringing up host-side veth {0}'.format(random_veth))
# Attach it to the container
attached = 0 == __salt__['cmd.retcode']('ip link set dev {veth}_c netns {container} name {interface_name}'.format(
veth=random_veth,
container=name,
interface_name=interface_name
))
if not attached:
raise CommandExecutionError('Error while attaching the veth {veth} to container {container}'.format(
veth=random_veth,
container=name
))
__salt__['file.remove']('/var/run/netns/{0}'.format(name))
if bridge is not None:
__salt__['bridge.addif'](bridge, random_veth)
|
saltstack/salt
|
salt/modules/lxc.py
|
list_
|
python
|
def list_(extra=False, limit=None, path=None):
'''
List containers classified by state
extra
Also get per-container specific info. This will change the return data.
Instead of returning a list of containers, a dictionary of containers
and each container's output from :mod:`lxc.info
<salt.modules.lxc.info>`.
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
limit
Return output matching a specific state (**frozen**, **running**, or
**stopped**).
.. versionadded:: 2015.5.0
CLI Examples:
.. code-block:: bash
salt '*' lxc.list
salt '*' lxc.list extra=True
salt '*' lxc.list limit=running
'''
ctnrs = ls_(path=path)
if extra:
stopped = {}
frozen = {}
running = {}
else:
stopped = []
frozen = []
running = []
ret = {'running': running,
'stopped': stopped,
'frozen': frozen}
for container in ctnrs:
cmd = 'lxc-info'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0}'.format(container)
c_info = __salt__['cmd.run'](
cmd,
python_shell=False,
output_loglevel='debug'
)
c_state = None
for line in c_info.splitlines():
stat = line.split(':')
if stat[0] in ('State', 'state'):
c_state = stat[1].strip()
break
if not c_state or (limit is not None and c_state.lower() != limit):
continue
if extra:
infos = info(container, path=path)
method = 'update'
value = {container: infos}
else:
method = 'append'
value = container
if c_state == 'STOPPED':
getattr(stopped, method)(value)
continue
if c_state == 'FROZEN':
getattr(frozen, method)(value)
continue
if c_state == 'RUNNING':
getattr(running, method)(value)
continue
if limit is not None:
return ret.get(limit, {} if extra else [])
return ret
|
List containers classified by state
extra
Also get per-container specific info. This will change the return data.
Instead of returning a list of containers, a dictionary of containers
and each container's output from :mod:`lxc.info
<salt.modules.lxc.info>`.
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
limit
Return output matching a specific state (**frozen**, **running**, or
**stopped**).
.. versionadded:: 2015.5.0
CLI Examples:
.. code-block:: bash
salt '*' lxc.list
salt '*' lxc.list extra=True
salt '*' lxc.list limit=running
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/lxc.py#L2150-L2235
|
[
"def info(name, path=None):\n '''\n Returns information about a container\n\n path\n path to the container parent directory\n default: /var/lib/lxc (system)\n\n .. versionadded:: 2015.8.0\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' lxc.info name\n '''\n cachekey = 'lxc.info.{0}{1}'.format(name, path)\n try:\n return __context__[cachekey]\n except KeyError:\n _ensure_exists(name, path=path)\n cpath = get_root_path(path)\n try:\n conf_file = os.path.join(cpath, name, 'config')\n except AttributeError:\n conf_file = os.path.join(cpath, six.text_type(name), 'config')\n\n if not os.path.isfile(conf_file):\n raise CommandExecutionError(\n 'LXC config file {0} does not exist'.format(conf_file)\n )\n\n ret = {}\n config = []\n with salt.utils.files.fopen(conf_file) as fp_:\n for line in fp_:\n line = salt.utils.stringutils.to_unicode(line)\n comps = [x.strip() for x in\n line.split('#', 1)[0].strip().split('=', 1)]\n if len(comps) == 2:\n config.append(tuple(comps))\n\n ifaces = []\n current = None\n\n for key, val in config:\n if key == 'lxc.network.type':\n current = {'type': val}\n ifaces.append(current)\n elif not current:\n continue\n elif key.startswith('lxc.network.'):\n current[key.replace('lxc.network.', '', 1)] = val\n if ifaces:\n ret['nics'] = ifaces\n\n ret['rootfs'] = next(\n (x[1] for x in config if x[0] == 'lxc.rootfs'),\n None\n )\n ret['state'] = state(name, path=path)\n ret['ips'] = []\n ret['public_ips'] = []\n ret['private_ips'] = []\n ret['public_ipv4_ips'] = []\n ret['public_ipv6_ips'] = []\n ret['private_ipv4_ips'] = []\n ret['private_ipv6_ips'] = []\n ret['ipv4_ips'] = []\n ret['ipv6_ips'] = []\n ret['size'] = None\n ret['config'] = conf_file\n\n if ret['state'] == 'running':\n try:\n limit = int(get_parameter(name, 'memory.limit_in_bytes'))\n except (CommandExecutionError, TypeError, ValueError):\n limit = 0\n try:\n usage = int(get_parameter(name, 'memory.usage_in_bytes'))\n except (CommandExecutionError, TypeError, ValueError):\n usage = 0\n free = limit - usage\n ret['memory_limit'] = limit\n ret['memory_free'] = free\n size = run_stdout(name, 'df /', path=path, python_shell=False)\n # The size is the 2nd column of the last line\n ret['size'] = size.splitlines()[-1].split()[1]\n\n # First try iproute2\n ip_cmd = run_all(\n name, 'ip link show', path=path, python_shell=False)\n if ip_cmd['retcode'] == 0:\n ip_data = ip_cmd['stdout']\n ip_cmd = run_all(\n name, 'ip addr show', path=path, python_shell=False)\n ip_data += '\\n' + ip_cmd['stdout']\n ip_data = salt.utils.network._interfaces_ip(ip_data)\n else:\n # That didn't work, try ifconfig\n ip_cmd = run_all(\n name, 'ifconfig', path=path, python_shell=False)\n if ip_cmd['retcode'] == 0:\n ip_data = \\\n salt.utils.network._interfaces_ifconfig(\n ip_cmd['stdout'])\n else:\n # Neither was successful, give up\n log.warning(\n 'Unable to run ip or ifconfig in container \\'%s\\'', name\n )\n ip_data = {}\n\n ret['ipv4_ips'] = salt.utils.network.ip_addrs(\n include_loopback=True,\n interface_data=ip_data\n )\n ret['ipv6_ips'] = salt.utils.network.ip_addrs6(\n include_loopback=True,\n interface_data=ip_data\n )\n ret['ips'] = ret['ipv4_ips'] + ret['ipv6_ips']\n for address in ret['ipv4_ips']:\n if address == '127.0.0.1':\n ret['private_ips'].append(address)\n ret['private_ipv4_ips'].append(address)\n elif salt.utils.cloud.is_public_ip(address):\n ret['public_ips'].append(address)\n ret['public_ipv4_ips'].append(address)\n else:\n ret['private_ips'].append(address)\n ret['private_ipv4_ips'].append(address)\n for address in ret['ipv6_ips']:\n if address == '::1' or address.startswith('fe80'):\n ret['private_ips'].append(address)\n ret['private_ipv6_ips'].append(address)\n else:\n ret['public_ips'].append(address)\n ret['public_ipv6_ips'].append(address)\n\n for key in [x for x in ret if x == 'ips' or x.endswith('ips')]:\n ret[key].sort(key=_ip_sort)\n __context__[cachekey] = ret\n return __context__[cachekey]\n",
"def ls_(active=None, cache=True, path=None):\n '''\n Return a list of the containers available on the minion\n\n path\n path to the container parent directory\n default: /var/lib/lxc (system)\n\n .. versionadded:: 2015.8.0\n\n active\n If ``True``, return only active (i.e. running) containers\n\n .. versionadded:: 2015.5.0\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' lxc.ls\n salt '*' lxc.ls active=True\n '''\n contextvar = 'lxc.ls{0}'.format(path)\n if active:\n contextvar += '.active'\n if cache and (contextvar in __context__):\n return __context__[contextvar]\n else:\n ret = []\n cmd = 'lxc-ls'\n if path:\n cmd += ' -P {0}'.format(pipes.quote(path))\n if active:\n cmd += ' --active'\n output = __salt__['cmd.run_stdout'](cmd, python_shell=False)\n for line in output.splitlines():\n ret.extend(line.split())\n __context__[contextvar] = ret\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Control Linux Containers via Salt
:depends: lxc package for distribution
lxc >= 1.0 (even beta alpha) is required
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import datetime
import copy
import string
import textwrap
import difflib
import logging
import tempfile
import os
import pipes
import time
import shutil
import re
import random
# Import salt libs
import salt.utils.args
import salt.utils.cloud
import salt.utils.data
import salt.utils.dictupdate
import salt.utils.files
import salt.utils.functools
import salt.utils.hashutils
import salt.utils.network
import salt.utils.odict
import salt.utils.path
import salt.utils.stringutils
from salt.exceptions import CommandExecutionError, SaltInvocationError
import salt.config
from salt.utils.versions import LooseVersion as _LooseVersion
# Import 3rd-party libs
from salt.ext import six
# pylint: disable=import-error,no-name-in-module
from salt.ext.six.moves import range # pylint: disable=redefined-builtin
from salt.ext.six.moves.urllib.parse import urlparse as _urlparse
# pylint: enable=import-error,no-name-in-module
# Set up logging
log = logging.getLogger(__name__)
# Don't shadow built-in's.
__func_alias__ = {
'list_': 'list',
'ls_': 'ls'
}
__virtualname__ = 'lxc'
DEFAULT_NIC = 'eth0'
DEFAULT_BR = 'br0'
SEED_MARKER = '/lxc.initial_seed'
EXEC_DRIVER = 'lxc-attach'
DEFAULT_PATH = '/var/lib/lxc'
_marker = object()
def __virtual__():
if salt.utils.path.which('lxc-start'):
return __virtualname__
# To speed up the whole thing, we decided to not use the
# subshell way and assume things are in place for lxc
# Discussion made by @kiorky and @thatch45
# lxc-version presence is not sufficient, in lxc1.0 alpha
# (precise backports), we have it and it is sufficient
# for the module to execute.
# elif salt.utils.path.which('lxc-version'):
# passed = False
# try:
# passed = subprocess.check_output(
# 'lxc-version').split(':')[1].strip() >= '1.0'
# except Exception:
# pass
# if not passed:
# log.warning('Support for lxc < 1.0 may be incomplete.')
# return 'lxc'
# return False
#
return (False, 'The lxc execution module cannot be loaded: the lxc-start binary is not in the path.')
def get_root_path(path):
'''
Get the configured lxc root for containers
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.get_root_path
'''
if not path:
path = __opts__.get('lxc.root_path', DEFAULT_PATH)
return path
def version():
'''
Return the actual lxc client version
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.version
'''
k = 'lxc.version'
if not __context__.get(k, None):
cversion = __salt__['cmd.run_all']('lxc-info --version')
if not cversion['retcode']:
ver = _LooseVersion(cversion['stdout'])
if ver < _LooseVersion('1.0'):
raise CommandExecutionError('LXC should be at least 1.0')
__context__[k] = "{0}".format(ver)
return __context__.get(k, None)
def _clear_context():
'''
Clear any lxc variables set in __context__
'''
for var in [x for x in __context__ if x.startswith('lxc.')]:
log.trace('Clearing __context__[\'%s\']', var)
__context__.pop(var, None)
def _ip_sort(ip):
'''Ip sorting'''
idx = '001'
if ip == '127.0.0.1':
idx = '200'
if ip == '::1':
idx = '201'
elif '::' in ip:
idx = '100'
return '{0}___{1}'.format(idx, ip)
def search_lxc_bridges():
'''
Search which bridges are potentially available as LXC bridges
CLI Example:
.. code-block:: bash
salt '*' lxc.search_lxc_bridges
'''
bridges = __context__.get('lxc.bridges', None)
# either match not yet called or no bridges were found
# to handle the case where lxc was not installed on the first
# call
if not bridges:
bridges = set()
running_bridges = set()
bridges.add(DEFAULT_BR)
try:
output = __salt__['cmd.run_all']('brctl show')
for line in output['stdout'].splitlines()[1:]:
if not line.startswith(' '):
running_bridges.add(line.split()[0].strip())
except (SaltInvocationError, CommandExecutionError):
pass
for ifc, ip in six.iteritems(
__grains__.get('ip_interfaces', {})
):
if ifc in running_bridges:
bridges.add(ifc)
elif os.path.exists(
'/sys/devices/virtual/net/{0}/bridge'.format(ifc)
):
bridges.add(ifc)
bridges = list(bridges)
# if we found interfaces that have lxc in their names
# we filter them as being the potential lxc bridges
# we also try to default on br0 on other cases
def sort_bridges(a):
pref = 'z'
if 'lxc' in a:
pref = 'a'
elif 'br0' == a:
pref = 'c'
return '{0}_{1}'.format(pref, a)
bridges.sort(key=sort_bridges)
__context__['lxc.bridges'] = bridges
return bridges
def search_lxc_bridge():
'''
Search the first bridge which is potentially available as LXC bridge
CLI Example:
.. code-block:: bash
salt '*' lxc.search_lxc_bridge
'''
return search_lxc_bridges()[0]
def _get_salt_config(config, **kwargs):
if not config:
config = kwargs.get('minion', {})
if not config:
config = {}
config.setdefault('master',
kwargs.get('master',
__opts__.get('master',
__opts__['id'])))
config.setdefault(
'master_port',
kwargs.get('master_port',
__opts__.get('master_port',
__opts__.get('ret_port',
__opts__.get('4506')))))
if not config['master']:
config = {}
return config
def cloud_init_interface(name, vm_=None, **kwargs):
'''
Interface between salt.cloud.lxc driver and lxc.init
``vm_`` is a mapping of vm opts in the salt.cloud format
as documented for the lxc driver.
This can be used either:
- from the salt cloud driver
- because you find the argument to give easier here
than using directly lxc.init
.. warning::
BE REALLY CAREFUL CHANGING DEFAULTS !!!
IT'S A RETRO COMPATIBLE INTERFACE WITH
THE SALT CLOUD DRIVER (ask kiorky).
name
name of the lxc container to create
pub_key
public key to preseed the minion with.
Can be the keycontent or a filepath
priv_key
private key to preseed the minion with.
Can be the keycontent or a filepath
path
path to the container parent directory (default: /var/lib/lxc)
.. versionadded:: 2015.8.0
profile
:ref:`profile <tutorial-lxc-profiles-container>` selection
network_profile
:ref:`network profile <tutorial-lxc-profiles-network>` selection
nic_opts
per interface settings compatibles with
network profile (ipv4/ipv6/link/gateway/mac/netmask)
eg::
- {'eth0': {'mac': '00:16:3e:01:29:40',
'gateway': None, (default)
'link': 'br0', (default)
'gateway': None, (default)
'netmask': '', (default)
'ip': '22.1.4.25'}}
unconditional_install
given to lxc.bootstrap (see relative doc)
force_install
given to lxc.bootstrap (see relative doc)
config
any extra argument for the salt minion config
dnsservers
list of DNS servers to set inside the container
dns_via_dhcp
do not set the dns servers, let them be set by the dhcp.
autostart
autostart the container at boot time
password
administrative password for the container
bootstrap_delay
delay before launching bootstrap script at Container init
.. warning::
Legacy but still supported options:
from_container
which container we use as a template
when running lxc.clone
image
which template do we use when we
are using lxc.create. This is the default
mode unless you specify something in from_container
backing
which backing store to use.
Values can be: overlayfs, dir(default), lvm, zfs, brtfs
fstype
When using a blockdevice level backing store,
which filesystem to use on
size
When using a blockdevice level backing store,
which size for the filesystem to use on
snapshot
Use snapshot when cloning the container source
vgname
if using LVM: vgname
lvname
if using LVM: lvname
thinpool:
if using LVM: thinpool
ip
ip for the primary nic
mac
mac address for the primary nic
netmask
netmask for the primary nic (24)
= ``vm_.get('netmask', '24')``
bridge
bridge for the primary nic (lxcbr0)
gateway
network gateway for the container
additional_ips
additional ips which will be wired on the main bridge (br0)
which is connected to internet.
Be aware that you may use manual virtual mac addresses
providen by you provider (online, ovh, etc).
This is a list of mappings {ip: '', mac: '', netmask:''}
Set gateway to None and an interface with a gateway
to escape from another interface that eth0.
eg::
- {'mac': '00:16:3e:01:29:40',
'gateway': None, (default)
'link': 'br0', (default)
'netmask': '', (default)
'ip': '22.1.4.25'}
users
administrative users for the container
default: [root] and [root, ubuntu] on ubuntu
default_nic
name of the first interface, you should
really not override this
CLI Example:
.. code-block:: bash
salt '*' lxc.cloud_init_interface foo
'''
if vm_ is None:
vm_ = {}
vm_ = copy.deepcopy(vm_)
vm_ = salt.utils.dictupdate.update(vm_, kwargs)
profile_data = copy.deepcopy(
vm_.get('lxc_profile',
vm_.get('profile', {})))
if not isinstance(profile_data, (dict, six.string_types)):
profile_data = {}
profile = get_container_profile(profile_data)
def _cloud_get(k, default=None):
return vm_.get(k, profile.get(k, default))
if name is None:
name = vm_['name']
# if we are on ubuntu, default to ubuntu
default_template = ''
if __grains__.get('os', '') in ['Ubuntu']:
default_template = 'ubuntu'
image = _cloud_get('image')
if not image:
_cloud_get('template', default_template)
backing = _cloud_get('backing', 'dir')
if image:
profile['template'] = image
vgname = _cloud_get('vgname', None)
if vgname:
profile['vgname'] = vgname
if backing:
profile['backing'] = backing
snapshot = _cloud_get('snapshot', False)
autostart = bool(_cloud_get('autostart', True))
dnsservers = _cloud_get('dnsservers', [])
dns_via_dhcp = _cloud_get('dns_via_dhcp', True)
password = _cloud_get('password', 's3cr3t')
password_encrypted = _cloud_get('password_encrypted', False)
fstype = _cloud_get('fstype', None)
lvname = _cloud_get('lvname', None)
thinpool = _cloud_get('thinpool', None)
pub_key = _cloud_get('pub_key', None)
priv_key = _cloud_get('priv_key', None)
size = _cloud_get('size', '20G')
script = _cloud_get('script', None)
script_args = _cloud_get('script_args', None)
users = _cloud_get('users', None)
if users is None:
users = []
ssh_username = _cloud_get('ssh_username', None)
if ssh_username and (ssh_username not in users):
users.append(ssh_username)
network_profile = _cloud_get('network_profile', None)
nic_opts = kwargs.get('nic_opts', None)
netmask = _cloud_get('netmask', '24')
path = _cloud_get('path', None)
bridge = _cloud_get('bridge', None)
gateway = _cloud_get('gateway', None)
unconditional_install = _cloud_get('unconditional_install', False)
force_install = _cloud_get('force_install', True)
config = _get_salt_config(_cloud_get('config', {}), **vm_)
default_nic = _cloud_get('default_nic', DEFAULT_NIC)
# do the interface with lxc.init mainly via nic_opts
# to avoid extra and confusing extra use cases.
if not isinstance(nic_opts, dict):
nic_opts = salt.utils.odict.OrderedDict()
# have a reference to the default nic
eth0 = nic_opts.setdefault(default_nic,
salt.utils.odict.OrderedDict())
# lxc config is based of ifc order, be sure to use odicts.
if not isinstance(nic_opts, salt.utils.odict.OrderedDict):
bnic_opts = salt.utils.odict.OrderedDict()
bnic_opts.update(nic_opts)
nic_opts = bnic_opts
gw = None
# legacy salt.cloud scheme for network interfaces settings support
bridge = _cloud_get('bridge', None)
ip = _cloud_get('ip', None)
mac = _cloud_get('mac', None)
if ip:
fullip = ip
if netmask:
fullip += '/{0}'.format(netmask)
eth0['ipv4'] = fullip
if mac is not None:
eth0['mac'] = mac
for ix, iopts in enumerate(_cloud_get("additional_ips", [])):
ifh = "eth{0}".format(ix+1)
ethx = nic_opts.setdefault(ifh, {})
if gw is None:
gw = iopts.get('gateway', ethx.get('gateway', None))
if gw:
# only one and only one default gateway is allowed !
eth0.pop('gateway', None)
gateway = None
# even if the gateway if on default "eth0" nic
# and we popped it will work
# as we reinject or set it here.
ethx['gateway'] = gw
elink = iopts.get('link', ethx.get('link', None))
if elink:
ethx['link'] = elink
# allow dhcp
aip = iopts.get('ipv4', iopts.get('ip', None))
if aip:
ethx['ipv4'] = aip
nm = iopts.get('netmask', '')
if nm:
ethx['ipv4'] += '/{0}'.format(nm)
for i in ('mac', 'hwaddr'):
if i in iopts:
ethx['mac'] = iopts[i]
break
if 'mac' not in ethx:
ethx['mac'] = salt.utils.network.gen_mac()
# last round checking for unique gateway and such
gw = None
for ethx in [a for a in nic_opts]:
ndata = nic_opts[ethx]
if gw:
ndata.pop('gateway', None)
if 'gateway' in ndata:
gw = ndata['gateway']
gateway = None
# only use a default bridge / gateway if we configured them
# via the legacy salt cloud configuration style.
# On other cases, we should rely on settings provided by the new
# salt lxc network profile style configuration which can
# be also be overridden or a per interface basis via the nic_opts dict.
if bridge:
eth0['link'] = bridge
if gateway:
eth0['gateway'] = gateway
#
lxc_init_interface = {}
lxc_init_interface['name'] = name
lxc_init_interface['config'] = config
lxc_init_interface['memory'] = _cloud_get('memory', 0) # nolimit
lxc_init_interface['pub_key'] = pub_key
lxc_init_interface['priv_key'] = priv_key
lxc_init_interface['nic_opts'] = nic_opts
for clone_from in ['clone_from', 'clone', 'from_container']:
# clone_from should default to None if not available
lxc_init_interface['clone_from'] = _cloud_get(clone_from, None)
if lxc_init_interface['clone_from'] is not None:
break
lxc_init_interface['profile'] = profile
lxc_init_interface['snapshot'] = snapshot
lxc_init_interface['dnsservers'] = dnsservers
lxc_init_interface['fstype'] = fstype
lxc_init_interface['path'] = path
lxc_init_interface['vgname'] = vgname
lxc_init_interface['size'] = size
lxc_init_interface['lvname'] = lvname
lxc_init_interface['thinpool'] = thinpool
lxc_init_interface['force_install'] = force_install
lxc_init_interface['unconditional_install'] = (
unconditional_install
)
lxc_init_interface['bootstrap_url'] = script
lxc_init_interface['bootstrap_args'] = script_args
lxc_init_interface['bootstrap_shell'] = _cloud_get('bootstrap_shell', 'sh')
lxc_init_interface['bootstrap_delay'] = _cloud_get('bootstrap_delay', None)
lxc_init_interface['autostart'] = autostart
lxc_init_interface['users'] = users
lxc_init_interface['password'] = password
lxc_init_interface['password_encrypted'] = password_encrypted
# be sure not to let objects goes inside the return
# as this return will be msgpacked for use in the runner !
lxc_init_interface['network_profile'] = network_profile
for i in ['cpu', 'cpuset', 'cpushare']:
if _cloud_get(i, None):
try:
lxc_init_interface[i] = vm_[i]
except KeyError:
lxc_init_interface[i] = profile[i]
return lxc_init_interface
def _get_profile(key, name, **kwargs):
if isinstance(name, dict):
profilename = name.pop('name', None)
return _get_profile(key, profilename, **name)
if name is None:
profile_match = {}
else:
profile_match = \
__salt__['config.get'](
'lxc.{1}:{0}'.format(name, key),
default=None,
merge='recurse'
)
if profile_match is None:
# No matching profile, make the profile an empty dict so that
# overrides can be applied below.
profile_match = {}
if not isinstance(profile_match, dict):
raise CommandExecutionError('lxc.{0} must be a dictionary'.format(key))
# Overlay the kwargs to override matched profile data
overrides = salt.utils.args.clean_kwargs(**copy.deepcopy(kwargs))
profile_match = salt.utils.dictupdate.update(
copy.deepcopy(profile_match),
overrides
)
return profile_match
def get_container_profile(name=None, **kwargs):
'''
.. versionadded:: 2015.5.0
Gather a pre-configured set of container configuration parameters. If no
arguments are passed, an empty profile is returned.
Profiles can be defined in the minion or master config files, or in pillar
or grains, and are loaded using :mod:`config.get
<salt.modules.config.get>`. The key under which LXC profiles must be
configured is ``lxc.container_profile.profile_name``. An example container
profile would be as follows:
.. code-block:: yaml
lxc.container_profile:
ubuntu:
template: ubuntu
backing: lvm
vgname: lxc
size: 1G
Parameters set in a profile can be overridden by passing additional
container creation arguments (such as the ones passed to :mod:`lxc.create
<salt.modules.lxc.create>`) to this function.
A profile can be defined either as the name of the profile, or a dictionary
of variable names and values. See the :ref:`LXC Tutorial
<tutorial-lxc-profiles>` for more information on how to use LXC profiles.
CLI Example:
.. code-block:: bash
salt-call lxc.get_container_profile centos
salt-call lxc.get_container_profile ubuntu template=ubuntu backing=overlayfs
'''
profile = _get_profile('container_profile', name, **kwargs)
return profile
def get_network_profile(name=None, **kwargs):
'''
.. versionadded:: 2015.5.0
Gather a pre-configured set of network configuration parameters. If no
arguments are passed, the following default profile is returned:
.. code-block:: python
{'eth0': {'link': 'br0', 'type': 'veth', 'flags': 'up'}}
Profiles can be defined in the minion or master config files, or in pillar
or grains, and are loaded using :mod:`config.get
<salt.modules.config.get>`. The key under which LXC profiles must be
configured is ``lxc.network_profile``. An example network profile would be
as follows:
.. code-block:: yaml
lxc.network_profile.centos:
eth0:
link: br0
type: veth
flags: up
To disable networking entirely:
.. code-block:: yaml
lxc.network_profile.centos:
eth0:
disable: true
Parameters set in a profile can be overridden by passing additional
arguments to this function.
A profile can be passed either as the name of the profile, or a
dictionary of variable names and values. See the :ref:`LXC Tutorial
<tutorial-lxc-profiles>` for more information on how to use network
profiles.
.. warning::
The ``ipv4``, ``ipv6``, ``gateway``, and ``link`` (bridge) settings in
network profiles will only work if the container doesn't redefine the
network configuration (for example in
``/etc/sysconfig/network-scripts/ifcfg-<interface_name>`` on
RHEL/CentOS, or ``/etc/network/interfaces`` on Debian/Ubuntu/etc.)
CLI Example:
.. code-block:: bash
salt-call lxc.get_network_profile default
'''
profile = _get_profile('network_profile', name, **kwargs)
return profile
def _rand_cpu_str(cpu):
'''
Return a random subset of cpus for the cpuset config
'''
cpu = int(cpu)
avail = __salt__['status.nproc']()
if cpu < avail:
return '0-{0}'.format(avail)
to_set = set()
while len(to_set) < cpu:
choice = random.randint(0, avail - 1)
if choice not in to_set:
to_set.add(six.text_type(choice))
return ','.join(sorted(to_set))
def _network_conf(conf_tuples=None, **kwargs):
'''
Network configuration defaults
network_profile
as for containers, we can either call this function
either with a network_profile dict or network profile name
in the kwargs
nic_opts
overrides or extra nics in the form {nic_name: {set: tings}
'''
nic = kwargs.get('network_profile', None)
ret = []
nic_opts = kwargs.get('nic_opts', {})
if nic_opts is None:
# coming from elsewhere
nic_opts = {}
if not conf_tuples:
conf_tuples = []
old = _get_veths(conf_tuples)
if not old:
old = {}
# if we have a profile name, get the profile and load the network settings
# this will obviously by default look for a profile called "eth0"
# or by what is defined in nic_opts
# and complete each nic settings by sane defaults
if nic and isinstance(nic, (six.string_types, dict)):
nicp = get_network_profile(nic)
else:
nicp = {}
if DEFAULT_NIC not in nicp:
nicp[DEFAULT_NIC] = {}
kwargs = copy.deepcopy(kwargs)
gateway = kwargs.pop('gateway', None)
bridge = kwargs.get('bridge', None)
if nic_opts:
for dev, args in six.iteritems(nic_opts):
ethx = nicp.setdefault(dev, {})
try:
ethx = salt.utils.dictupdate.update(ethx, args)
except AttributeError:
raise SaltInvocationError('Invalid nic_opts configuration')
ifs = [a for a in nicp]
ifs += [a for a in old if a not in nicp]
ifs.sort()
gateway_set = False
for dev in ifs:
args = nicp.get(dev, {})
opts = nic_opts.get(dev, {}) if nic_opts else {}
old_if = old.get(dev, {})
disable = opts.get('disable', args.get('disable', False))
if disable:
continue
mac = opts.get('mac',
opts.get('hwaddr',
args.get('mac',
args.get('hwaddr', ''))))
type_ = opts.get('type', args.get('type', ''))
flags = opts.get('flags', args.get('flags', ''))
link = opts.get('link', args.get('link', ''))
ipv4 = opts.get('ipv4', args.get('ipv4', ''))
ipv6 = opts.get('ipv6', args.get('ipv6', ''))
infos = salt.utils.odict.OrderedDict([
('lxc.network.type', {
'test': not type_,
'value': type_,
'old': old_if.get('lxc.network.type'),
'default': 'veth'}),
('lxc.network.name', {
'test': False,
'value': dev,
'old': dev,
'default': dev}),
('lxc.network.flags', {
'test': not flags,
'value': flags,
'old': old_if.get('lxc.network.flags'),
'default': 'up'}),
('lxc.network.link', {
'test': not link,
'value': link,
'old': old_if.get('lxc.network.link'),
'default': search_lxc_bridge()}),
('lxc.network.hwaddr', {
'test': not mac,
'value': mac,
'old': old_if.get('lxc.network.hwaddr'),
'default': salt.utils.network.gen_mac()}),
('lxc.network.ipv4', {
'test': not ipv4,
'value': ipv4,
'old': old_if.get('lxc.network.ipv4', ''),
'default': None}),
('lxc.network.ipv6', {
'test': not ipv6,
'value': ipv6,
'old': old_if.get('lxc.network.ipv6', ''),
'default': None})])
# for each parameter, if not explicitly set, the
# config value present in the LXC configuration should
# take precedence over the profile configuration
for info in list(infos.keys()):
bundle = infos[info]
if bundle['test']:
if bundle['old']:
bundle['value'] = bundle['old']
elif bundle['default']:
bundle['value'] = bundle['default']
for info, data in six.iteritems(infos):
if data['value']:
ret.append({info: data['value']})
for key, val in six.iteritems(args):
if key == 'link' and bridge:
val = bridge
val = opts.get(key, val)
if key in [
'type', 'flags', 'name',
'gateway', 'mac', 'link', 'ipv4', 'ipv6'
]:
continue
ret.append({'lxc.network.{0}'.format(key): val})
# gateway (in automode) must be appended following network conf !
if not gateway:
gateway = args.get('gateway', None)
if gateway is not None and not gateway_set:
ret.append({'lxc.network.ipv4.gateway': gateway})
# only one network gateway ;)
gateway_set = True
# normally, this won't happen
# set the gateway if specified even if we did
# not managed the network underlying
if gateway is not None and not gateway_set:
ret.append({'lxc.network.ipv4.gateway': gateway})
# only one network gateway ;)
gateway_set = True
new = _get_veths(ret)
# verify that we did not loose the mac settings
for iface in [a for a in new]:
ndata = new[iface]
nmac = ndata.get('lxc.network.hwaddr', '')
ntype = ndata.get('lxc.network.type', '')
omac, otype = '', ''
if iface in old:
odata = old[iface]
omac = odata.get('lxc.network.hwaddr', '')
otype = odata.get('lxc.network.type', '')
# default for network type is setted here
# attention not to change the network type
# without a good and explicit reason to.
if otype and not ntype:
ntype = otype
if not ntype:
ntype = 'veth'
new[iface]['lxc.network.type'] = ntype
if omac and not nmac:
new[iface]['lxc.network.hwaddr'] = omac
ret = []
for val in six.itervalues(new):
for row in val:
ret.append(salt.utils.odict.OrderedDict([(row, val[row])]))
# on old versions of lxc, still support the gateway auto mode
# if we didn't explicitly say no to
# (lxc.network.ipv4.gateway: auto)
if _LooseVersion(version()) <= _LooseVersion('1.0.7') and \
True not in ['lxc.network.ipv4.gateway' in a for a in ret] and \
True in ['lxc.network.ipv4' in a for a in ret]:
ret.append({'lxc.network.ipv4.gateway': 'auto'})
return ret
def _get_lxc_default_data(**kwargs):
kwargs = copy.deepcopy(kwargs)
ret = {}
for k in ['utsname', 'rootfs']:
val = kwargs.get(k, None)
if val is not None:
ret['lxc.{0}'.format(k)] = val
autostart = kwargs.get('autostart')
# autostart can have made in kwargs, but with the None
# value which is invalid, we need an explicit boolean
# autostart = on is the default.
if autostart is None:
autostart = True
# we will set the regular lxc marker to restart container at
# machine (re)boot only if we did not explicitly ask
# not to touch to the autostart settings via
# autostart == 'keep'
if autostart != 'keep':
if autostart:
ret['lxc.start.auto'] = '1'
else:
ret['lxc.start.auto'] = '0'
memory = kwargs.get('memory')
if memory is not None:
# converting the config value from MB to bytes
ret['lxc.cgroup.memory.limit_in_bytes'] = memory * 1024 * 1024
cpuset = kwargs.get('cpuset')
if cpuset:
ret['lxc.cgroup.cpuset.cpus'] = cpuset
cpushare = kwargs.get('cpushare')
cpu = kwargs.get('cpu')
if cpushare:
ret['lxc.cgroup.cpu.shares'] = cpushare
if cpu and not cpuset:
ret['lxc.cgroup.cpuset.cpus'] = _rand_cpu_str(cpu)
return ret
def _config_list(conf_tuples=None, only_net=False, **kwargs):
'''
Return a list of dicts from the salt level configurations
conf_tuples
_LXCConfig compatible list of entries which can contain
- string line
- tuple (lxc config param,value)
- dict of one entry: {lxc config param: value)
only_net
by default we add to the tuples a reflection of both
the real config if avalaible and a certain amount of
default values like the cpu parameters, the memory
and etc.
On the other hand, we also no matter the case reflect
the network configuration computed from the actual config if
available and given values.
if no_default_loads is set, we will only
reflect the network configuration back to the conf tuples
list
'''
# explicit cast
only_net = bool(only_net)
if not conf_tuples:
conf_tuples = []
kwargs = copy.deepcopy(kwargs)
ret = []
if not only_net:
default_data = _get_lxc_default_data(**kwargs)
for k, val in six.iteritems(default_data):
ret.append({k: val})
net_datas = _network_conf(conf_tuples=conf_tuples, **kwargs)
ret.extend(net_datas)
return ret
def _get_veths(net_data):
'''
Parse the nic setup inside lxc conf tuples back to a dictionary indexed by
network interface
'''
if isinstance(net_data, dict):
net_data = list(net_data.items())
nics = salt.utils.odict.OrderedDict()
current_nic = salt.utils.odict.OrderedDict()
no_names = True
for item in net_data:
if item and isinstance(item, dict):
item = list(item.items())[0]
# skip LXC configuration comment lines, and play only with tuples conf
elif isinstance(item, six.string_types):
# deal with reflection of commented lxc configs
sitem = item.strip()
if sitem.startswith('#') or not sitem:
continue
elif '=' in item:
item = tuple([a.strip() for a in item.split('=', 1)])
if item[0] == 'lxc.network.type':
current_nic = salt.utils.odict.OrderedDict()
if item[0] == 'lxc.network.name':
no_names = False
nics[item[1].strip()] = current_nic
current_nic[item[0].strip()] = item[1].strip()
# if not ethernet card name has been collected, assuming we collected
# data for eth0
if no_names and current_nic:
nics[DEFAULT_NIC] = current_nic
return nics
class _LXCConfig(object):
'''
LXC configuration data
'''
pattern = re.compile(r'^(\S+)(\s*)(=)(\s*)(.*)')
non_interpretable_pattern = re.compile(r'^((#.*)|(\s*))$')
def __init__(self, **kwargs):
kwargs = copy.deepcopy(kwargs)
self.name = kwargs.pop('name', None)
path = get_root_path(kwargs.get('path', None))
self.data = []
if self.name:
self.path = os.path.join(path, self.name, 'config')
if os.path.isfile(self.path):
with salt.utils.files.fopen(self.path) as fhr:
for line in salt.utils.data.decode(fhr.readlines()):
match = self.pattern.findall((line.strip()))
if match:
self.data.append((match[0][0], match[0][-1]))
match = self.non_interpretable_pattern.findall(
(line.strip()))
if match:
self.data.append(('', match[0][0]))
else:
self.path = None
def _replace(key, val):
if val:
self._filter_data(key)
self.data.append((key, val))
default_data = _get_lxc_default_data(**kwargs)
for key, val in six.iteritems(default_data):
_replace(key, val)
old_net = self._filter_data('lxc.network')
net_datas = _network_conf(conf_tuples=old_net, **kwargs)
if net_datas:
for row in net_datas:
self.data.extend(list(row.items()))
# be sure to reset harmful settings
for idx in ['lxc.cgroup.memory.limit_in_bytes']:
if not default_data.get(idx):
self._filter_data(idx)
def as_string(self):
chunks = ('{0[0]}{1}{0[1]}'.format(item, (' = ' if item[0] else '')) for item in self.data)
return '\n'.join(chunks) + '\n'
def write(self):
if self.path:
content = self.as_string()
# 2 step rendering to be sure not to open/wipe the config
# before as_string succeeds.
with salt.utils.files.fopen(self.path, 'w') as fic:
fic.write(salt.utils.stringutils.to_str(content))
fic.flush()
def tempfile(self):
# this might look like the function name is shadowing the
# module, but it's not since the method belongs to the class
ntf = tempfile.NamedTemporaryFile()
ntf.write(self.as_string())
ntf.flush()
return ntf
def _filter_data(self, pattern):
'''
Removes parameters which match the pattern from the config data
'''
removed = []
filtered = []
for param in self.data:
if not param[0].startswith(pattern):
filtered.append(param)
else:
removed.append(param)
self.data = filtered
return removed
def _get_base(**kwargs):
'''
If the needed base does not exist, then create it, if it does exist
create nothing and return the name of the base lxc container so
it can be cloned.
'''
profile = get_container_profile(copy.deepcopy(kwargs.get('profile')))
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, _marker)
profile_match = profile.pop(key, default)
# let kwarg overrides be the preferred choice
if kw_overrides_match is _marker:
return profile_match
return kw_overrides_match
template = select('template')
image = select('image')
vgname = select('vgname')
path = kwargs.get('path', None)
# remove the above three variables from kwargs, if they exist, to avoid
# duplicates if create() is invoked below.
for param in ('path', 'image', 'vgname', 'template'):
kwargs.pop(param, None)
if image:
proto = _urlparse(image).scheme
img_tar = __salt__['cp.cache_file'](image)
img_name = os.path.basename(img_tar)
hash_ = salt.utils.hashutils.get_hash(
img_tar,
__salt__['config.get']('hash_type'))
name = '__base_{0}_{1}_{2}'.format(proto, img_name, hash_)
if not exists(name, path=path):
create(name, template=template, image=image,
path=path, vgname=vgname, **kwargs)
if vgname:
rootfs = os.path.join('/dev', vgname, name)
edit_conf(info(name, path=path)['config'],
out_format='commented', **{'lxc.rootfs': rootfs})
return name
elif template:
name = '__base_{0}'.format(template)
if not exists(name, path=path):
create(name, template=template, image=image, path=path,
vgname=vgname, **kwargs)
if vgname:
rootfs = os.path.join('/dev', vgname, name)
edit_conf(info(name, path=path)['config'],
out_format='commented', **{'lxc.rootfs': rootfs})
return name
return ''
def init(name,
config=None,
cpuset=None,
cpushare=None,
memory=None,
profile=None,
network_profile=None,
nic_opts=None,
cpu=None,
autostart=True,
password=None,
password_encrypted=None,
users=None,
dnsservers=None,
searchdomains=None,
bridge=None,
gateway=None,
pub_key=None,
priv_key=None,
force_install=False,
unconditional_install=False,
bootstrap_delay=None,
bootstrap_args=None,
bootstrap_shell=None,
bootstrap_url=None,
**kwargs):
'''
Initialize a new container.
This is a partial idempotent function as if it is already provisioned, we
will reset a bit the lxc configuration file but much of the hard work will
be escaped as markers will prevent re-execution of harmful tasks.
name
Name of the container
image
A tar archive to use as the rootfs for the container. Conflicts with
the ``template`` argument.
cpus
Select a random number of cpu cores and assign it to the cpuset, if the
cpuset option is set then this option will be ignored
cpuset
Explicitly define the cpus this container will be bound to
cpushare
cgroups cpu shares
autostart
autostart container on reboot
memory
cgroups memory limit, in MB
.. versionchanged:: 2015.5.0
If no value is passed, no limit is set. In earlier Salt versions,
not passing this value causes a 1024MB memory limit to be set, and
it was necessary to pass ``memory=0`` to set no limit.
gateway
the ipv4 gateway to use
the default does nothing more than lxcutils does
bridge
the bridge to use
the default does nothing more than lxcutils does
network_profile
Network profile to use for the container
.. versionadded:: 2015.5.0
nic_opts
Extra options for network interfaces, will override
``{"eth0": {"hwaddr": "aa:bb:cc:dd:ee:ff", "ipv4": "10.1.1.1", "ipv6": "2001:db8::ff00:42:8329"}}``
or
``{"eth0": {"hwaddr": "aa:bb:cc:dd:ee:ff", "ipv4": "10.1.1.1/24", "ipv6": "2001:db8::ff00:42:8329"}}``
users
Users for which the password defined in the ``password`` param should
be set. Can be passed as a comma separated list or a python list.
Defaults to just the ``root`` user.
password
Set the initial password for the users defined in the ``users``
parameter
password_encrypted : False
Set to ``True`` to denote a password hash instead of a plaintext
password
.. versionadded:: 2015.5.0
profile
A LXC profile (defined in config or pillar).
This can be either a real profile mapping or a string
to retrieve it in configuration
start
Start the newly-created container
dnsservers
list of dns servers to set in the container, default [] (no setting)
seed
Seed the container with the minion config. Default: ``True``
install
If salt-minion is not already installed, install it. Default: ``True``
config
Optional config parameters. By default, the id is set to
the name of the container.
master
salt master (default to minion's master)
master_port
salt master port (default to minion's master port)
pub_key
Explicit public key to preseed the minion with (optional).
This can be either a filepath or a string representing the key
priv_key
Explicit private key to preseed the minion with (optional).
This can be either a filepath or a string representing the key
approve_key
If explicit preseeding is not used;
Attempt to request key approval from the master. Default: ``True``
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
clone_from
Original from which to use a clone operation to create the container.
Default: ``None``
bootstrap_delay
Delay in seconds between end of container creation and bootstrapping.
Useful when waiting for container to obtain a DHCP lease.
.. versionadded:: 2015.5.0
bootstrap_url
See lxc.bootstrap
bootstrap_shell
See lxc.bootstrap
bootstrap_args
See lxc.bootstrap
force_install
Force installation even if salt-minion is detected,
this is the way to run vendor bootstrap scripts even
if a salt minion is already present in the container
unconditional_install
Run the script even if the container seems seeded
CLI Example:
.. code-block:: bash
salt 'minion' lxc.init name [cpuset=cgroups_cpuset] \\
[cpushare=cgroups_cpushare] [memory=cgroups_memory] \\
[nic=nic_profile] [profile=lxc_profile] \\
[nic_opts=nic_opts] [start=(True|False)] \\
[seed=(True|False)] [install=(True|False)] \\
[config=minion_config] [approve_key=(True|False) \\
[clone_from=original] [autostart=True] \\
[priv_key=/path_or_content] [pub_key=/path_or_content] \\
[bridge=lxcbr0] [gateway=10.0.3.1] \\
[dnsservers[dns1,dns2]] \\
[users=[foo]] [password='secret'] \\
[password_encrypted=(True|False)]
'''
ret = {'name': name,
'changes': {}}
profile = get_container_profile(copy.deepcopy(profile))
if not network_profile:
network_profile = profile.get('network_profile')
if not network_profile:
network_profile = DEFAULT_NIC
# Changes is a pointer to changes_dict['init']. This method is used so that
# we can have a list of changes as they are made, providing an ordered list
# of things that were changed.
changes_dict = {'init': []}
changes = changes_dict.get('init')
if users is None:
users = []
dusers = ['root']
for user in dusers:
if user not in users:
users.append(user)
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, _marker)
profile_match = profile.pop(key, default)
# let kwarg overrides be the preferred choice
if kw_overrides_match is _marker:
return profile_match
return kw_overrides_match
path = select('path')
bpath = get_root_path(path)
state_pre = state(name, path=path)
tvg = select('vgname')
vgname = tvg if tvg else __salt__['config.get']('lxc.vgname')
start_ = select('start', True)
autostart = select('autostart', autostart)
seed = select('seed', True)
install = select('install', True)
seed_cmd = select('seed_cmd')
salt_config = _get_salt_config(config, **kwargs)
approve_key = select('approve_key', True)
clone_from = select('clone_from')
# If using a volume group then set up to make snapshot cow clones
if vgname and not clone_from:
try:
kwargs['vgname'] = vgname
clone_from = _get_base(profile=profile, **kwargs)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = exc.strerror
if changes:
ret['changes'] = changes_dict
return ret
if not kwargs.get('snapshot') is False:
kwargs['snapshot'] = True
does_exist = exists(name, path=path)
to_reboot = False
remove_seed_marker = False
if does_exist:
pass
elif clone_from:
remove_seed_marker = True
try:
clone(name, clone_from, profile=profile, **kwargs)
changes.append({'create': 'Container cloned'})
except (SaltInvocationError, CommandExecutionError) as exc:
if 'already exists' in exc.strerror:
changes.append({'create': 'Container already exists'})
else:
ret['result'] = False
ret['comment'] = exc.strerror
if changes:
ret['changes'] = changes_dict
return ret
cfg = _LXCConfig(name=name, network_profile=network_profile,
nic_opts=nic_opts, bridge=bridge, path=path,
gateway=gateway, autostart=autostart,
cpuset=cpuset, cpushare=cpushare, memory=memory)
old_chunks = read_conf(cfg.path, out_format='commented')
cfg.write()
chunks = read_conf(cfg.path, out_format='commented')
if old_chunks != chunks:
to_reboot = True
else:
remove_seed_marker = True
cfg = _LXCConfig(network_profile=network_profile,
nic_opts=nic_opts, cpuset=cpuset, path=path,
bridge=bridge, gateway=gateway,
autostart=autostart,
cpushare=cpushare, memory=memory)
with cfg.tempfile() as cfile:
try:
create(name, config=cfile.name, profile=profile, **kwargs)
changes.append({'create': 'Container created'})
except (SaltInvocationError, CommandExecutionError) as exc:
if 'already exists' in exc.strerror:
changes.append({'create': 'Container already exists'})
else:
ret['comment'] = exc.strerror
if changes:
ret['changes'] = changes_dict
return ret
cpath = os.path.join(bpath, name, 'config')
old_chunks = []
if os.path.exists(cpath):
old_chunks = read_conf(cpath, out_format='commented')
new_cfg = _config_list(conf_tuples=old_chunks,
cpu=cpu,
network_profile=network_profile,
nic_opts=nic_opts, bridge=bridge,
cpuset=cpuset, cpushare=cpushare,
memory=memory)
if new_cfg:
edit_conf(cpath, out_format='commented', lxc_config=new_cfg)
chunks = read_conf(cpath, out_format='commented')
if old_chunks != chunks:
to_reboot = True
# last time to be sure any of our property is correctly applied
cfg = _LXCConfig(name=name, network_profile=network_profile,
nic_opts=nic_opts, bridge=bridge, path=path,
gateway=gateway, autostart=autostart,
cpuset=cpuset, cpushare=cpushare, memory=memory)
old_chunks = []
if os.path.exists(cfg.path):
old_chunks = read_conf(cfg.path, out_format='commented')
cfg.write()
chunks = read_conf(cfg.path, out_format='commented')
if old_chunks != chunks:
changes.append({'config': 'Container configuration updated'})
to_reboot = True
if to_reboot:
try:
stop(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
if changes:
ret['changes'] = changes_dict
return ret
if not does_exist or (does_exist and state(name, path=path) != 'running'):
try:
start(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
if changes:
ret['changes'] = changes_dict
return ret
if remove_seed_marker:
run(name,
'rm -f \'{0}\''.format(SEED_MARKER),
path=path,
chroot_fallback=False,
python_shell=False)
# set the default user/password, only the first time
if ret.get('result', True) and password:
gid = '/.lxc.initial_pass'
gids = [gid,
'/lxc.initial_pass',
'/.lxc.{0}.initial_pass'.format(name)]
if not any(retcode(name,
'test -e "{0}"'.format(x),
chroot_fallback=True,
path=path,
ignore_retcode=True) == 0
for x in gids):
# think to touch the default user generated by default templates
# which has a really unsecure passwords...
# root is defined as a member earlier in the code
for default_user in ['ubuntu']:
if (
default_user not in users and
retcode(name,
'id {0}'.format(default_user),
python_shell=False,
path=path,
chroot_fallback=True,
ignore_retcode=True) == 0
):
users.append(default_user)
for user in users:
try:
cret = set_password(name,
users=[user],
path=path,
password=password,
encrypted=password_encrypted)
except (SaltInvocationError, CommandExecutionError) as exc:
msg = '{0}: Failed to set password'.format(
user) + exc.strerror
# only hardfail in unrecoverable situation:
# root cannot be setted up
if user == 'root':
ret['comment'] = msg
ret['result'] = False
else:
log.debug(msg)
if ret.get('result', True):
changes.append({'password': 'Password(s) updated'})
if retcode(name,
('sh -c \'touch "{0}"; test -e "{0}"\''
.format(gid)),
path=path,
chroot_fallback=True,
ignore_retcode=True) != 0:
ret['comment'] = 'Failed to set password marker'
changes[-1]['password'] += '. ' + ret['comment'] + '.'
ret['result'] = False
# set dns servers if any, only the first time
if ret.get('result', True) and dnsservers:
# retro compatibility, test also old markers
gid = '/.lxc.initial_dns'
gids = [gid,
'/lxc.initial_dns',
'/lxc.{0}.initial_dns'.format(name)]
if not any(retcode(name,
'test -e "{0}"'.format(x),
chroot_fallback=True,
path=path,
ignore_retcode=True) == 0
for x in gids):
try:
set_dns(name,
path=path,
dnsservers=dnsservers,
searchdomains=searchdomains)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Failed to set DNS: ' + exc.strerror
ret['result'] = False
else:
changes.append({'dns': 'DNS updated'})
if retcode(name,
('sh -c \'touch "{0}"; test -e "{0}"\''
.format(gid)),
chroot_fallback=True,
path=path,
ignore_retcode=True) != 0:
ret['comment'] = 'Failed to set DNS marker'
changes[-1]['dns'] += '. ' + ret['comment'] + '.'
ret['result'] = False
# retro compatibility, test also old markers
if remove_seed_marker:
run(name,
'rm -f \'{0}\''.format(SEED_MARKER),
path=path,
python_shell=False)
gid = '/.lxc.initial_seed'
gids = [gid, '/lxc.initial_seed']
if (
any(retcode(name,
'test -e {0}'.format(x),
path=path,
chroot_fallback=True,
ignore_retcode=True) == 0
for x in gids) or not ret.get('result', True)
):
pass
elif seed or seed_cmd:
if seed:
try:
result = bootstrap(
name, config=salt_config, path=path,
approve_key=approve_key,
pub_key=pub_key, priv_key=priv_key,
install=install,
force_install=force_install,
unconditional_install=unconditional_install,
bootstrap_delay=bootstrap_delay,
bootstrap_url=bootstrap_url,
bootstrap_shell=bootstrap_shell,
bootstrap_args=bootstrap_args)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Bootstrap failed: ' + exc.strerror
ret['result'] = False
else:
if not result:
ret['comment'] = ('Bootstrap failed, see minion log for '
'more information')
ret['result'] = False
else:
changes.append(
{'bootstrap': 'Container successfully bootstrapped'}
)
elif seed_cmd:
try:
result = __salt__[seed_cmd](info(name, path=path)['rootfs'],
name,
salt_config)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = ('Bootstrap via seed_cmd \'{0}\' failed: {1}'
.format(seed_cmd, exc.strerror))
ret['result'] = False
else:
if not result:
ret['comment'] = ('Bootstrap via seed_cmd \'{0}\' failed, '
'see minion log for more information '
.format(seed_cmd))
ret['result'] = False
else:
changes.append(
{'bootstrap': 'Container successfully bootstrapped '
'using seed_cmd \'{0}\''
.format(seed_cmd)}
)
if ret.get('result', True) and not start_:
try:
stop(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
ret['result'] = False
state_post = state(name, path=path)
if state_pre != state_post:
changes.append({'state': {'old': state_pre, 'new': state_post}})
if ret.get('result', True):
ret['comment'] = ('Container \'{0}\' successfully initialized'
.format(name))
ret['result'] = True
if changes:
ret['changes'] = changes_dict
return ret
def cloud_init(name, vm_=None, **kwargs):
'''
Thin wrapper to lxc.init to be used from the saltcloud lxc driver
name
Name of the container
may be None and then guessed from saltcloud mapping
`vm_`
saltcloud mapping defaults for the vm
CLI Example:
.. code-block:: bash
salt '*' lxc.cloud_init foo
'''
init_interface = cloud_init_interface(name, vm_, **kwargs)
name = init_interface.pop('name', name)
return init(name, **init_interface)
def images(dist=None):
'''
.. versionadded:: 2015.5.0
List the available images for LXC's ``download`` template.
dist : None
Filter results to a single Linux distribution
CLI Examples:
.. code-block:: bash
salt myminion lxc.images
salt myminion lxc.images dist=centos
'''
out = __salt__['cmd.run_stdout'](
'lxc-create -n __imgcheck -t download -- --list',
ignore_retcode=True
)
if 'DIST' not in out:
raise CommandExecutionError(
'Unable to run the \'download\' template script. Is it installed?'
)
ret = {}
passed_header = False
for line in out.splitlines():
try:
distro, release, arch, variant, build_time = line.split()
except ValueError:
continue
if not passed_header:
if distro == 'DIST':
passed_header = True
continue
dist_list = ret.setdefault(distro, [])
dist_list.append({
'release': release,
'arch': arch,
'variant': variant,
'build_time': build_time,
})
if dist is not None:
return dict([(dist, ret.get(dist, []))])
return ret
def templates():
'''
.. versionadded:: 2015.5.0
List the available LXC template scripts installed on the minion
CLI Examples:
.. code-block:: bash
salt myminion lxc.templates
'''
try:
template_scripts = os.listdir('/usr/share/lxc/templates')
except OSError:
return []
else:
return [x[4:] for x in template_scripts if x.startswith('lxc-')]
def _after_ignition_network_profile(cmd,
ret,
name,
network_profile,
path,
nic_opts):
_clear_context()
if ret['retcode'] == 0 and exists(name, path=path):
if network_profile:
network_changes = apply_network_profile(name,
network_profile,
path=path,
nic_opts=nic_opts)
if network_changes:
log.info(
'Network changes from applying network profile \'%s\' '
'to newly-created container \'%s\':\n%s',
network_profile, name, network_changes
)
c_state = state(name, path=path)
return {'result': True,
'state': {'old': None, 'new': c_state}}
else:
if exists(name, path=path):
# destroy the container if it was partially created
cmd = 'lxc-destroy'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0}'.format(name)
__salt__['cmd.retcode'](cmd, python_shell=False)
raise CommandExecutionError(
'Container could not be created with cmd \'{0}\': {1}'
.format(cmd, ret['stderr'])
)
def create(name,
config=None,
profile=None,
network_profile=None,
nic_opts=None,
**kwargs):
'''
Create a new container.
name
Name of the container
config
The config file to use for the container. Defaults to system-wide
config (usually in /etc/lxc/lxc.conf).
profile
Profile to use in container creation (see
:mod:`lxc.get_container_profile
<salt.modules.lxc.get_container_profile>`). Values in a profile will be
overridden by the **Container Creation Arguments** listed below.
network_profile
Network profile to use for container
.. versionadded:: 2015.5.0
**Container Creation Arguments**
template
The template to use. For example, ``ubuntu`` or ``fedora``.
For a full list of available templates, check out
the :mod:`lxc.templates <salt.modules.lxc.templates>` function.
Conflicts with the ``image`` argument.
.. note::
The ``download`` template requires the following three parameters
to be defined in ``options``:
* **dist** - The name of the distribution
* **release** - Release name/version
* **arch** - Architecture of the container
The available images can be listed using the :mod:`lxc.images
<salt.modules.lxc.images>` function.
options
Template-specific options to pass to the lxc-create command. These
correspond to the long options (ones beginning with two dashes) that
the template script accepts. For example:
.. code-block:: bash
options='{"dist": "centos", "release": "6", "arch": "amd64"}'
For available template options, refer to the lxc template scripts
which are ususally located under ``/usr/share/lxc/templates``,
or run ``lxc-create -t <template> -h``.
image
A tar archive to use as the rootfs for the container. Conflicts with
the ``template`` argument.
backing
The type of storage to use. Set to ``lvm`` to use an LVM group.
Defaults to filesystem within /var/lib/lxc.
fstype
Filesystem type to use on LVM logical volume
size : 1G
Size of the volume to create. Only applicable if ``backing=lvm``.
vgname : lxc
Name of the LVM volume group in which to create the volume for this
container. Only applicable if ``backing=lvm``.
lvname
Name of the LVM logical volume in which to create the volume for this
container. Only applicable if ``backing=lvm``.
thinpool
Name of a pool volume that will be used for thin-provisioning this
container. Only applicable if ``backing=lvm``.
nic_opts
give extra opts overriding network profile values
path
parent path for the container creation (default: /var/lib/lxc)
zfsroot
Name of the ZFS root in which to create the volume for this container.
Only applicable if ``backing=zfs``. (default: tank/lxc)
.. versionadded:: 2015.8.0
'''
# Required params for 'download' template
download_template_deps = ('dist', 'release', 'arch')
cmd = 'lxc-create -n {0}'.format(name)
profile = get_container_profile(copy.deepcopy(profile))
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, None)
profile_match = profile.pop(key, default)
# Return the profile match if the the kwarg match was None, as the
# lxc.present state will pass these kwargs set to None by default.
if kw_overrides_match is None:
return profile_match
return kw_overrides_match
path = select('path')
if exists(name, path=path):
raise CommandExecutionError(
'Container \'{0}\' already exists'.format(name)
)
tvg = select('vgname')
vgname = tvg if tvg else __salt__['config.get']('lxc.vgname')
# The 'template' and 'image' params conflict
template = select('template')
image = select('image')
if template and image:
raise SaltInvocationError(
'Only one of \'template\' and \'image\' is permitted'
)
elif not any((template, image, profile)):
raise SaltInvocationError(
'At least one of \'template\', \'image\', and \'profile\' is '
'required'
)
options = select('options') or {}
backing = select('backing')
if vgname and not backing:
backing = 'lvm'
lvname = select('lvname')
thinpool = select('thinpool')
fstype = select('fstype')
size = select('size', '1G')
zfsroot = select('zfsroot')
if backing in ('dir', 'overlayfs', 'btrfs', 'zfs'):
fstype = None
size = None
# some backends won't support some parameters
if backing in ('aufs', 'dir', 'overlayfs', 'btrfs'):
lvname = vgname = thinpool = None
if image:
img_tar = __salt__['cp.cache_file'](image)
template = os.path.join(
os.path.dirname(salt.__file__),
'templates',
'lxc',
'salt_tarball')
options['imgtar'] = img_tar
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
if not os.path.exists(path):
os.makedirs(path)
if config:
cmd += ' -f {0}'.format(config)
if template:
cmd += ' -t {0}'.format(template)
if backing:
backing = backing.lower()
cmd += ' -B {0}'.format(backing)
if backing in ('zfs',):
if zfsroot:
cmd += ' --zfsroot {0}'.format(zfsroot)
if backing in ('lvm',):
if lvname:
cmd += ' --lvname {0}'.format(lvname)
if vgname:
cmd += ' --vgname {0}'.format(vgname)
if thinpool:
cmd += ' --thinpool {0}'.format(thinpool)
if backing not in ('dir', 'overlayfs'):
if fstype:
cmd += ' --fstype {0}'.format(fstype)
if size:
cmd += ' --fssize {0}'.format(size)
if options:
if template == 'download':
missing_deps = [x for x in download_template_deps
if x not in options]
if missing_deps:
raise SaltInvocationError(
'Missing params in \'options\' dict: {0}'
.format(', '.join(missing_deps))
)
cmd += ' --'
for key, val in six.iteritems(options):
cmd += ' --{0} {1}'.format(key, val)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
# please do not merge extra conflicting stuff
# inside those two line (ret =, return)
return _after_ignition_network_profile(cmd,
ret,
name,
network_profile,
path,
nic_opts)
def clone(name,
orig,
profile=None,
network_profile=None,
nic_opts=None,
**kwargs):
'''
Create a new container as a clone of another container
name
Name of the container
orig
Name of the original container to be cloned
profile
Profile to use in container cloning (see
:mod:`lxc.get_container_profile
<salt.modules.lxc.get_container_profile>`). Values in a profile will be
overridden by the **Container Cloning Arguments** listed below.
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
**Container Cloning Arguments**
snapshot
Use Copy On Write snapshots (LVM)
size : 1G
Size of the volume to create. Only applicable if ``backing=lvm``.
backing
The type of storage to use. Set to ``lvm`` to use an LVM group.
Defaults to filesystem within /var/lib/lxc.
network_profile
Network profile to use for container
.. versionadded:: 2015.8.0
nic_opts
give extra opts overriding network profile values
.. versionadded:: 2015.8.0
CLI Examples:
.. code-block:: bash
salt '*' lxc.clone myclone orig=orig_container
salt '*' lxc.clone myclone orig=orig_container snapshot=True
'''
profile = get_container_profile(copy.deepcopy(profile))
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, None)
profile_match = profile.pop(key, default)
# let kwarg overrides be the preferred choice
if kw_overrides_match is None:
return profile_match
return kw_overrides_match
path = select('path')
if exists(name, path=path):
raise CommandExecutionError(
'Container \'{0}\' already exists'.format(name)
)
_ensure_exists(orig, path=path)
if state(orig, path=path) != 'stopped':
raise CommandExecutionError(
'Container \'{0}\' must be stopped to be cloned'.format(orig)
)
backing = select('backing')
snapshot = select('snapshot')
if backing in ('dir',):
snapshot = False
if not snapshot:
snapshot = ''
else:
snapshot = '-s'
size = select('size', '1G')
if backing in ('dir', 'overlayfs', 'btrfs'):
size = None
# LXC commands and options changed in 2.0 - CF issue #34086 for details
if _LooseVersion(version()) >= _LooseVersion('2.0'):
# https://linuxcontainers.org/lxc/manpages//man1/lxc-copy.1.html
cmd = 'lxc-copy'
cmd += ' {0} -n {1} -N {2}'.format(snapshot, orig, name)
else:
# https://linuxcontainers.org/lxc/manpages//man1/lxc-clone.1.html
cmd = 'lxc-clone'
cmd += ' {0} -o {1} -n {2}'.format(snapshot, orig, name)
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
if not os.path.exists(path):
os.makedirs(path)
if backing:
backing = backing.lower()
cmd += ' -B {0}'.format(backing)
if backing not in ('dir', 'overlayfs'):
if size:
cmd += ' -L {0}'.format(size)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
# please do not merge extra conflicting stuff
# inside those two line (ret =, return)
return _after_ignition_network_profile(cmd,
ret,
name,
network_profile,
path,
nic_opts)
def ls_(active=None, cache=True, path=None):
'''
Return a list of the containers available on the minion
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
active
If ``True``, return only active (i.e. running) containers
.. versionadded:: 2015.5.0
CLI Example:
.. code-block:: bash
salt '*' lxc.ls
salt '*' lxc.ls active=True
'''
contextvar = 'lxc.ls{0}'.format(path)
if active:
contextvar += '.active'
if cache and (contextvar in __context__):
return __context__[contextvar]
else:
ret = []
cmd = 'lxc-ls'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
if active:
cmd += ' --active'
output = __salt__['cmd.run_stdout'](cmd, python_shell=False)
for line in output.splitlines():
ret.extend(line.split())
__context__[contextvar] = ret
return ret
def _change_state(cmd,
name,
expected,
stdin=_marker,
stdout=_marker,
stderr=_marker,
with_communicate=_marker,
use_vt=_marker,
path=None):
pre = state(name, path=path)
if pre == expected:
return {'result': True,
'state': {'old': expected, 'new': expected},
'comment': 'Container \'{0}\' already {1}'
.format(name, expected)}
if cmd == 'lxc-destroy':
# Kill the container first
scmd = 'lxc-stop'
if path:
scmd += ' -P {0}'.format(pipes.quote(path))
scmd += ' -k -n {0}'.format(name)
__salt__['cmd.run'](scmd,
python_shell=False)
if path and ' -P ' not in cmd:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0}'.format(name)
# certain lxc commands need to be taken with care (lxc-start)
# as te command itself mess with double forks; we must not
# communicate with it, but just wait for the exit status
pkwargs = {'python_shell': False,
'redirect_stderr': True,
'with_communicate': with_communicate,
'use_vt': use_vt,
'stdin': stdin,
'stdout': stdout}
for i in [a for a in pkwargs]:
val = pkwargs[i]
if val is _marker:
pkwargs.pop(i, None)
_cmdout = __salt__['cmd.run_all'](cmd, **pkwargs)
if _cmdout['retcode'] != 0:
raise CommandExecutionError(
'Error changing state for container \'{0}\' using command '
'\'{1}\': {2}'.format(name, cmd, _cmdout['stdout'])
)
if expected is not None:
# some commands do not wait, so we will
rcmd = 'lxc-wait'
if path:
rcmd += ' -P {0}'.format(pipes.quote(path))
rcmd += ' -n {0} -s {1}'.format(name, expected.upper())
__salt__['cmd.run'](rcmd, python_shell=False, timeout=30)
_clear_context()
post = state(name, path=path)
ret = {'result': post == expected,
'state': {'old': pre, 'new': post}}
return ret
def _ensure_exists(name, path=None):
'''
Raise an exception if the container does not exist
'''
if not exists(name, path=path):
raise CommandExecutionError(
'Container \'{0}\' does not exist'.format(name)
)
def _ensure_running(name, no_start=False, path=None):
'''
If the container is not currently running, start it. This function returns
the state that the container was in before changing
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
'''
_ensure_exists(name, path=path)
pre = state(name, path=path)
if pre == 'running':
# This will be a no-op but running the function will give us a pretty
# return dict.
return start(name, path=path)
elif pre == 'stopped':
if no_start:
raise CommandExecutionError(
'Container \'{0}\' is not running'.format(name)
)
return start(name, path=path)
elif pre == 'frozen':
if no_start:
raise CommandExecutionError(
'Container \'{0}\' is not running'.format(name)
)
return unfreeze(name, path=path)
def restart(name, path=None, lxc_config=None, force=False):
'''
.. versionadded:: 2015.5.0
Restart the named container. If the container was not running, the
container will merely be started.
name
The name of the container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
lxc_config
path to a lxc config file
config file will be guessed from container name otherwise
.. versionadded:: 2015.8.0
force : False
If ``True``, the container will be force-stopped instead of gracefully
shut down
CLI Example:
.. code-block:: bash
salt myminion lxc.restart name
'''
_ensure_exists(name, path=path)
orig_state = state(name, path=path)
if orig_state != 'stopped':
stop(name, kill=force, path=path)
ret = start(name, path=path, lxc_config=lxc_config)
ret['state']['old'] = orig_state
if orig_state != 'stopped':
ret['restarted'] = True
return ret
def start(name, **kwargs):
'''
Start the named container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
lxc_config
path to a lxc config file
config file will be guessed from container name otherwise
.. versionadded:: 2015.8.0
use_vt
run the command through VT
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.start name
'''
path = kwargs.get('path', None)
cpath = get_root_path(path)
lxc_config = kwargs.get('lxc_config', None)
cmd = 'lxc-start'
if not lxc_config:
lxc_config = os.path.join(cpath, name, 'config')
# we try to start, even without config, if global opts are there
if os.path.exists(lxc_config):
cmd += ' -f {0}'.format(pipes.quote(lxc_config))
cmd += ' -d'
_ensure_exists(name, path=path)
if state(name, path=path) == 'frozen':
raise CommandExecutionError(
'Container \'{0}\' is frozen, use lxc.unfreeze'.format(name)
)
# lxc-start daemonize itself violently, we must not communicate with it
use_vt = kwargs.get('use_vt', None)
with_communicate = kwargs.get('with_communicate', False)
return _change_state(cmd, name, 'running',
stdout=None,
stderr=None,
stdin=None,
with_communicate=with_communicate,
path=path,
use_vt=use_vt)
def stop(name, kill=False, path=None, use_vt=None):
'''
Stop the named container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
kill: False
Do not wait for the container to stop, kill all tasks in the container.
Older LXC versions will stop containers like this irrespective of this
argument.
.. versionchanged:: 2015.5.0
Default value changed to ``False``
use_vt
run the command through VT
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.stop name
'''
_ensure_exists(name, path=path)
orig_state = state(name, path=path)
if orig_state == 'frozen' and not kill:
# Gracefully stopping a frozen container is slower than unfreezing and
# then stopping it (at least in my testing), so if we're not
# force-stopping the container, unfreeze it first.
unfreeze(name, path=path)
cmd = 'lxc-stop'
if kill:
cmd += ' -k'
ret = _change_state(cmd, name, 'stopped', use_vt=use_vt, path=path)
ret['state']['old'] = orig_state
return ret
def freeze(name, **kwargs):
'''
Freeze the named container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
start : False
If ``True`` and the container is stopped, the container will be started
before attempting to freeze.
.. versionadded:: 2015.5.0
use_vt
run the command through VT
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.freeze name
'''
use_vt = kwargs.get('use_vt', None)
path = kwargs.get('path', None)
_ensure_exists(name, path=path)
orig_state = state(name, path=path)
start_ = kwargs.get('start', False)
if orig_state == 'stopped':
if not start_:
raise CommandExecutionError(
'Container \'{0}\' is stopped'.format(name)
)
start(name, path=path)
cmd = 'lxc-freeze'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
ret = _change_state(cmd, name, 'frozen', use_vt=use_vt, path=path)
if orig_state == 'stopped' and start_:
ret['state']['old'] = orig_state
ret['started'] = True
ret['state']['new'] = state(name, path=path)
return ret
def unfreeze(name, path=None, use_vt=None):
'''
Unfreeze the named container.
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
use_vt
run the command through VT
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.unfreeze name
'''
_ensure_exists(name, path=path)
if state(name, path=path) == 'stopped':
raise CommandExecutionError(
'Container \'{0}\' is stopped'.format(name)
)
cmd = 'lxc-unfreeze'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
return _change_state(cmd, name, 'running', path=path, use_vt=use_vt)
def destroy(name, stop=False, path=None):
'''
Destroy the named container.
.. warning::
Destroys all data associated with the container.
path
path to the container parent directory (default: /var/lib/lxc)
.. versionadded:: 2015.8.0
stop : False
If ``True``, the container will be destroyed even if it is
running/frozen.
.. versionchanged:: 2015.5.0
Default value changed to ``False``. This more closely matches the
behavior of ``lxc-destroy(1)``, and also makes it less likely that
an accidental command will destroy a running container that was
being used for important things.
CLI Examples:
.. code-block:: bash
salt '*' lxc.destroy foo
salt '*' lxc.destroy foo stop=True
'''
_ensure_exists(name, path=path)
if not stop and state(name, path=path) != 'stopped':
raise CommandExecutionError(
'Container \'{0}\' is not stopped'.format(name)
)
return _change_state('lxc-destroy', name, None, path=path)
# Compatibility between LXC and nspawn
remove = salt.utils.functools.alias_function(destroy, 'remove')
def exists(name, path=None):
'''
Returns whether the named container exists.
path
path to the container parent directory (default: /var/lib/lxc)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.exists name
'''
_exists = name in ls_(path=path)
# container may be just created but we did cached earlier the
# lxc-ls results
if not _exists:
_exists = name in ls_(cache=False, path=path)
return _exists
def state(name, path=None):
'''
Returns the state of a container.
path
path to the container parent directory (default: /var/lib/lxc)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.state name
'''
# Don't use _ensure_exists() here, it will mess with _change_state()
cachekey = 'lxc.state.{0}{1}'.format(name, path)
try:
return __context__[cachekey]
except KeyError:
if not exists(name, path=path):
__context__[cachekey] = None
else:
cmd = 'lxc-info'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0}'.format(name)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
if ret['retcode'] != 0:
_clear_context()
raise CommandExecutionError(
'Unable to get state of container \'{0}\''.format(name)
)
c_infos = ret['stdout'].splitlines()
c_state = None
for c_info in c_infos:
stat = c_info.split(':')
if stat[0].lower() == 'state':
c_state = stat[1].strip().lower()
break
__context__[cachekey] = c_state
return __context__[cachekey]
def get_parameter(name, parameter, path=None):
'''
Returns the value of a cgroup parameter for a container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.get_parameter container_name memory.limit_in_bytes
'''
_ensure_exists(name, path=path)
cmd = 'lxc-cgroup'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0} {1}'.format(name, parameter)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
if ret['retcode'] != 0:
raise CommandExecutionError(
'Unable to retrieve value for \'{0}\''.format(parameter)
)
return ret['stdout'].strip()
def set_parameter(name, parameter, value, path=None):
'''
Set the value of a cgroup parameter for a container.
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.set_parameter name parameter value
'''
if not exists(name, path=path):
return None
cmd = 'lxc-cgroup'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0} {1} {2}'.format(name, parameter, value)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
if ret['retcode'] != 0:
return False
else:
return True
def info(name, path=None):
'''
Returns information about a container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.info name
'''
cachekey = 'lxc.info.{0}{1}'.format(name, path)
try:
return __context__[cachekey]
except KeyError:
_ensure_exists(name, path=path)
cpath = get_root_path(path)
try:
conf_file = os.path.join(cpath, name, 'config')
except AttributeError:
conf_file = os.path.join(cpath, six.text_type(name), 'config')
if not os.path.isfile(conf_file):
raise CommandExecutionError(
'LXC config file {0} does not exist'.format(conf_file)
)
ret = {}
config = []
with salt.utils.files.fopen(conf_file) as fp_:
for line in fp_:
line = salt.utils.stringutils.to_unicode(line)
comps = [x.strip() for x in
line.split('#', 1)[0].strip().split('=', 1)]
if len(comps) == 2:
config.append(tuple(comps))
ifaces = []
current = None
for key, val in config:
if key == 'lxc.network.type':
current = {'type': val}
ifaces.append(current)
elif not current:
continue
elif key.startswith('lxc.network.'):
current[key.replace('lxc.network.', '', 1)] = val
if ifaces:
ret['nics'] = ifaces
ret['rootfs'] = next(
(x[1] for x in config if x[0] == 'lxc.rootfs'),
None
)
ret['state'] = state(name, path=path)
ret['ips'] = []
ret['public_ips'] = []
ret['private_ips'] = []
ret['public_ipv4_ips'] = []
ret['public_ipv6_ips'] = []
ret['private_ipv4_ips'] = []
ret['private_ipv6_ips'] = []
ret['ipv4_ips'] = []
ret['ipv6_ips'] = []
ret['size'] = None
ret['config'] = conf_file
if ret['state'] == 'running':
try:
limit = int(get_parameter(name, 'memory.limit_in_bytes'))
except (CommandExecutionError, TypeError, ValueError):
limit = 0
try:
usage = int(get_parameter(name, 'memory.usage_in_bytes'))
except (CommandExecutionError, TypeError, ValueError):
usage = 0
free = limit - usage
ret['memory_limit'] = limit
ret['memory_free'] = free
size = run_stdout(name, 'df /', path=path, python_shell=False)
# The size is the 2nd column of the last line
ret['size'] = size.splitlines()[-1].split()[1]
# First try iproute2
ip_cmd = run_all(
name, 'ip link show', path=path, python_shell=False)
if ip_cmd['retcode'] == 0:
ip_data = ip_cmd['stdout']
ip_cmd = run_all(
name, 'ip addr show', path=path, python_shell=False)
ip_data += '\n' + ip_cmd['stdout']
ip_data = salt.utils.network._interfaces_ip(ip_data)
else:
# That didn't work, try ifconfig
ip_cmd = run_all(
name, 'ifconfig', path=path, python_shell=False)
if ip_cmd['retcode'] == 0:
ip_data = \
salt.utils.network._interfaces_ifconfig(
ip_cmd['stdout'])
else:
# Neither was successful, give up
log.warning(
'Unable to run ip or ifconfig in container \'%s\'', name
)
ip_data = {}
ret['ipv4_ips'] = salt.utils.network.ip_addrs(
include_loopback=True,
interface_data=ip_data
)
ret['ipv6_ips'] = salt.utils.network.ip_addrs6(
include_loopback=True,
interface_data=ip_data
)
ret['ips'] = ret['ipv4_ips'] + ret['ipv6_ips']
for address in ret['ipv4_ips']:
if address == '127.0.0.1':
ret['private_ips'].append(address)
ret['private_ipv4_ips'].append(address)
elif salt.utils.cloud.is_public_ip(address):
ret['public_ips'].append(address)
ret['public_ipv4_ips'].append(address)
else:
ret['private_ips'].append(address)
ret['private_ipv4_ips'].append(address)
for address in ret['ipv6_ips']:
if address == '::1' or address.startswith('fe80'):
ret['private_ips'].append(address)
ret['private_ipv6_ips'].append(address)
else:
ret['public_ips'].append(address)
ret['public_ipv6_ips'].append(address)
for key in [x for x in ret if x == 'ips' or x.endswith('ips')]:
ret[key].sort(key=_ip_sort)
__context__[cachekey] = ret
return __context__[cachekey]
def set_password(name, users, password, encrypted=True, path=None):
'''
.. versionchanged:: 2015.5.0
Function renamed from ``set_pass`` to ``set_password``. Additionally,
this function now supports (and defaults to using) a password hash
instead of a plaintext password.
Set the password of one or more system users inside containers
users
Comma-separated list (or python list) of users to change password
password
Password to set for the specified user(s)
encrypted : True
If true, ``password`` must be a password hash. Set to ``False`` to set
a plaintext password (not recommended).
.. versionadded:: 2015.5.0
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.set_pass container-name root '$6$uJ2uAyLU$KoI67t8As/0fXtJOPcHKGXmUpcoYUcVR2K6x93walnShTCQvjRwq25yIkiCBOqgbfdKQSFnAo28/ek6716vEV1'
salt '*' lxc.set_pass container-name root foo encrypted=False
'''
def _bad_user_input():
raise SaltInvocationError('Invalid input for \'users\' parameter')
if not isinstance(users, list):
try:
users = users.split(',')
except AttributeError:
_bad_user_input()
if not users:
_bad_user_input()
failed_users = []
for user in users:
result = retcode(name,
'chpasswd{0}'.format(' -e' if encrypted else ''),
stdin=':'.join((user, password)),
python_shell=False,
path=path,
chroot_fallback=True,
output_loglevel='quiet')
if result != 0:
failed_users.append(user)
if failed_users:
raise CommandExecutionError(
'Password change failed for the following user(s): {0}'
.format(', '.join(failed_users))
)
return True
set_pass = salt.utils.functools.alias_function(set_password, 'set_pass')
def update_lxc_conf(name, lxc_conf, lxc_conf_unset, path=None):
'''
Edit LXC configuration options
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.update_lxc_conf ubuntu \\
lxc_conf="[{'network.ipv4.ip':'10.0.3.5'}]" \\
lxc_conf_unset="['lxc.utsname']"
'''
_ensure_exists(name, path=path)
cpath = get_root_path(path)
lxc_conf_p = os.path.join(cpath, name, 'config')
if not os.path.exists(lxc_conf_p):
raise SaltInvocationError(
'Configuration file {0} does not exist'.format(lxc_conf_p)
)
changes = {'edited': [], 'added': [], 'removed': []}
ret = {'changes': changes, 'result': True, 'comment': ''}
# do not use salt.utils.files.fopen !
with salt.utils.files.fopen(lxc_conf_p, 'r') as fic:
filtered_lxc_conf = []
for row in lxc_conf:
if not row:
continue
for conf in row:
filtered_lxc_conf.append((conf.strip(),
row[conf].strip()))
ret['comment'] = 'lxc.conf is up to date'
lines = []
orig_config = salt.utils.stringutils.to_unicode(fic.read())
for line in orig_config.splitlines():
if line.startswith('#') or not line.strip():
lines.append([line, ''])
else:
line = line.split('=')
index = line.pop(0)
val = (index.strip(), '='.join(line).strip())
if val not in lines:
lines.append(val)
for key, item in filtered_lxc_conf:
matched = False
for idx, line in enumerate(lines[:]):
if line[0] == key:
matched = True
lines[idx] = (key, item)
if '='.join(line[1:]).strip() != item.strip():
changes['edited'].append(
({line[0]: line[1:]}, {key: item}))
break
if not matched:
if (key, item) not in lines:
lines.append((key, item))
changes['added'].append({key: item})
dest_lxc_conf = []
# filter unset
if lxc_conf_unset:
for line in lines:
for opt in lxc_conf_unset:
if (
not line[0].startswith(opt) and
line not in dest_lxc_conf
):
dest_lxc_conf.append(line)
else:
changes['removed'].append(opt)
else:
dest_lxc_conf = lines
conf = ''
for key, val in dest_lxc_conf:
if not val:
conf += '{0}\n'.format(key)
else:
conf += '{0} = {1}\n'.format(key.strip(), val.strip())
conf_changed = conf != orig_config
chrono = datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S')
if conf_changed:
# DO NOT USE salt.utils.files.fopen here, i got (kiorky)
# problems with lxc configs which were wiped !
with salt.utils.files.fopen('{0}.{1}'.format(lxc_conf_p, chrono), 'w') as wfic:
wfic.write(salt.utils.stringutils.to_str(conf))
with salt.utils.files.fopen(lxc_conf_p, 'w') as wfic:
wfic.write(salt.utils.stringutils.to_str(conf))
ret['comment'] = 'Updated'
ret['result'] = True
if not any(changes[x] for x in changes):
# Ensure an empty changes dict if nothing was modified
ret['changes'] = {}
return ret
def set_dns(name, dnsservers=None, searchdomains=None, path=None):
'''
.. versionchanged:: 2015.5.0
The ``dnsservers`` and ``searchdomains`` parameters can now be passed
as a comma-separated list.
Update /etc/resolv.confo
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.set_dns ubuntu "['8.8.8.8', '4.4.4.4']"
'''
if dnsservers is None:
dnsservers = ['8.8.8.8', '4.4.4.4']
elif not isinstance(dnsservers, list):
try:
dnsservers = dnsservers.split(',')
except AttributeError:
raise SaltInvocationError(
'Invalid input for \'dnsservers\' parameter'
)
if searchdomains is None:
searchdomains = []
elif not isinstance(searchdomains, list):
try:
searchdomains = searchdomains.split(',')
except AttributeError:
raise SaltInvocationError(
'Invalid input for \'searchdomains\' parameter'
)
dns = ['nameserver {0}'.format(x) for x in dnsservers]
dns.extend(['search {0}'.format(x) for x in searchdomains])
dns = '\n'.join(dns) + '\n'
# we may be using resolvconf in the container
# We need to handle that case with care:
# - we create the resolv.conf runtime directory (the
# linked directory) as anyway it will be shadowed when the real
# runned tmpfs mountpoint will be mounted.
# ( /etc/resolv.conf -> ../run/resolvconf/resolv.conf)
# Indeed, it can save us in any other case (running, eg, in a
# bare chroot when repairing or preparing the container for
# operation.
# - We also teach resolvconf to use the aforementioned dns.
# - We finally also set /etc/resolv.conf in all cases
rstr = __salt__['test.random_hash']()
# no tmp here, apparmor won't let us execute !
script = '/sbin/{0}_dns.sh'.format(rstr)
DNS_SCRIPT = "\n".join([
# 'set -x',
'#!/usr/bin/env bash',
'if [ -h /etc/resolv.conf ];then',
' if [ "x$(readlink /etc/resolv.conf)"'
' = "x../run/resolvconf/resolv.conf" ];then',
' if [ ! -d /run/resolvconf/ ];then',
' mkdir -p /run/resolvconf',
' fi',
' cat > /etc/resolvconf/resolv.conf.d/head <<EOF',
dns,
'EOF',
'',
' fi',
'fi',
'cat > /etc/resolv.conf <<EOF',
dns,
'EOF',
''])
result = run_all(
name, 'tee {0}'.format(script), path=path,
stdin=DNS_SCRIPT, python_shell=True)
if result['retcode'] == 0:
result = run_all(
name, 'sh -c "chmod +x {0};{0}"'.format(script),
path=path, python_shell=True)
# blindly delete the setter file
run_all(name,
'sh -c \'if [ -f "{0}" ];then rm -f "{0}";fi\''.format(script),
path=path, python_shell=True)
if result['retcode'] != 0:
error = ('Unable to write to /etc/resolv.conf in container \'{0}\''
.format(name))
if result['stderr']:
error += ': {0}'.format(result['stderr'])
raise CommandExecutionError(error)
return True
def running_systemd(name, cache=True, path=None):
'''
Determine if systemD is running
path
path to the container parent
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.running_systemd ubuntu
'''
k = 'lxc.systemd.test.{0}{1}'.format(name, path)
ret = __context__.get(k, None)
if ret is None or not cache:
rstr = __salt__['test.random_hash']()
# no tmp here, apparmor won't let us execute !
script = '/sbin/{0}_testsystemd.sh'.format(rstr)
# ubuntu already had since trusty some bits of systemd but was
# still using upstart ...
# we need to be a bit more careful that just testing that systemd
# is present
_script = textwrap.dedent(
'''\
#!/usr/bin/env bash
set -x
if ! command -v systemctl 1>/dev/null 2>/dev/null;then exit 2;fi
for i in \\
/run/systemd/journal/dev-log\\
/run/systemd/journal/flushed\\
/run/systemd/journal/kernel-seqnum\\
/run/systemd/journal/socket\\
/run/systemd/journal/stdout\\
/var/run/systemd/journal/dev-log\\
/var/run/systemd/journal/flushed\\
/var/run/systemd/journal/kernel-seqnum\\
/var/run/systemd/journal/socket\\
/var/run/systemd/journal/stdout\\
;do\\
if test -e ${i};then exit 0;fi
done
if test -d /var/systemd/system;then exit 0;fi
exit 2
''')
result = run_all(
name, 'tee {0}'.format(script), path=path,
stdin=_script, python_shell=True)
if result['retcode'] == 0:
result = run_all(name,
'sh -c "chmod +x {0};{0}"'''.format(script),
path=path,
python_shell=True)
else:
raise CommandExecutionError(
'lxc {0} failed to copy initd tester'.format(name))
run_all(name,
'sh -c \'if [ -f "{0}" ];then rm -f "{0}";fi\''
''.format(script),
path=path,
ignore_retcode=True,
python_shell=True)
if result['retcode'] != 0:
error = ('Unable to determine if the container \'{0}\''
' was running systemd, assmuming it is not.'
''.format(name))
if result['stderr']:
error += ': {0}'.format(result['stderr'])
# only cache result if we got a known exit code
if result['retcode'] in (0, 2):
__context__[k] = ret = not result['retcode']
return ret
def systemd_running_state(name, path=None):
'''
Get the operational state of a systemd based container
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.systemd_running_state ubuntu
'''
try:
ret = run_all(name,
'systemctl is-system-running',
path=path,
ignore_retcode=True)['stdout']
except CommandExecutionError:
ret = ''
return ret
def test_sd_started_state(name, path=None):
'''
Test if a systemd container is fully started
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.test_sd_started_state ubuntu
'''
qstate = systemd_running_state(name, path=path)
if qstate in ('initializing', 'starting'):
return False
elif qstate == '':
return None
else:
return True
def test_bare_started_state(name, path=None):
'''
Test if a non systemd container is fully started
For now, it consists only to test if the container is attachable
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.test_bare_started_state ubuntu
'''
try:
ret = run_all(
name, 'ls', path=path, ignore_retcode=True
)['retcode'] == 0
except (CommandExecutionError,):
ret = None
return ret
def wait_started(name, path=None, timeout=300):
'''
Check that the system has fully inited
This is actually very important for systemD based containers
see https://github.com/saltstack/salt/issues/23847
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.wait_started ubuntu
'''
if not exists(name, path=path):
raise CommandExecutionError(
'Container {0} does does exists'.format(name))
if not state(name, path=path) == 'running':
raise CommandExecutionError(
'Container {0} is not running'.format(name))
ret = False
if running_systemd(name, path=path):
test_started = test_sd_started_state
logger = log.error
else:
test_started = test_bare_started_state
logger = log.debug
now = time.time()
expire = now + timeout
now = time.time()
started = test_started(name, path=path)
while time.time() < expire and not started:
time.sleep(0.3)
started = test_started(name, path=path)
if started is None:
logger(
'Assuming %s is started, although we failed to detect that'
' is fully started correctly', name)
ret = True
else:
ret = started
return ret
def _needs_install(name, path=None):
ret = 0
has_minion = retcode(name,
'which salt-minion',
path=path,
ignore_retcode=True)
# we assume that installing is when no minion is running
# but testing the executable presence is not enougth for custom
# installs where the bootstrap can do much more than installing
# the bare salt binaries.
if has_minion:
processes = run_stdout(name, "ps aux", path=path)
if 'salt-minion' not in processes:
ret = 1
else:
retcode(name, 'salt-call --local service.stop salt-minion')
else:
ret = 1
return ret
def bootstrap(name,
config=None,
approve_key=True,
install=True,
pub_key=None,
priv_key=None,
bootstrap_url=None,
force_install=False,
unconditional_install=False,
path=None,
bootstrap_delay=None,
bootstrap_args=None,
bootstrap_shell=None):
'''
Install and configure salt in a container.
config
Minion configuration options. By default, the ``master`` option is set
to the target host's master.
approve_key
Request a pre-approval of the generated minion key. Requires
that the salt-master be configured to either auto-accept all keys or
expect a signing request from the target host. Default: ``True``
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
pub_key
Explicit public key to pressed the minion with (optional).
This can be either a filepath or a string representing the key
priv_key
Explicit private key to pressed the minion with (optional).
This can be either a filepath or a string representing the key
bootstrap_delay
Delay in seconds between end of container creation and bootstrapping.
Useful when waiting for container to obtain a DHCP lease.
.. versionadded:: 2015.5.0
bootstrap_url
url, content or filepath to the salt bootstrap script
bootstrap_args
salt bootstrap script arguments
bootstrap_shell
shell to execute the script into
install
Whether to attempt a full installation of salt-minion if needed.
force_install
Force installation even if salt-minion is detected,
this is the way to run vendor bootstrap scripts even
if a salt minion is already present in the container
unconditional_install
Run the script even if the container seems seeded
CLI Examples:
.. code-block:: bash
salt 'minion' lxc.bootstrap container_name [config=config_data] \\
[approve_key=(True|False)] [install=(True|False)]
'''
wait_started(name, path=path)
if bootstrap_delay is not None:
try:
log.info('LXC %s: bootstrap_delay: %s', name, bootstrap_delay)
time.sleep(bootstrap_delay)
except TypeError:
# Bad input, but assume since a value was passed that
# a delay was desired, and sleep for 5 seconds
time.sleep(5)
c_info = info(name, path=path)
if not c_info:
return None
# default set here as we cannot set them
# in def as it can come from a chain of procedures.
if bootstrap_args:
# custom bootstrap args can be totally customized, and user could
# have inserted the placeholder for the config directory.
# For example, some salt bootstrap script do not use at all -c
if '{0}' not in bootstrap_args:
bootstrap_args += ' -c {0}'
else:
bootstrap_args = '-c {0}'
if not bootstrap_shell:
bootstrap_shell = 'sh'
orig_state = _ensure_running(name, path=path)
if not orig_state:
return orig_state
if not force_install:
needs_install = _needs_install(name, path=path)
else:
needs_install = True
seeded = retcode(name,
'test -e \'{0}\''.format(SEED_MARKER),
path=path,
chroot_fallback=True,
ignore_retcode=True) == 0
tmp = tempfile.mkdtemp()
if seeded and not unconditional_install:
ret = True
else:
ret = False
cfg_files = __salt__['seed.mkconfig'](
config, tmp=tmp, id_=name, approve_key=approve_key,
pub_key=pub_key, priv_key=priv_key)
if needs_install or force_install or unconditional_install:
if install:
rstr = __salt__['test.random_hash']()
configdir = '/var/tmp/.c_{0}'.format(rstr)
cmd = 'install -m 0700 -d {0}'.format(configdir)
if run_all(
name, cmd, path=path, python_shell=False
)['retcode'] != 0:
log.error('tmpdir %s creation failed %s', configdir, cmd)
return False
bs_ = __salt__['config.gather_bootstrap_script'](
bootstrap=bootstrap_url)
script = '/sbin/{0}_bootstrap.sh'.format(rstr)
copy_to(name, bs_, script, path=path)
result = run_all(name,
'sh -c "chmod +x {0}"'.format(script),
path=path,
python_shell=True)
copy_to(name, cfg_files['config'],
os.path.join(configdir, 'minion'),
path=path)
copy_to(name, cfg_files['privkey'],
os.path.join(configdir, 'minion.pem'),
path=path)
copy_to(name, cfg_files['pubkey'],
os.path.join(configdir, 'minion.pub'),
path=path)
bootstrap_args = bootstrap_args.format(configdir)
cmd = ('{0} {2} {1}'
.format(bootstrap_shell,
bootstrap_args.replace("'", "''"),
script))
# log ASAP the forged bootstrap command which can be wrapped
# out of the output in case of unexpected problem
log.info('Running %s in LXC container \'%s\'', cmd, name)
ret = retcode(name, cmd, output_loglevel='info',
path=path, use_vt=True) == 0
run_all(name,
'sh -c \'if [ -f "{0}" ];then rm -f "{0}";fi\''
''.format(script),
path=path,
ignore_retcode=True,
python_shell=True)
else:
ret = False
else:
minion_config = salt.config.minion_config(cfg_files['config'])
pki_dir = minion_config['pki_dir']
copy_to(name,
cfg_files['config'],
'/etc/salt/minion',
path=path)
copy_to(name,
cfg_files['privkey'],
os.path.join(pki_dir, 'minion.pem'),
path=path)
copy_to(name,
cfg_files['pubkey'],
os.path.join(pki_dir, 'minion.pub'),
path=path)
run(name,
'salt-call --local service.enable salt-minion',
path=path,
python_shell=False)
ret = True
shutil.rmtree(tmp)
if orig_state == 'stopped':
stop(name, path=path)
elif orig_state == 'frozen':
freeze(name, path=path)
# mark seeded upon successful install
if ret:
run(name,
'touch \'{0}\''.format(SEED_MARKER),
path=path,
python_shell=False)
return ret
def attachable(name, path=None):
'''
Return True if the named container can be attached to via the lxc-attach
command
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt 'minion' lxc.attachable ubuntu
'''
cachekey = 'lxc.attachable{0}{1}'.format(name, path)
try:
return __context__[cachekey]
except KeyError:
_ensure_exists(name, path=path)
# Can't use run() here because it uses attachable() and would
# endlessly recurse, resulting in a traceback
log.debug('Checking if LXC container %s is attachable', name)
cmd = 'lxc-attach'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' --clear-env -n {0} -- /usr/bin/env'.format(name)
result = __salt__['cmd.retcode'](cmd,
python_shell=False,
output_loglevel='quiet',
ignore_retcode=True) == 0
__context__[cachekey] = result
return __context__[cachekey]
def _run(name,
cmd,
output=None,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=None,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
Common logic for lxc.run functions
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
'''
orig_state = state(name, path=path)
try:
if attachable(name, path=path):
ret = __salt__['container_resource.run'](
name,
cmd,
path=path,
container_type=__virtualname__,
exec_driver=EXEC_DRIVER,
output=output,
no_start=no_start,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
ignore_retcode=ignore_retcode,
use_vt=use_vt,
keep_env=keep_env)
else:
if not chroot_fallback:
raise CommandExecutionError(
'{0} is not attachable.'.format(name))
rootfs = info(name, path=path).get('rootfs')
# Set context var to make cmd.run_chroot run cmd.run instead of
# cmd.run_all.
__context__['cmd.run_chroot.func'] = __salt__['cmd.run']
ret = __salt__['cmd.run_chroot'](rootfs,
cmd,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
ignore_retcode=ignore_retcode)
except Exception:
raise
finally:
# Make sure we honor preserve_state, even if there was an exception
new_state = state(name, path=path)
if preserve_state:
if orig_state == 'stopped' and new_state != 'stopped':
stop(name, path=path)
elif orig_state == 'frozen' and new_state != 'frozen':
freeze(name, start=True, path=path)
if output in (None, 'all'):
return ret
else:
return ret[output]
def run(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.8.0
Run :mod:`cmd.run <salt.modules.cmdmod.run>` within a container
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed in stderr if the command being run
does not exist. If no output is returned using this function, try using
:mod:`lxc.run_stderr <salt.modules.lxc.run_stderr>` or
:mod:`lxc.run_all <salt.modules.lxc.run_all>`.
name
Name of the container in which to run the command
cmd
Command to run
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console. Assumes
``output=all``.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
CLI Example:
.. code-block:: bash
salt myminion lxc.run mycontainer 'ifconfig -a'
'''
return _run(name,
cmd,
path=path,
output=None,
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def run_stdout(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.5.0
Run :mod:`cmd.run_stdout <salt.modules.cmdmod.run_stdout>` within a container
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed in stderr if the command being run
does not exist. If no output is returned using this function, try using
:mod:`lxc.run_stderr <salt.modules.lxc.run_stderr>` or
:mod:`lxc.run_all <salt.modules.lxc.run_all>`.
name
Name of the container in which to run the command
cmd
Command to run
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console
``output=all``.
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
CLI Example:
.. code-block:: bash
salt myminion lxc.run_stdout mycontainer 'ifconfig -a'
'''
return _run(name,
cmd,
path=path,
output='stdout',
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def run_stderr(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.5.0
Run :mod:`cmd.run_stderr <salt.modules.cmdmod.run_stderr>` within a container
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed if the command being run does not
exist.
name
Name of the container in which to run the command
cmd
Command to run
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console
``output=all``.
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
CLI Example:
.. code-block:: bash
salt myminion lxc.run_stderr mycontainer 'ip addr show'
'''
return _run(name,
cmd,
path=path,
output='stderr',
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def retcode(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.5.0
Run :mod:`cmd.retcode <salt.modules.cmdmod.retcode>` within a container
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed in stderr if the command being run
does not exist. If the retcode is nonzero and not what was expected,
try using :mod:`lxc.run_stderr <salt.modules.lxc.run_stderr>`
or :mod:`lxc.run_all <salt.modules.lxc.run_all>`.
name
Name of the container in which to run the command
cmd
Command to run
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console
``output=all``.
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
CLI Example:
.. code-block:: bash
salt myminion lxc.retcode mycontainer 'ip addr show'
'''
return _run(name,
cmd,
output='retcode',
path=path,
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def run_all(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.5.0
Run :mod:`cmd.run_all <salt.modules.cmdmod.run_all>` within a container
.. note::
While the command is run within the container, it is initiated from the
host. Therefore, the PID in the return dict is from the host, not from
the container.
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed in stderr if the command being run
does not exist.
name
Name of the container in which to run the command
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
cmd
Command to run
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console
``output=all``.
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
CLI Example:
.. code-block:: bash
salt myminion lxc.run_all mycontainer 'ip addr show'
'''
return _run(name,
cmd,
output='all',
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
path=path,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def _get_md5(name, path):
'''
Get the MD5 checksum of a file from a container
'''
output = run_stdout(name, 'md5sum "{0}"'.format(path),
chroot_fallback=True,
ignore_retcode=True)
try:
return output.split()[0]
except IndexError:
# Destination file does not exist or could not be accessed
return None
def copy_to(name, source, dest, overwrite=False, makedirs=False, path=None):
'''
.. versionchanged:: 2015.8.0
Function renamed from ``lxc.cp`` to ``lxc.copy_to`` for consistency
with other container types. ``lxc.cp`` will continue to work, however.
For versions 2015.2.x and earlier, use ``lxc.cp``.
Copy a file or directory from the host into a container
name
Container name
source
File to be copied to the container
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
dest
Destination on the container. Must be an absolute path.
.. versionchanged:: 2015.5.0
If the destination is a directory, the file will be copied into
that directory.
overwrite : False
Unless this option is set to ``True``, then if a file exists at the
location specified by the ``dest`` argument, an error will be raised.
.. versionadded:: 2015.8.0
makedirs : False
Create the parent directory on the container if it does not already
exist.
.. versionadded:: 2015.5.0
CLI Example:
.. code-block:: bash
salt 'minion' lxc.copy_to /tmp/foo /root/foo
salt 'minion' lxc.cp /tmp/foo /root/foo
'''
_ensure_running(name, no_start=True, path=path)
return __salt__['container_resource.copy_to'](
name,
source,
dest,
container_type=__virtualname__,
path=path,
exec_driver=EXEC_DRIVER,
overwrite=overwrite,
makedirs=makedirs)
cp = salt.utils.functools.alias_function(copy_to, 'cp')
def read_conf(conf_file, out_format='simple'):
'''
Read in an LXC configuration file. By default returns a simple, unsorted
dict, but can also return a more detailed structure including blank lines
and comments.
out_format:
set to 'simple' if you need the old and unsupported behavior.
This won't support the multiple lxc values (eg: multiple network nics)
CLI Examples:
.. code-block:: bash
salt 'minion' lxc.read_conf /etc/lxc/mycontainer.conf
salt 'minion' lxc.read_conf /etc/lxc/mycontainer.conf out_format=commented
'''
ret_commented = []
ret_simple = {}
with salt.utils.files.fopen(conf_file, 'r') as fp_:
for line in salt.utils.data.decode(fp_.readlines()):
if '=' not in line:
ret_commented.append(line)
continue
comps = line.split('=')
value = '='.join(comps[1:]).strip()
comment = None
if value.strip().startswith('#'):
vcomps = value.strip().split('#')
value = vcomps[1].strip()
comment = '#'.join(vcomps[1:]).strip()
ret_commented.append({comps[0].strip(): {
'value': value,
'comment': comment,
}})
else:
ret_commented.append({comps[0].strip(): value})
ret_simple[comps[0].strip()] = value
if out_format == 'simple':
return ret_simple
return ret_commented
def write_conf(conf_file, conf):
'''
Write out an LXC configuration file
This is normally only used internally. The format of the data structure
must match that which is returned from ``lxc.read_conf()``, with
``out_format`` set to ``commented``.
An example might look like:
.. code-block:: python
[
{'lxc.utsname': '$CONTAINER_NAME'},
'# This is a commented line\\n',
'\\n',
{'lxc.mount': '$CONTAINER_FSTAB'},
{'lxc.rootfs': {'comment': 'This is another test',
'value': 'This is another test'}},
'\\n',
{'lxc.network.type': 'veth'},
{'lxc.network.flags': 'up'},
{'lxc.network.link': 'br0'},
{'lxc.network.mac': '$CONTAINER_MACADDR'},
{'lxc.network.ipv4': '$CONTAINER_IPADDR'},
{'lxc.network.name': '$CONTAINER_DEVICENAME'},
]
CLI Example:
.. code-block:: bash
salt 'minion' lxc.write_conf /etc/lxc/mycontainer.conf \\
out_format=commented
'''
if not isinstance(conf, list):
raise SaltInvocationError('Configuration must be passed as a list')
# construct the content prior to write to the file
# to avoid half written configs
content = ''
for line in conf:
if isinstance(line, (six.text_type, six.string_types)):
content += line
elif isinstance(line, dict):
for key in list(line.keys()):
out_line = None
if isinstance(
line[key],
(six.text_type, six.string_types, six.integer_types, float)
):
out_line = ' = '.join((key, "{0}".format(line[key])))
elif isinstance(line[key], dict):
out_line = ' = '.join((key, line[key]['value']))
if 'comment' in line[key]:
out_line = ' # '.join((out_line, line[key]['comment']))
if out_line:
content += out_line
content += '\n'
with salt.utils.files.fopen(conf_file, 'w') as fp_:
fp_.write(salt.utils.stringutils.to_str(content))
return {}
def edit_conf(conf_file,
out_format='simple',
read_only=False,
lxc_config=None,
**kwargs):
'''
Edit an LXC configuration file. If a setting is already present inside the
file, its value will be replaced. If it does not exist, it will be appended
to the end of the file. Comments and blank lines will be kept in-tact if
they already exist in the file.
out_format:
Set to simple if you need backward compatibility (multiple items for a
simple key is not supported)
read_only:
return only the edited configuration without applying it
to the underlying lxc configuration file
lxc_config:
List of dict containning lxc configuration items
For network configuration, you also need to add the device it belongs
to, otherwise it will default to eth0.
Also, any change to a network parameter will result in the whole
network reconfiguration to avoid mismatchs, be aware of that !
After the file is edited, its contents will be returned. By default, it
will be returned in ``simple`` format, meaning an unordered dict (which
may not represent the actual file order). Passing in an ``out_format`` of
``commented`` will return a data structure which accurately represents the
order and content of the file.
CLI Example:
.. code-block:: bash
salt 'minion' lxc.edit_conf /etc/lxc/mycontainer.conf \\
out_format=commented lxc.network.type=veth
salt 'minion' lxc.edit_conf /etc/lxc/mycontainer.conf \\
out_format=commented \\
lxc_config="[{'lxc.network.name': 'eth0', \\
'lxc.network.ipv4': '1.2.3.4'},
{'lxc.network.name': 'eth2', \\
'lxc.network.ipv4': '1.2.3.5',\\
'lxc.network.gateway': '1.2.3.1'}]"
'''
data = []
try:
conf = read_conf(conf_file, out_format=out_format)
except Exception:
conf = []
if not lxc_config:
lxc_config = []
lxc_config = copy.deepcopy(lxc_config)
# search if we want to access net config
# in that case, we will replace all the net configuration
net_config = []
for lxc_kws in lxc_config + [kwargs]:
net_params = {}
for kwarg in [a for a in lxc_kws]:
if kwarg.startswith('__'):
continue
if kwarg.startswith('lxc.network.'):
net_params[kwarg] = lxc_kws[kwarg]
lxc_kws.pop(kwarg, None)
if net_params:
net_config.append(net_params)
nic_opts = salt.utils.odict.OrderedDict()
for params in net_config:
dev = params.get('lxc.network.name', DEFAULT_NIC)
dev_opts = nic_opts.setdefault(dev, salt.utils.odict.OrderedDict())
for param in params:
opt = param.replace('lxc.network.', '')
opt = {'hwaddr': 'mac'}.get(opt, opt)
dev_opts[opt] = params[param]
net_changes = []
if nic_opts:
net_changes = _config_list(conf, only_net=True,
**{'network_profile': DEFAULT_NIC,
'nic_opts': nic_opts})
if net_changes:
lxc_config.extend(net_changes)
for line in conf:
if not isinstance(line, dict):
data.append(line)
continue
else:
for key in list(line.keys()):
val = line[key]
if net_changes and key.startswith('lxc.network.'):
continue
found = False
for ix in range(len(lxc_config)):
kw = lxc_config[ix]
if key in kw:
found = True
data.append({key: kw[key]})
del kw[key]
if not found:
data.append({key: val})
for lxc_kws in lxc_config:
for kwarg in lxc_kws:
data.append({kwarg: lxc_kws[kwarg]})
if read_only:
return data
write_conf(conf_file, data)
return read_conf(conf_file, out_format)
def reboot(name, path=None):
'''
Reboot a container.
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Examples:
.. code-block:: bash
salt 'minion' lxc.reboot myvm
'''
ret = {'result': True,
'changes': {},
'comment': '{0} rebooted'.format(name)}
does_exist = exists(name, path=path)
if does_exist and (state(name, path=path) == 'running'):
try:
stop(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
ret['result'] = False
return ret
if does_exist and (state(name, path=path) != 'running'):
try:
start(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
ret['result'] = False
return ret
ret['changes'][name] = 'rebooted'
return ret
def reconfigure(name,
cpu=None,
cpuset=None,
cpushare=None,
memory=None,
profile=None,
network_profile=None,
nic_opts=None,
bridge=None,
gateway=None,
autostart=None,
utsname=None,
rootfs=None,
path=None,
**kwargs):
'''
Reconfigure a container.
This only applies to a few property
name
Name of the container.
utsname
utsname of the container.
.. versionadded:: 2016.3.0
rootfs
rootfs of the container.
.. versionadded:: 2016.3.0
cpu
Select a random number of cpu cores and assign it to the cpuset, if the
cpuset option is set then this option will be ignored
cpuset
Explicitly define the cpus this container will be bound to
cpushare
cgroups cpu shares.
autostart
autostart container on reboot
memory
cgroups memory limit, in MB.
(0 for nolimit, None for old default 1024MB)
gateway
the ipv4 gateway to use
the default does nothing more than lxcutils does
bridge
the bridge to use
the default does nothing more than lxcutils does
nic
Network interfaces profile (defined in config or pillar).
nic_opts
Extra options for network interfaces, will override
``{"eth0": {"mac": "aa:bb:cc:dd:ee:ff", "ipv4": "10.1.1.1", "ipv6": "2001:db8::ff00:42:8329"}}``
or
``{"eth0": {"mac": "aa:bb:cc:dd:ee:ff", "ipv4": "10.1.1.1/24", "ipv6": "2001:db8::ff00:42:8329"}}``
path
path to the container parent
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt-call -lall mc_lxc_fork.reconfigure foobar nic_opts="{'eth1': {'mac': '00:16:3e:dd:ee:44'}}" memory=4
'''
changes = {}
cpath = get_root_path(path)
path = os.path.join(cpath, name, 'config')
ret = {'name': name,
'comment': 'config for {0} up to date'.format(name),
'result': True,
'changes': changes}
profile = get_container_profile(copy.deepcopy(profile))
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, _marker)
profile_match = profile.pop(key, default)
# let kwarg overrides be the preferred choice
if kw_overrides_match is _marker:
return profile_match
return kw_overrides_match
if nic_opts is not None and not network_profile:
network_profile = DEFAULT_NIC
if autostart is not None:
autostart = select('autostart', autostart)
else:
autostart = 'keep'
if not utsname:
utsname = select('utsname', utsname)
if os.path.exists(path):
old_chunks = read_conf(path, out_format='commented')
make_kw = salt.utils.odict.OrderedDict([
('utsname', utsname),
('rootfs', rootfs),
('autostart', autostart),
('cpu', cpu),
('gateway', gateway),
('cpuset', cpuset),
('cpushare', cpushare),
('network_profile', network_profile),
('nic_opts', nic_opts),
('bridge', bridge)])
# match 0 and none as memory = 0 in lxc config is harmful
if memory:
make_kw['memory'] = memory
kw = salt.utils.odict.OrderedDict()
for key, val in six.iteritems(make_kw):
if val is not None:
kw[key] = val
new_cfg = _config_list(conf_tuples=old_chunks, **kw)
if new_cfg:
edit_conf(path, out_format='commented', lxc_config=new_cfg)
chunks = read_conf(path, out_format='commented')
if old_chunks != chunks:
ret['comment'] = '{0} lxc config updated'.format(name)
if state(name, path=path) == 'running':
cret = reboot(name, path=path)
ret['result'] = cret['result']
return ret
def apply_network_profile(name, network_profile, nic_opts=None, path=None):
'''
.. versionadded:: 2015.5.0
Apply a network profile to a container
network_profile
profile name or default values (dict)
nic_opts
values to override in defaults (dict)
indexed by nic card names
path
path to the container parent
.. versionadded:: 2015.8.0
CLI Examples:
.. code-block:: bash
salt 'minion' lxc.apply_network_profile web1 centos
salt 'minion' lxc.apply_network_profile web1 centos \\
nic_opts="{'eth0': {'mac': 'xx:xx:xx:xx:xx:xx'}}"
salt 'minion' lxc.apply_network_profile web1 \\
"{'eth0': {'mac': 'xx:xx:xx:xx:xx:yy'}}"
nic_opts="{'eth0': {'mac': 'xx:xx:xx:xx:xx:xx'}}"
The special case to disable use of ethernet nics:
.. code-block:: bash
salt 'minion' lxc.apply_network_profile web1 centos \\
"{eth0: {disable: true}}"
'''
cpath = get_root_path(path)
cfgpath = os.path.join(cpath, name, 'config')
before = []
with salt.utils.files.fopen(cfgpath, 'r') as fp_:
for line in fp_:
before.append(line)
lxcconfig = _LXCConfig(name=name, path=path)
old_net = lxcconfig._filter_data('lxc.network')
network_params = {}
for param in _network_conf(
conf_tuples=old_net,
network_profile=network_profile, nic_opts=nic_opts
):
network_params.update(param)
if network_params:
edit_conf(cfgpath, out_format='commented', **network_params)
after = []
with salt.utils.files.fopen(cfgpath, 'r') as fp_:
for line in fp_:
after.append(line)
diff = ''
for line in difflib.unified_diff(before,
after,
fromfile='before',
tofile='after'):
diff += line
return diff
def get_pid(name, path=None):
'''
Returns a container pid.
Throw an exception if the container isn't running.
CLI Example:
.. code-block:: bash
salt '*' lxc.get_pid name
'''
if name not in list_(limit='running', path=path):
raise CommandExecutionError('Container {0} is not running, can\'t determine PID'.format(name))
info = __salt__['cmd.run']('lxc-info -n {0}'.format(name)).split("\n")
pid = [line.split(':')[1].strip() for line in info if re.match(r'\s*PID', line)][0]
return pid
def add_veth(name, interface_name, bridge=None, path=None):
'''
Add a veth to a container.
Note : this function doesn't update the container config, just add the interface at runtime
name
Name of the container
interface_name
Name of the interface in the container
bridge
Name of the bridge to attach the interface to (facultative)
CLI Examples:
.. code-block:: bash
salt '*' lxc.add_veth container_name eth1 br1
salt '*' lxc.add_veth container_name eth1
'''
# Get container init PID
pid = get_pid(name, path=path)
# Generate a ramdom string for veth and ensure that is isn't present on the system
while True:
random_veth = 'veth'+''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(6))
if random_veth not in __salt__['network.interfaces']().keys():
break
# Check prerequisites
if not __salt__['file.directory_exists']('/var/run/'):
raise CommandExecutionError('Directory /var/run required for lxc.add_veth doesn\'t exists')
if not __salt__['file.file_exists']('/proc/{0}/ns/net'.format(pid)):
raise CommandExecutionError('Proc file for container {0} network namespace doesn\'t exists'.format(name))
if not __salt__['file.directory_exists']('/var/run/netns'):
__salt__['file.mkdir']('/var/run/netns')
# Ensure that the symlink is up to date (change on container restart)
if __salt__['file.is_link']('/var/run/netns/{0}'.format(name)):
__salt__['file.remove']('/var/run/netns/{0}'.format(name))
__salt__['file.symlink']('/proc/{0}/ns/net'.format(pid), '/var/run/netns/{0}'.format(name))
# Ensure that interface doesn't exists
interface_exists = 0 == __salt__['cmd.retcode']('ip netns exec {netns} ip address list {interface}'.format(
netns=name,
interface=interface_name
))
if interface_exists:
raise CommandExecutionError('Interface {interface} already exists in {container}'.format(
interface=interface_name,
container=name
))
# Create veth and bring it up
if __salt__['cmd.retcode']('ip link add name {veth} type veth peer name {veth}_c'.format(veth=random_veth)) != 0:
raise CommandExecutionError('Error while creating the veth pair {0}'.format(random_veth))
if __salt__['cmd.retcode']('ip link set dev {0} up'.format(random_veth)) != 0:
raise CommandExecutionError('Error while bringing up host-side veth {0}'.format(random_veth))
# Attach it to the container
attached = 0 == __salt__['cmd.retcode']('ip link set dev {veth}_c netns {container} name {interface_name}'.format(
veth=random_veth,
container=name,
interface_name=interface_name
))
if not attached:
raise CommandExecutionError('Error while attaching the veth {veth} to container {container}'.format(
veth=random_veth,
container=name
))
__salt__['file.remove']('/var/run/netns/{0}'.format(name))
if bridge is not None:
__salt__['bridge.addif'](bridge, random_veth)
|
saltstack/salt
|
salt/modules/lxc.py
|
_ensure_exists
|
python
|
def _ensure_exists(name, path=None):
'''
Raise an exception if the container does not exist
'''
if not exists(name, path=path):
raise CommandExecutionError(
'Container \'{0}\' does not exist'.format(name)
)
|
Raise an exception if the container does not exist
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/lxc.py#L2302-L2309
|
[
"def exists(name, path=None):\n '''\n Returns whether the named container exists.\n\n path\n path to the container parent directory (default: /var/lib/lxc)\n\n .. versionadded:: 2015.8.0\n\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' lxc.exists name\n '''\n\n _exists = name in ls_(path=path)\n # container may be just created but we did cached earlier the\n # lxc-ls results\n if not _exists:\n _exists = name in ls_(cache=False, path=path)\n return _exists\n"
] |
# -*- coding: utf-8 -*-
'''
Control Linux Containers via Salt
:depends: lxc package for distribution
lxc >= 1.0 (even beta alpha) is required
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import datetime
import copy
import string
import textwrap
import difflib
import logging
import tempfile
import os
import pipes
import time
import shutil
import re
import random
# Import salt libs
import salt.utils.args
import salt.utils.cloud
import salt.utils.data
import salt.utils.dictupdate
import salt.utils.files
import salt.utils.functools
import salt.utils.hashutils
import salt.utils.network
import salt.utils.odict
import salt.utils.path
import salt.utils.stringutils
from salt.exceptions import CommandExecutionError, SaltInvocationError
import salt.config
from salt.utils.versions import LooseVersion as _LooseVersion
# Import 3rd-party libs
from salt.ext import six
# pylint: disable=import-error,no-name-in-module
from salt.ext.six.moves import range # pylint: disable=redefined-builtin
from salt.ext.six.moves.urllib.parse import urlparse as _urlparse
# pylint: enable=import-error,no-name-in-module
# Set up logging
log = logging.getLogger(__name__)
# Don't shadow built-in's.
__func_alias__ = {
'list_': 'list',
'ls_': 'ls'
}
__virtualname__ = 'lxc'
DEFAULT_NIC = 'eth0'
DEFAULT_BR = 'br0'
SEED_MARKER = '/lxc.initial_seed'
EXEC_DRIVER = 'lxc-attach'
DEFAULT_PATH = '/var/lib/lxc'
_marker = object()
def __virtual__():
if salt.utils.path.which('lxc-start'):
return __virtualname__
# To speed up the whole thing, we decided to not use the
# subshell way and assume things are in place for lxc
# Discussion made by @kiorky and @thatch45
# lxc-version presence is not sufficient, in lxc1.0 alpha
# (precise backports), we have it and it is sufficient
# for the module to execute.
# elif salt.utils.path.which('lxc-version'):
# passed = False
# try:
# passed = subprocess.check_output(
# 'lxc-version').split(':')[1].strip() >= '1.0'
# except Exception:
# pass
# if not passed:
# log.warning('Support for lxc < 1.0 may be incomplete.')
# return 'lxc'
# return False
#
return (False, 'The lxc execution module cannot be loaded: the lxc-start binary is not in the path.')
def get_root_path(path):
'''
Get the configured lxc root for containers
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.get_root_path
'''
if not path:
path = __opts__.get('lxc.root_path', DEFAULT_PATH)
return path
def version():
'''
Return the actual lxc client version
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.version
'''
k = 'lxc.version'
if not __context__.get(k, None):
cversion = __salt__['cmd.run_all']('lxc-info --version')
if not cversion['retcode']:
ver = _LooseVersion(cversion['stdout'])
if ver < _LooseVersion('1.0'):
raise CommandExecutionError('LXC should be at least 1.0')
__context__[k] = "{0}".format(ver)
return __context__.get(k, None)
def _clear_context():
'''
Clear any lxc variables set in __context__
'''
for var in [x for x in __context__ if x.startswith('lxc.')]:
log.trace('Clearing __context__[\'%s\']', var)
__context__.pop(var, None)
def _ip_sort(ip):
'''Ip sorting'''
idx = '001'
if ip == '127.0.0.1':
idx = '200'
if ip == '::1':
idx = '201'
elif '::' in ip:
idx = '100'
return '{0}___{1}'.format(idx, ip)
def search_lxc_bridges():
'''
Search which bridges are potentially available as LXC bridges
CLI Example:
.. code-block:: bash
salt '*' lxc.search_lxc_bridges
'''
bridges = __context__.get('lxc.bridges', None)
# either match not yet called or no bridges were found
# to handle the case where lxc was not installed on the first
# call
if not bridges:
bridges = set()
running_bridges = set()
bridges.add(DEFAULT_BR)
try:
output = __salt__['cmd.run_all']('brctl show')
for line in output['stdout'].splitlines()[1:]:
if not line.startswith(' '):
running_bridges.add(line.split()[0].strip())
except (SaltInvocationError, CommandExecutionError):
pass
for ifc, ip in six.iteritems(
__grains__.get('ip_interfaces', {})
):
if ifc in running_bridges:
bridges.add(ifc)
elif os.path.exists(
'/sys/devices/virtual/net/{0}/bridge'.format(ifc)
):
bridges.add(ifc)
bridges = list(bridges)
# if we found interfaces that have lxc in their names
# we filter them as being the potential lxc bridges
# we also try to default on br0 on other cases
def sort_bridges(a):
pref = 'z'
if 'lxc' in a:
pref = 'a'
elif 'br0' == a:
pref = 'c'
return '{0}_{1}'.format(pref, a)
bridges.sort(key=sort_bridges)
__context__['lxc.bridges'] = bridges
return bridges
def search_lxc_bridge():
'''
Search the first bridge which is potentially available as LXC bridge
CLI Example:
.. code-block:: bash
salt '*' lxc.search_lxc_bridge
'''
return search_lxc_bridges()[0]
def _get_salt_config(config, **kwargs):
if not config:
config = kwargs.get('minion', {})
if not config:
config = {}
config.setdefault('master',
kwargs.get('master',
__opts__.get('master',
__opts__['id'])))
config.setdefault(
'master_port',
kwargs.get('master_port',
__opts__.get('master_port',
__opts__.get('ret_port',
__opts__.get('4506')))))
if not config['master']:
config = {}
return config
def cloud_init_interface(name, vm_=None, **kwargs):
'''
Interface between salt.cloud.lxc driver and lxc.init
``vm_`` is a mapping of vm opts in the salt.cloud format
as documented for the lxc driver.
This can be used either:
- from the salt cloud driver
- because you find the argument to give easier here
than using directly lxc.init
.. warning::
BE REALLY CAREFUL CHANGING DEFAULTS !!!
IT'S A RETRO COMPATIBLE INTERFACE WITH
THE SALT CLOUD DRIVER (ask kiorky).
name
name of the lxc container to create
pub_key
public key to preseed the minion with.
Can be the keycontent or a filepath
priv_key
private key to preseed the minion with.
Can be the keycontent or a filepath
path
path to the container parent directory (default: /var/lib/lxc)
.. versionadded:: 2015.8.0
profile
:ref:`profile <tutorial-lxc-profiles-container>` selection
network_profile
:ref:`network profile <tutorial-lxc-profiles-network>` selection
nic_opts
per interface settings compatibles with
network profile (ipv4/ipv6/link/gateway/mac/netmask)
eg::
- {'eth0': {'mac': '00:16:3e:01:29:40',
'gateway': None, (default)
'link': 'br0', (default)
'gateway': None, (default)
'netmask': '', (default)
'ip': '22.1.4.25'}}
unconditional_install
given to lxc.bootstrap (see relative doc)
force_install
given to lxc.bootstrap (see relative doc)
config
any extra argument for the salt minion config
dnsservers
list of DNS servers to set inside the container
dns_via_dhcp
do not set the dns servers, let them be set by the dhcp.
autostart
autostart the container at boot time
password
administrative password for the container
bootstrap_delay
delay before launching bootstrap script at Container init
.. warning::
Legacy but still supported options:
from_container
which container we use as a template
when running lxc.clone
image
which template do we use when we
are using lxc.create. This is the default
mode unless you specify something in from_container
backing
which backing store to use.
Values can be: overlayfs, dir(default), lvm, zfs, brtfs
fstype
When using a blockdevice level backing store,
which filesystem to use on
size
When using a blockdevice level backing store,
which size for the filesystem to use on
snapshot
Use snapshot when cloning the container source
vgname
if using LVM: vgname
lvname
if using LVM: lvname
thinpool:
if using LVM: thinpool
ip
ip for the primary nic
mac
mac address for the primary nic
netmask
netmask for the primary nic (24)
= ``vm_.get('netmask', '24')``
bridge
bridge for the primary nic (lxcbr0)
gateway
network gateway for the container
additional_ips
additional ips which will be wired on the main bridge (br0)
which is connected to internet.
Be aware that you may use manual virtual mac addresses
providen by you provider (online, ovh, etc).
This is a list of mappings {ip: '', mac: '', netmask:''}
Set gateway to None and an interface with a gateway
to escape from another interface that eth0.
eg::
- {'mac': '00:16:3e:01:29:40',
'gateway': None, (default)
'link': 'br0', (default)
'netmask': '', (default)
'ip': '22.1.4.25'}
users
administrative users for the container
default: [root] and [root, ubuntu] on ubuntu
default_nic
name of the first interface, you should
really not override this
CLI Example:
.. code-block:: bash
salt '*' lxc.cloud_init_interface foo
'''
if vm_ is None:
vm_ = {}
vm_ = copy.deepcopy(vm_)
vm_ = salt.utils.dictupdate.update(vm_, kwargs)
profile_data = copy.deepcopy(
vm_.get('lxc_profile',
vm_.get('profile', {})))
if not isinstance(profile_data, (dict, six.string_types)):
profile_data = {}
profile = get_container_profile(profile_data)
def _cloud_get(k, default=None):
return vm_.get(k, profile.get(k, default))
if name is None:
name = vm_['name']
# if we are on ubuntu, default to ubuntu
default_template = ''
if __grains__.get('os', '') in ['Ubuntu']:
default_template = 'ubuntu'
image = _cloud_get('image')
if not image:
_cloud_get('template', default_template)
backing = _cloud_get('backing', 'dir')
if image:
profile['template'] = image
vgname = _cloud_get('vgname', None)
if vgname:
profile['vgname'] = vgname
if backing:
profile['backing'] = backing
snapshot = _cloud_get('snapshot', False)
autostart = bool(_cloud_get('autostart', True))
dnsservers = _cloud_get('dnsservers', [])
dns_via_dhcp = _cloud_get('dns_via_dhcp', True)
password = _cloud_get('password', 's3cr3t')
password_encrypted = _cloud_get('password_encrypted', False)
fstype = _cloud_get('fstype', None)
lvname = _cloud_get('lvname', None)
thinpool = _cloud_get('thinpool', None)
pub_key = _cloud_get('pub_key', None)
priv_key = _cloud_get('priv_key', None)
size = _cloud_get('size', '20G')
script = _cloud_get('script', None)
script_args = _cloud_get('script_args', None)
users = _cloud_get('users', None)
if users is None:
users = []
ssh_username = _cloud_get('ssh_username', None)
if ssh_username and (ssh_username not in users):
users.append(ssh_username)
network_profile = _cloud_get('network_profile', None)
nic_opts = kwargs.get('nic_opts', None)
netmask = _cloud_get('netmask', '24')
path = _cloud_get('path', None)
bridge = _cloud_get('bridge', None)
gateway = _cloud_get('gateway', None)
unconditional_install = _cloud_get('unconditional_install', False)
force_install = _cloud_get('force_install', True)
config = _get_salt_config(_cloud_get('config', {}), **vm_)
default_nic = _cloud_get('default_nic', DEFAULT_NIC)
# do the interface with lxc.init mainly via nic_opts
# to avoid extra and confusing extra use cases.
if not isinstance(nic_opts, dict):
nic_opts = salt.utils.odict.OrderedDict()
# have a reference to the default nic
eth0 = nic_opts.setdefault(default_nic,
salt.utils.odict.OrderedDict())
# lxc config is based of ifc order, be sure to use odicts.
if not isinstance(nic_opts, salt.utils.odict.OrderedDict):
bnic_opts = salt.utils.odict.OrderedDict()
bnic_opts.update(nic_opts)
nic_opts = bnic_opts
gw = None
# legacy salt.cloud scheme for network interfaces settings support
bridge = _cloud_get('bridge', None)
ip = _cloud_get('ip', None)
mac = _cloud_get('mac', None)
if ip:
fullip = ip
if netmask:
fullip += '/{0}'.format(netmask)
eth0['ipv4'] = fullip
if mac is not None:
eth0['mac'] = mac
for ix, iopts in enumerate(_cloud_get("additional_ips", [])):
ifh = "eth{0}".format(ix+1)
ethx = nic_opts.setdefault(ifh, {})
if gw is None:
gw = iopts.get('gateway', ethx.get('gateway', None))
if gw:
# only one and only one default gateway is allowed !
eth0.pop('gateway', None)
gateway = None
# even if the gateway if on default "eth0" nic
# and we popped it will work
# as we reinject or set it here.
ethx['gateway'] = gw
elink = iopts.get('link', ethx.get('link', None))
if elink:
ethx['link'] = elink
# allow dhcp
aip = iopts.get('ipv4', iopts.get('ip', None))
if aip:
ethx['ipv4'] = aip
nm = iopts.get('netmask', '')
if nm:
ethx['ipv4'] += '/{0}'.format(nm)
for i in ('mac', 'hwaddr'):
if i in iopts:
ethx['mac'] = iopts[i]
break
if 'mac' not in ethx:
ethx['mac'] = salt.utils.network.gen_mac()
# last round checking for unique gateway and such
gw = None
for ethx in [a for a in nic_opts]:
ndata = nic_opts[ethx]
if gw:
ndata.pop('gateway', None)
if 'gateway' in ndata:
gw = ndata['gateway']
gateway = None
# only use a default bridge / gateway if we configured them
# via the legacy salt cloud configuration style.
# On other cases, we should rely on settings provided by the new
# salt lxc network profile style configuration which can
# be also be overridden or a per interface basis via the nic_opts dict.
if bridge:
eth0['link'] = bridge
if gateway:
eth0['gateway'] = gateway
#
lxc_init_interface = {}
lxc_init_interface['name'] = name
lxc_init_interface['config'] = config
lxc_init_interface['memory'] = _cloud_get('memory', 0) # nolimit
lxc_init_interface['pub_key'] = pub_key
lxc_init_interface['priv_key'] = priv_key
lxc_init_interface['nic_opts'] = nic_opts
for clone_from in ['clone_from', 'clone', 'from_container']:
# clone_from should default to None if not available
lxc_init_interface['clone_from'] = _cloud_get(clone_from, None)
if lxc_init_interface['clone_from'] is not None:
break
lxc_init_interface['profile'] = profile
lxc_init_interface['snapshot'] = snapshot
lxc_init_interface['dnsservers'] = dnsservers
lxc_init_interface['fstype'] = fstype
lxc_init_interface['path'] = path
lxc_init_interface['vgname'] = vgname
lxc_init_interface['size'] = size
lxc_init_interface['lvname'] = lvname
lxc_init_interface['thinpool'] = thinpool
lxc_init_interface['force_install'] = force_install
lxc_init_interface['unconditional_install'] = (
unconditional_install
)
lxc_init_interface['bootstrap_url'] = script
lxc_init_interface['bootstrap_args'] = script_args
lxc_init_interface['bootstrap_shell'] = _cloud_get('bootstrap_shell', 'sh')
lxc_init_interface['bootstrap_delay'] = _cloud_get('bootstrap_delay', None)
lxc_init_interface['autostart'] = autostart
lxc_init_interface['users'] = users
lxc_init_interface['password'] = password
lxc_init_interface['password_encrypted'] = password_encrypted
# be sure not to let objects goes inside the return
# as this return will be msgpacked for use in the runner !
lxc_init_interface['network_profile'] = network_profile
for i in ['cpu', 'cpuset', 'cpushare']:
if _cloud_get(i, None):
try:
lxc_init_interface[i] = vm_[i]
except KeyError:
lxc_init_interface[i] = profile[i]
return lxc_init_interface
def _get_profile(key, name, **kwargs):
if isinstance(name, dict):
profilename = name.pop('name', None)
return _get_profile(key, profilename, **name)
if name is None:
profile_match = {}
else:
profile_match = \
__salt__['config.get'](
'lxc.{1}:{0}'.format(name, key),
default=None,
merge='recurse'
)
if profile_match is None:
# No matching profile, make the profile an empty dict so that
# overrides can be applied below.
profile_match = {}
if not isinstance(profile_match, dict):
raise CommandExecutionError('lxc.{0} must be a dictionary'.format(key))
# Overlay the kwargs to override matched profile data
overrides = salt.utils.args.clean_kwargs(**copy.deepcopy(kwargs))
profile_match = salt.utils.dictupdate.update(
copy.deepcopy(profile_match),
overrides
)
return profile_match
def get_container_profile(name=None, **kwargs):
'''
.. versionadded:: 2015.5.0
Gather a pre-configured set of container configuration parameters. If no
arguments are passed, an empty profile is returned.
Profiles can be defined in the minion or master config files, or in pillar
or grains, and are loaded using :mod:`config.get
<salt.modules.config.get>`. The key under which LXC profiles must be
configured is ``lxc.container_profile.profile_name``. An example container
profile would be as follows:
.. code-block:: yaml
lxc.container_profile:
ubuntu:
template: ubuntu
backing: lvm
vgname: lxc
size: 1G
Parameters set in a profile can be overridden by passing additional
container creation arguments (such as the ones passed to :mod:`lxc.create
<salt.modules.lxc.create>`) to this function.
A profile can be defined either as the name of the profile, or a dictionary
of variable names and values. See the :ref:`LXC Tutorial
<tutorial-lxc-profiles>` for more information on how to use LXC profiles.
CLI Example:
.. code-block:: bash
salt-call lxc.get_container_profile centos
salt-call lxc.get_container_profile ubuntu template=ubuntu backing=overlayfs
'''
profile = _get_profile('container_profile', name, **kwargs)
return profile
def get_network_profile(name=None, **kwargs):
'''
.. versionadded:: 2015.5.0
Gather a pre-configured set of network configuration parameters. If no
arguments are passed, the following default profile is returned:
.. code-block:: python
{'eth0': {'link': 'br0', 'type': 'veth', 'flags': 'up'}}
Profiles can be defined in the minion or master config files, or in pillar
or grains, and are loaded using :mod:`config.get
<salt.modules.config.get>`. The key under which LXC profiles must be
configured is ``lxc.network_profile``. An example network profile would be
as follows:
.. code-block:: yaml
lxc.network_profile.centos:
eth0:
link: br0
type: veth
flags: up
To disable networking entirely:
.. code-block:: yaml
lxc.network_profile.centos:
eth0:
disable: true
Parameters set in a profile can be overridden by passing additional
arguments to this function.
A profile can be passed either as the name of the profile, or a
dictionary of variable names and values. See the :ref:`LXC Tutorial
<tutorial-lxc-profiles>` for more information on how to use network
profiles.
.. warning::
The ``ipv4``, ``ipv6``, ``gateway``, and ``link`` (bridge) settings in
network profiles will only work if the container doesn't redefine the
network configuration (for example in
``/etc/sysconfig/network-scripts/ifcfg-<interface_name>`` on
RHEL/CentOS, or ``/etc/network/interfaces`` on Debian/Ubuntu/etc.)
CLI Example:
.. code-block:: bash
salt-call lxc.get_network_profile default
'''
profile = _get_profile('network_profile', name, **kwargs)
return profile
def _rand_cpu_str(cpu):
'''
Return a random subset of cpus for the cpuset config
'''
cpu = int(cpu)
avail = __salt__['status.nproc']()
if cpu < avail:
return '0-{0}'.format(avail)
to_set = set()
while len(to_set) < cpu:
choice = random.randint(0, avail - 1)
if choice not in to_set:
to_set.add(six.text_type(choice))
return ','.join(sorted(to_set))
def _network_conf(conf_tuples=None, **kwargs):
'''
Network configuration defaults
network_profile
as for containers, we can either call this function
either with a network_profile dict or network profile name
in the kwargs
nic_opts
overrides or extra nics in the form {nic_name: {set: tings}
'''
nic = kwargs.get('network_profile', None)
ret = []
nic_opts = kwargs.get('nic_opts', {})
if nic_opts is None:
# coming from elsewhere
nic_opts = {}
if not conf_tuples:
conf_tuples = []
old = _get_veths(conf_tuples)
if not old:
old = {}
# if we have a profile name, get the profile and load the network settings
# this will obviously by default look for a profile called "eth0"
# or by what is defined in nic_opts
# and complete each nic settings by sane defaults
if nic and isinstance(nic, (six.string_types, dict)):
nicp = get_network_profile(nic)
else:
nicp = {}
if DEFAULT_NIC not in nicp:
nicp[DEFAULT_NIC] = {}
kwargs = copy.deepcopy(kwargs)
gateway = kwargs.pop('gateway', None)
bridge = kwargs.get('bridge', None)
if nic_opts:
for dev, args in six.iteritems(nic_opts):
ethx = nicp.setdefault(dev, {})
try:
ethx = salt.utils.dictupdate.update(ethx, args)
except AttributeError:
raise SaltInvocationError('Invalid nic_opts configuration')
ifs = [a for a in nicp]
ifs += [a for a in old if a not in nicp]
ifs.sort()
gateway_set = False
for dev in ifs:
args = nicp.get(dev, {})
opts = nic_opts.get(dev, {}) if nic_opts else {}
old_if = old.get(dev, {})
disable = opts.get('disable', args.get('disable', False))
if disable:
continue
mac = opts.get('mac',
opts.get('hwaddr',
args.get('mac',
args.get('hwaddr', ''))))
type_ = opts.get('type', args.get('type', ''))
flags = opts.get('flags', args.get('flags', ''))
link = opts.get('link', args.get('link', ''))
ipv4 = opts.get('ipv4', args.get('ipv4', ''))
ipv6 = opts.get('ipv6', args.get('ipv6', ''))
infos = salt.utils.odict.OrderedDict([
('lxc.network.type', {
'test': not type_,
'value': type_,
'old': old_if.get('lxc.network.type'),
'default': 'veth'}),
('lxc.network.name', {
'test': False,
'value': dev,
'old': dev,
'default': dev}),
('lxc.network.flags', {
'test': not flags,
'value': flags,
'old': old_if.get('lxc.network.flags'),
'default': 'up'}),
('lxc.network.link', {
'test': not link,
'value': link,
'old': old_if.get('lxc.network.link'),
'default': search_lxc_bridge()}),
('lxc.network.hwaddr', {
'test': not mac,
'value': mac,
'old': old_if.get('lxc.network.hwaddr'),
'default': salt.utils.network.gen_mac()}),
('lxc.network.ipv4', {
'test': not ipv4,
'value': ipv4,
'old': old_if.get('lxc.network.ipv4', ''),
'default': None}),
('lxc.network.ipv6', {
'test': not ipv6,
'value': ipv6,
'old': old_if.get('lxc.network.ipv6', ''),
'default': None})])
# for each parameter, if not explicitly set, the
# config value present in the LXC configuration should
# take precedence over the profile configuration
for info in list(infos.keys()):
bundle = infos[info]
if bundle['test']:
if bundle['old']:
bundle['value'] = bundle['old']
elif bundle['default']:
bundle['value'] = bundle['default']
for info, data in six.iteritems(infos):
if data['value']:
ret.append({info: data['value']})
for key, val in six.iteritems(args):
if key == 'link' and bridge:
val = bridge
val = opts.get(key, val)
if key in [
'type', 'flags', 'name',
'gateway', 'mac', 'link', 'ipv4', 'ipv6'
]:
continue
ret.append({'lxc.network.{0}'.format(key): val})
# gateway (in automode) must be appended following network conf !
if not gateway:
gateway = args.get('gateway', None)
if gateway is not None and not gateway_set:
ret.append({'lxc.network.ipv4.gateway': gateway})
# only one network gateway ;)
gateway_set = True
# normally, this won't happen
# set the gateway if specified even if we did
# not managed the network underlying
if gateway is not None and not gateway_set:
ret.append({'lxc.network.ipv4.gateway': gateway})
# only one network gateway ;)
gateway_set = True
new = _get_veths(ret)
# verify that we did not loose the mac settings
for iface in [a for a in new]:
ndata = new[iface]
nmac = ndata.get('lxc.network.hwaddr', '')
ntype = ndata.get('lxc.network.type', '')
omac, otype = '', ''
if iface in old:
odata = old[iface]
omac = odata.get('lxc.network.hwaddr', '')
otype = odata.get('lxc.network.type', '')
# default for network type is setted here
# attention not to change the network type
# without a good and explicit reason to.
if otype and not ntype:
ntype = otype
if not ntype:
ntype = 'veth'
new[iface]['lxc.network.type'] = ntype
if omac and not nmac:
new[iface]['lxc.network.hwaddr'] = omac
ret = []
for val in six.itervalues(new):
for row in val:
ret.append(salt.utils.odict.OrderedDict([(row, val[row])]))
# on old versions of lxc, still support the gateway auto mode
# if we didn't explicitly say no to
# (lxc.network.ipv4.gateway: auto)
if _LooseVersion(version()) <= _LooseVersion('1.0.7') and \
True not in ['lxc.network.ipv4.gateway' in a for a in ret] and \
True in ['lxc.network.ipv4' in a for a in ret]:
ret.append({'lxc.network.ipv4.gateway': 'auto'})
return ret
def _get_lxc_default_data(**kwargs):
kwargs = copy.deepcopy(kwargs)
ret = {}
for k in ['utsname', 'rootfs']:
val = kwargs.get(k, None)
if val is not None:
ret['lxc.{0}'.format(k)] = val
autostart = kwargs.get('autostart')
# autostart can have made in kwargs, but with the None
# value which is invalid, we need an explicit boolean
# autostart = on is the default.
if autostart is None:
autostart = True
# we will set the regular lxc marker to restart container at
# machine (re)boot only if we did not explicitly ask
# not to touch to the autostart settings via
# autostart == 'keep'
if autostart != 'keep':
if autostart:
ret['lxc.start.auto'] = '1'
else:
ret['lxc.start.auto'] = '0'
memory = kwargs.get('memory')
if memory is not None:
# converting the config value from MB to bytes
ret['lxc.cgroup.memory.limit_in_bytes'] = memory * 1024 * 1024
cpuset = kwargs.get('cpuset')
if cpuset:
ret['lxc.cgroup.cpuset.cpus'] = cpuset
cpushare = kwargs.get('cpushare')
cpu = kwargs.get('cpu')
if cpushare:
ret['lxc.cgroup.cpu.shares'] = cpushare
if cpu and not cpuset:
ret['lxc.cgroup.cpuset.cpus'] = _rand_cpu_str(cpu)
return ret
def _config_list(conf_tuples=None, only_net=False, **kwargs):
'''
Return a list of dicts from the salt level configurations
conf_tuples
_LXCConfig compatible list of entries which can contain
- string line
- tuple (lxc config param,value)
- dict of one entry: {lxc config param: value)
only_net
by default we add to the tuples a reflection of both
the real config if avalaible and a certain amount of
default values like the cpu parameters, the memory
and etc.
On the other hand, we also no matter the case reflect
the network configuration computed from the actual config if
available and given values.
if no_default_loads is set, we will only
reflect the network configuration back to the conf tuples
list
'''
# explicit cast
only_net = bool(only_net)
if not conf_tuples:
conf_tuples = []
kwargs = copy.deepcopy(kwargs)
ret = []
if not only_net:
default_data = _get_lxc_default_data(**kwargs)
for k, val in six.iteritems(default_data):
ret.append({k: val})
net_datas = _network_conf(conf_tuples=conf_tuples, **kwargs)
ret.extend(net_datas)
return ret
def _get_veths(net_data):
'''
Parse the nic setup inside lxc conf tuples back to a dictionary indexed by
network interface
'''
if isinstance(net_data, dict):
net_data = list(net_data.items())
nics = salt.utils.odict.OrderedDict()
current_nic = salt.utils.odict.OrderedDict()
no_names = True
for item in net_data:
if item and isinstance(item, dict):
item = list(item.items())[0]
# skip LXC configuration comment lines, and play only with tuples conf
elif isinstance(item, six.string_types):
# deal with reflection of commented lxc configs
sitem = item.strip()
if sitem.startswith('#') or not sitem:
continue
elif '=' in item:
item = tuple([a.strip() for a in item.split('=', 1)])
if item[0] == 'lxc.network.type':
current_nic = salt.utils.odict.OrderedDict()
if item[0] == 'lxc.network.name':
no_names = False
nics[item[1].strip()] = current_nic
current_nic[item[0].strip()] = item[1].strip()
# if not ethernet card name has been collected, assuming we collected
# data for eth0
if no_names and current_nic:
nics[DEFAULT_NIC] = current_nic
return nics
class _LXCConfig(object):
'''
LXC configuration data
'''
pattern = re.compile(r'^(\S+)(\s*)(=)(\s*)(.*)')
non_interpretable_pattern = re.compile(r'^((#.*)|(\s*))$')
def __init__(self, **kwargs):
kwargs = copy.deepcopy(kwargs)
self.name = kwargs.pop('name', None)
path = get_root_path(kwargs.get('path', None))
self.data = []
if self.name:
self.path = os.path.join(path, self.name, 'config')
if os.path.isfile(self.path):
with salt.utils.files.fopen(self.path) as fhr:
for line in salt.utils.data.decode(fhr.readlines()):
match = self.pattern.findall((line.strip()))
if match:
self.data.append((match[0][0], match[0][-1]))
match = self.non_interpretable_pattern.findall(
(line.strip()))
if match:
self.data.append(('', match[0][0]))
else:
self.path = None
def _replace(key, val):
if val:
self._filter_data(key)
self.data.append((key, val))
default_data = _get_lxc_default_data(**kwargs)
for key, val in six.iteritems(default_data):
_replace(key, val)
old_net = self._filter_data('lxc.network')
net_datas = _network_conf(conf_tuples=old_net, **kwargs)
if net_datas:
for row in net_datas:
self.data.extend(list(row.items()))
# be sure to reset harmful settings
for idx in ['lxc.cgroup.memory.limit_in_bytes']:
if not default_data.get(idx):
self._filter_data(idx)
def as_string(self):
chunks = ('{0[0]}{1}{0[1]}'.format(item, (' = ' if item[0] else '')) for item in self.data)
return '\n'.join(chunks) + '\n'
def write(self):
if self.path:
content = self.as_string()
# 2 step rendering to be sure not to open/wipe the config
# before as_string succeeds.
with salt.utils.files.fopen(self.path, 'w') as fic:
fic.write(salt.utils.stringutils.to_str(content))
fic.flush()
def tempfile(self):
# this might look like the function name is shadowing the
# module, but it's not since the method belongs to the class
ntf = tempfile.NamedTemporaryFile()
ntf.write(self.as_string())
ntf.flush()
return ntf
def _filter_data(self, pattern):
'''
Removes parameters which match the pattern from the config data
'''
removed = []
filtered = []
for param in self.data:
if not param[0].startswith(pattern):
filtered.append(param)
else:
removed.append(param)
self.data = filtered
return removed
def _get_base(**kwargs):
'''
If the needed base does not exist, then create it, if it does exist
create nothing and return the name of the base lxc container so
it can be cloned.
'''
profile = get_container_profile(copy.deepcopy(kwargs.get('profile')))
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, _marker)
profile_match = profile.pop(key, default)
# let kwarg overrides be the preferred choice
if kw_overrides_match is _marker:
return profile_match
return kw_overrides_match
template = select('template')
image = select('image')
vgname = select('vgname')
path = kwargs.get('path', None)
# remove the above three variables from kwargs, if they exist, to avoid
# duplicates if create() is invoked below.
for param in ('path', 'image', 'vgname', 'template'):
kwargs.pop(param, None)
if image:
proto = _urlparse(image).scheme
img_tar = __salt__['cp.cache_file'](image)
img_name = os.path.basename(img_tar)
hash_ = salt.utils.hashutils.get_hash(
img_tar,
__salt__['config.get']('hash_type'))
name = '__base_{0}_{1}_{2}'.format(proto, img_name, hash_)
if not exists(name, path=path):
create(name, template=template, image=image,
path=path, vgname=vgname, **kwargs)
if vgname:
rootfs = os.path.join('/dev', vgname, name)
edit_conf(info(name, path=path)['config'],
out_format='commented', **{'lxc.rootfs': rootfs})
return name
elif template:
name = '__base_{0}'.format(template)
if not exists(name, path=path):
create(name, template=template, image=image, path=path,
vgname=vgname, **kwargs)
if vgname:
rootfs = os.path.join('/dev', vgname, name)
edit_conf(info(name, path=path)['config'],
out_format='commented', **{'lxc.rootfs': rootfs})
return name
return ''
def init(name,
config=None,
cpuset=None,
cpushare=None,
memory=None,
profile=None,
network_profile=None,
nic_opts=None,
cpu=None,
autostart=True,
password=None,
password_encrypted=None,
users=None,
dnsservers=None,
searchdomains=None,
bridge=None,
gateway=None,
pub_key=None,
priv_key=None,
force_install=False,
unconditional_install=False,
bootstrap_delay=None,
bootstrap_args=None,
bootstrap_shell=None,
bootstrap_url=None,
**kwargs):
'''
Initialize a new container.
This is a partial idempotent function as if it is already provisioned, we
will reset a bit the lxc configuration file but much of the hard work will
be escaped as markers will prevent re-execution of harmful tasks.
name
Name of the container
image
A tar archive to use as the rootfs for the container. Conflicts with
the ``template`` argument.
cpus
Select a random number of cpu cores and assign it to the cpuset, if the
cpuset option is set then this option will be ignored
cpuset
Explicitly define the cpus this container will be bound to
cpushare
cgroups cpu shares
autostart
autostart container on reboot
memory
cgroups memory limit, in MB
.. versionchanged:: 2015.5.0
If no value is passed, no limit is set. In earlier Salt versions,
not passing this value causes a 1024MB memory limit to be set, and
it was necessary to pass ``memory=0`` to set no limit.
gateway
the ipv4 gateway to use
the default does nothing more than lxcutils does
bridge
the bridge to use
the default does nothing more than lxcutils does
network_profile
Network profile to use for the container
.. versionadded:: 2015.5.0
nic_opts
Extra options for network interfaces, will override
``{"eth0": {"hwaddr": "aa:bb:cc:dd:ee:ff", "ipv4": "10.1.1.1", "ipv6": "2001:db8::ff00:42:8329"}}``
or
``{"eth0": {"hwaddr": "aa:bb:cc:dd:ee:ff", "ipv4": "10.1.1.1/24", "ipv6": "2001:db8::ff00:42:8329"}}``
users
Users for which the password defined in the ``password`` param should
be set. Can be passed as a comma separated list or a python list.
Defaults to just the ``root`` user.
password
Set the initial password for the users defined in the ``users``
parameter
password_encrypted : False
Set to ``True`` to denote a password hash instead of a plaintext
password
.. versionadded:: 2015.5.0
profile
A LXC profile (defined in config or pillar).
This can be either a real profile mapping or a string
to retrieve it in configuration
start
Start the newly-created container
dnsservers
list of dns servers to set in the container, default [] (no setting)
seed
Seed the container with the minion config. Default: ``True``
install
If salt-minion is not already installed, install it. Default: ``True``
config
Optional config parameters. By default, the id is set to
the name of the container.
master
salt master (default to minion's master)
master_port
salt master port (default to minion's master port)
pub_key
Explicit public key to preseed the minion with (optional).
This can be either a filepath or a string representing the key
priv_key
Explicit private key to preseed the minion with (optional).
This can be either a filepath or a string representing the key
approve_key
If explicit preseeding is not used;
Attempt to request key approval from the master. Default: ``True``
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
clone_from
Original from which to use a clone operation to create the container.
Default: ``None``
bootstrap_delay
Delay in seconds between end of container creation and bootstrapping.
Useful when waiting for container to obtain a DHCP lease.
.. versionadded:: 2015.5.0
bootstrap_url
See lxc.bootstrap
bootstrap_shell
See lxc.bootstrap
bootstrap_args
See lxc.bootstrap
force_install
Force installation even if salt-minion is detected,
this is the way to run vendor bootstrap scripts even
if a salt minion is already present in the container
unconditional_install
Run the script even if the container seems seeded
CLI Example:
.. code-block:: bash
salt 'minion' lxc.init name [cpuset=cgroups_cpuset] \\
[cpushare=cgroups_cpushare] [memory=cgroups_memory] \\
[nic=nic_profile] [profile=lxc_profile] \\
[nic_opts=nic_opts] [start=(True|False)] \\
[seed=(True|False)] [install=(True|False)] \\
[config=minion_config] [approve_key=(True|False) \\
[clone_from=original] [autostart=True] \\
[priv_key=/path_or_content] [pub_key=/path_or_content] \\
[bridge=lxcbr0] [gateway=10.0.3.1] \\
[dnsservers[dns1,dns2]] \\
[users=[foo]] [password='secret'] \\
[password_encrypted=(True|False)]
'''
ret = {'name': name,
'changes': {}}
profile = get_container_profile(copy.deepcopy(profile))
if not network_profile:
network_profile = profile.get('network_profile')
if not network_profile:
network_profile = DEFAULT_NIC
# Changes is a pointer to changes_dict['init']. This method is used so that
# we can have a list of changes as they are made, providing an ordered list
# of things that were changed.
changes_dict = {'init': []}
changes = changes_dict.get('init')
if users is None:
users = []
dusers = ['root']
for user in dusers:
if user not in users:
users.append(user)
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, _marker)
profile_match = profile.pop(key, default)
# let kwarg overrides be the preferred choice
if kw_overrides_match is _marker:
return profile_match
return kw_overrides_match
path = select('path')
bpath = get_root_path(path)
state_pre = state(name, path=path)
tvg = select('vgname')
vgname = tvg if tvg else __salt__['config.get']('lxc.vgname')
start_ = select('start', True)
autostart = select('autostart', autostart)
seed = select('seed', True)
install = select('install', True)
seed_cmd = select('seed_cmd')
salt_config = _get_salt_config(config, **kwargs)
approve_key = select('approve_key', True)
clone_from = select('clone_from')
# If using a volume group then set up to make snapshot cow clones
if vgname and not clone_from:
try:
kwargs['vgname'] = vgname
clone_from = _get_base(profile=profile, **kwargs)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = exc.strerror
if changes:
ret['changes'] = changes_dict
return ret
if not kwargs.get('snapshot') is False:
kwargs['snapshot'] = True
does_exist = exists(name, path=path)
to_reboot = False
remove_seed_marker = False
if does_exist:
pass
elif clone_from:
remove_seed_marker = True
try:
clone(name, clone_from, profile=profile, **kwargs)
changes.append({'create': 'Container cloned'})
except (SaltInvocationError, CommandExecutionError) as exc:
if 'already exists' in exc.strerror:
changes.append({'create': 'Container already exists'})
else:
ret['result'] = False
ret['comment'] = exc.strerror
if changes:
ret['changes'] = changes_dict
return ret
cfg = _LXCConfig(name=name, network_profile=network_profile,
nic_opts=nic_opts, bridge=bridge, path=path,
gateway=gateway, autostart=autostart,
cpuset=cpuset, cpushare=cpushare, memory=memory)
old_chunks = read_conf(cfg.path, out_format='commented')
cfg.write()
chunks = read_conf(cfg.path, out_format='commented')
if old_chunks != chunks:
to_reboot = True
else:
remove_seed_marker = True
cfg = _LXCConfig(network_profile=network_profile,
nic_opts=nic_opts, cpuset=cpuset, path=path,
bridge=bridge, gateway=gateway,
autostart=autostart,
cpushare=cpushare, memory=memory)
with cfg.tempfile() as cfile:
try:
create(name, config=cfile.name, profile=profile, **kwargs)
changes.append({'create': 'Container created'})
except (SaltInvocationError, CommandExecutionError) as exc:
if 'already exists' in exc.strerror:
changes.append({'create': 'Container already exists'})
else:
ret['comment'] = exc.strerror
if changes:
ret['changes'] = changes_dict
return ret
cpath = os.path.join(bpath, name, 'config')
old_chunks = []
if os.path.exists(cpath):
old_chunks = read_conf(cpath, out_format='commented')
new_cfg = _config_list(conf_tuples=old_chunks,
cpu=cpu,
network_profile=network_profile,
nic_opts=nic_opts, bridge=bridge,
cpuset=cpuset, cpushare=cpushare,
memory=memory)
if new_cfg:
edit_conf(cpath, out_format='commented', lxc_config=new_cfg)
chunks = read_conf(cpath, out_format='commented')
if old_chunks != chunks:
to_reboot = True
# last time to be sure any of our property is correctly applied
cfg = _LXCConfig(name=name, network_profile=network_profile,
nic_opts=nic_opts, bridge=bridge, path=path,
gateway=gateway, autostart=autostart,
cpuset=cpuset, cpushare=cpushare, memory=memory)
old_chunks = []
if os.path.exists(cfg.path):
old_chunks = read_conf(cfg.path, out_format='commented')
cfg.write()
chunks = read_conf(cfg.path, out_format='commented')
if old_chunks != chunks:
changes.append({'config': 'Container configuration updated'})
to_reboot = True
if to_reboot:
try:
stop(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
if changes:
ret['changes'] = changes_dict
return ret
if not does_exist or (does_exist and state(name, path=path) != 'running'):
try:
start(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
if changes:
ret['changes'] = changes_dict
return ret
if remove_seed_marker:
run(name,
'rm -f \'{0}\''.format(SEED_MARKER),
path=path,
chroot_fallback=False,
python_shell=False)
# set the default user/password, only the first time
if ret.get('result', True) and password:
gid = '/.lxc.initial_pass'
gids = [gid,
'/lxc.initial_pass',
'/.lxc.{0}.initial_pass'.format(name)]
if not any(retcode(name,
'test -e "{0}"'.format(x),
chroot_fallback=True,
path=path,
ignore_retcode=True) == 0
for x in gids):
# think to touch the default user generated by default templates
# which has a really unsecure passwords...
# root is defined as a member earlier in the code
for default_user in ['ubuntu']:
if (
default_user not in users and
retcode(name,
'id {0}'.format(default_user),
python_shell=False,
path=path,
chroot_fallback=True,
ignore_retcode=True) == 0
):
users.append(default_user)
for user in users:
try:
cret = set_password(name,
users=[user],
path=path,
password=password,
encrypted=password_encrypted)
except (SaltInvocationError, CommandExecutionError) as exc:
msg = '{0}: Failed to set password'.format(
user) + exc.strerror
# only hardfail in unrecoverable situation:
# root cannot be setted up
if user == 'root':
ret['comment'] = msg
ret['result'] = False
else:
log.debug(msg)
if ret.get('result', True):
changes.append({'password': 'Password(s) updated'})
if retcode(name,
('sh -c \'touch "{0}"; test -e "{0}"\''
.format(gid)),
path=path,
chroot_fallback=True,
ignore_retcode=True) != 0:
ret['comment'] = 'Failed to set password marker'
changes[-1]['password'] += '. ' + ret['comment'] + '.'
ret['result'] = False
# set dns servers if any, only the first time
if ret.get('result', True) and dnsservers:
# retro compatibility, test also old markers
gid = '/.lxc.initial_dns'
gids = [gid,
'/lxc.initial_dns',
'/lxc.{0}.initial_dns'.format(name)]
if not any(retcode(name,
'test -e "{0}"'.format(x),
chroot_fallback=True,
path=path,
ignore_retcode=True) == 0
for x in gids):
try:
set_dns(name,
path=path,
dnsservers=dnsservers,
searchdomains=searchdomains)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Failed to set DNS: ' + exc.strerror
ret['result'] = False
else:
changes.append({'dns': 'DNS updated'})
if retcode(name,
('sh -c \'touch "{0}"; test -e "{0}"\''
.format(gid)),
chroot_fallback=True,
path=path,
ignore_retcode=True) != 0:
ret['comment'] = 'Failed to set DNS marker'
changes[-1]['dns'] += '. ' + ret['comment'] + '.'
ret['result'] = False
# retro compatibility, test also old markers
if remove_seed_marker:
run(name,
'rm -f \'{0}\''.format(SEED_MARKER),
path=path,
python_shell=False)
gid = '/.lxc.initial_seed'
gids = [gid, '/lxc.initial_seed']
if (
any(retcode(name,
'test -e {0}'.format(x),
path=path,
chroot_fallback=True,
ignore_retcode=True) == 0
for x in gids) or not ret.get('result', True)
):
pass
elif seed or seed_cmd:
if seed:
try:
result = bootstrap(
name, config=salt_config, path=path,
approve_key=approve_key,
pub_key=pub_key, priv_key=priv_key,
install=install,
force_install=force_install,
unconditional_install=unconditional_install,
bootstrap_delay=bootstrap_delay,
bootstrap_url=bootstrap_url,
bootstrap_shell=bootstrap_shell,
bootstrap_args=bootstrap_args)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Bootstrap failed: ' + exc.strerror
ret['result'] = False
else:
if not result:
ret['comment'] = ('Bootstrap failed, see minion log for '
'more information')
ret['result'] = False
else:
changes.append(
{'bootstrap': 'Container successfully bootstrapped'}
)
elif seed_cmd:
try:
result = __salt__[seed_cmd](info(name, path=path)['rootfs'],
name,
salt_config)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = ('Bootstrap via seed_cmd \'{0}\' failed: {1}'
.format(seed_cmd, exc.strerror))
ret['result'] = False
else:
if not result:
ret['comment'] = ('Bootstrap via seed_cmd \'{0}\' failed, '
'see minion log for more information '
.format(seed_cmd))
ret['result'] = False
else:
changes.append(
{'bootstrap': 'Container successfully bootstrapped '
'using seed_cmd \'{0}\''
.format(seed_cmd)}
)
if ret.get('result', True) and not start_:
try:
stop(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
ret['result'] = False
state_post = state(name, path=path)
if state_pre != state_post:
changes.append({'state': {'old': state_pre, 'new': state_post}})
if ret.get('result', True):
ret['comment'] = ('Container \'{0}\' successfully initialized'
.format(name))
ret['result'] = True
if changes:
ret['changes'] = changes_dict
return ret
def cloud_init(name, vm_=None, **kwargs):
'''
Thin wrapper to lxc.init to be used from the saltcloud lxc driver
name
Name of the container
may be None and then guessed from saltcloud mapping
`vm_`
saltcloud mapping defaults for the vm
CLI Example:
.. code-block:: bash
salt '*' lxc.cloud_init foo
'''
init_interface = cloud_init_interface(name, vm_, **kwargs)
name = init_interface.pop('name', name)
return init(name, **init_interface)
def images(dist=None):
'''
.. versionadded:: 2015.5.0
List the available images for LXC's ``download`` template.
dist : None
Filter results to a single Linux distribution
CLI Examples:
.. code-block:: bash
salt myminion lxc.images
salt myminion lxc.images dist=centos
'''
out = __salt__['cmd.run_stdout'](
'lxc-create -n __imgcheck -t download -- --list',
ignore_retcode=True
)
if 'DIST' not in out:
raise CommandExecutionError(
'Unable to run the \'download\' template script. Is it installed?'
)
ret = {}
passed_header = False
for line in out.splitlines():
try:
distro, release, arch, variant, build_time = line.split()
except ValueError:
continue
if not passed_header:
if distro == 'DIST':
passed_header = True
continue
dist_list = ret.setdefault(distro, [])
dist_list.append({
'release': release,
'arch': arch,
'variant': variant,
'build_time': build_time,
})
if dist is not None:
return dict([(dist, ret.get(dist, []))])
return ret
def templates():
'''
.. versionadded:: 2015.5.0
List the available LXC template scripts installed on the minion
CLI Examples:
.. code-block:: bash
salt myminion lxc.templates
'''
try:
template_scripts = os.listdir('/usr/share/lxc/templates')
except OSError:
return []
else:
return [x[4:] for x in template_scripts if x.startswith('lxc-')]
def _after_ignition_network_profile(cmd,
ret,
name,
network_profile,
path,
nic_opts):
_clear_context()
if ret['retcode'] == 0 and exists(name, path=path):
if network_profile:
network_changes = apply_network_profile(name,
network_profile,
path=path,
nic_opts=nic_opts)
if network_changes:
log.info(
'Network changes from applying network profile \'%s\' '
'to newly-created container \'%s\':\n%s',
network_profile, name, network_changes
)
c_state = state(name, path=path)
return {'result': True,
'state': {'old': None, 'new': c_state}}
else:
if exists(name, path=path):
# destroy the container if it was partially created
cmd = 'lxc-destroy'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0}'.format(name)
__salt__['cmd.retcode'](cmd, python_shell=False)
raise CommandExecutionError(
'Container could not be created with cmd \'{0}\': {1}'
.format(cmd, ret['stderr'])
)
def create(name,
config=None,
profile=None,
network_profile=None,
nic_opts=None,
**kwargs):
'''
Create a new container.
name
Name of the container
config
The config file to use for the container. Defaults to system-wide
config (usually in /etc/lxc/lxc.conf).
profile
Profile to use in container creation (see
:mod:`lxc.get_container_profile
<salt.modules.lxc.get_container_profile>`). Values in a profile will be
overridden by the **Container Creation Arguments** listed below.
network_profile
Network profile to use for container
.. versionadded:: 2015.5.0
**Container Creation Arguments**
template
The template to use. For example, ``ubuntu`` or ``fedora``.
For a full list of available templates, check out
the :mod:`lxc.templates <salt.modules.lxc.templates>` function.
Conflicts with the ``image`` argument.
.. note::
The ``download`` template requires the following three parameters
to be defined in ``options``:
* **dist** - The name of the distribution
* **release** - Release name/version
* **arch** - Architecture of the container
The available images can be listed using the :mod:`lxc.images
<salt.modules.lxc.images>` function.
options
Template-specific options to pass to the lxc-create command. These
correspond to the long options (ones beginning with two dashes) that
the template script accepts. For example:
.. code-block:: bash
options='{"dist": "centos", "release": "6", "arch": "amd64"}'
For available template options, refer to the lxc template scripts
which are ususally located under ``/usr/share/lxc/templates``,
or run ``lxc-create -t <template> -h``.
image
A tar archive to use as the rootfs for the container. Conflicts with
the ``template`` argument.
backing
The type of storage to use. Set to ``lvm`` to use an LVM group.
Defaults to filesystem within /var/lib/lxc.
fstype
Filesystem type to use on LVM logical volume
size : 1G
Size of the volume to create. Only applicable if ``backing=lvm``.
vgname : lxc
Name of the LVM volume group in which to create the volume for this
container. Only applicable if ``backing=lvm``.
lvname
Name of the LVM logical volume in which to create the volume for this
container. Only applicable if ``backing=lvm``.
thinpool
Name of a pool volume that will be used for thin-provisioning this
container. Only applicable if ``backing=lvm``.
nic_opts
give extra opts overriding network profile values
path
parent path for the container creation (default: /var/lib/lxc)
zfsroot
Name of the ZFS root in which to create the volume for this container.
Only applicable if ``backing=zfs``. (default: tank/lxc)
.. versionadded:: 2015.8.0
'''
# Required params for 'download' template
download_template_deps = ('dist', 'release', 'arch')
cmd = 'lxc-create -n {0}'.format(name)
profile = get_container_profile(copy.deepcopy(profile))
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, None)
profile_match = profile.pop(key, default)
# Return the profile match if the the kwarg match was None, as the
# lxc.present state will pass these kwargs set to None by default.
if kw_overrides_match is None:
return profile_match
return kw_overrides_match
path = select('path')
if exists(name, path=path):
raise CommandExecutionError(
'Container \'{0}\' already exists'.format(name)
)
tvg = select('vgname')
vgname = tvg if tvg else __salt__['config.get']('lxc.vgname')
# The 'template' and 'image' params conflict
template = select('template')
image = select('image')
if template and image:
raise SaltInvocationError(
'Only one of \'template\' and \'image\' is permitted'
)
elif not any((template, image, profile)):
raise SaltInvocationError(
'At least one of \'template\', \'image\', and \'profile\' is '
'required'
)
options = select('options') or {}
backing = select('backing')
if vgname and not backing:
backing = 'lvm'
lvname = select('lvname')
thinpool = select('thinpool')
fstype = select('fstype')
size = select('size', '1G')
zfsroot = select('zfsroot')
if backing in ('dir', 'overlayfs', 'btrfs', 'zfs'):
fstype = None
size = None
# some backends won't support some parameters
if backing in ('aufs', 'dir', 'overlayfs', 'btrfs'):
lvname = vgname = thinpool = None
if image:
img_tar = __salt__['cp.cache_file'](image)
template = os.path.join(
os.path.dirname(salt.__file__),
'templates',
'lxc',
'salt_tarball')
options['imgtar'] = img_tar
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
if not os.path.exists(path):
os.makedirs(path)
if config:
cmd += ' -f {0}'.format(config)
if template:
cmd += ' -t {0}'.format(template)
if backing:
backing = backing.lower()
cmd += ' -B {0}'.format(backing)
if backing in ('zfs',):
if zfsroot:
cmd += ' --zfsroot {0}'.format(zfsroot)
if backing in ('lvm',):
if lvname:
cmd += ' --lvname {0}'.format(lvname)
if vgname:
cmd += ' --vgname {0}'.format(vgname)
if thinpool:
cmd += ' --thinpool {0}'.format(thinpool)
if backing not in ('dir', 'overlayfs'):
if fstype:
cmd += ' --fstype {0}'.format(fstype)
if size:
cmd += ' --fssize {0}'.format(size)
if options:
if template == 'download':
missing_deps = [x for x in download_template_deps
if x not in options]
if missing_deps:
raise SaltInvocationError(
'Missing params in \'options\' dict: {0}'
.format(', '.join(missing_deps))
)
cmd += ' --'
for key, val in six.iteritems(options):
cmd += ' --{0} {1}'.format(key, val)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
# please do not merge extra conflicting stuff
# inside those two line (ret =, return)
return _after_ignition_network_profile(cmd,
ret,
name,
network_profile,
path,
nic_opts)
def clone(name,
orig,
profile=None,
network_profile=None,
nic_opts=None,
**kwargs):
'''
Create a new container as a clone of another container
name
Name of the container
orig
Name of the original container to be cloned
profile
Profile to use in container cloning (see
:mod:`lxc.get_container_profile
<salt.modules.lxc.get_container_profile>`). Values in a profile will be
overridden by the **Container Cloning Arguments** listed below.
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
**Container Cloning Arguments**
snapshot
Use Copy On Write snapshots (LVM)
size : 1G
Size of the volume to create. Only applicable if ``backing=lvm``.
backing
The type of storage to use. Set to ``lvm`` to use an LVM group.
Defaults to filesystem within /var/lib/lxc.
network_profile
Network profile to use for container
.. versionadded:: 2015.8.0
nic_opts
give extra opts overriding network profile values
.. versionadded:: 2015.8.0
CLI Examples:
.. code-block:: bash
salt '*' lxc.clone myclone orig=orig_container
salt '*' lxc.clone myclone orig=orig_container snapshot=True
'''
profile = get_container_profile(copy.deepcopy(profile))
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, None)
profile_match = profile.pop(key, default)
# let kwarg overrides be the preferred choice
if kw_overrides_match is None:
return profile_match
return kw_overrides_match
path = select('path')
if exists(name, path=path):
raise CommandExecutionError(
'Container \'{0}\' already exists'.format(name)
)
_ensure_exists(orig, path=path)
if state(orig, path=path) != 'stopped':
raise CommandExecutionError(
'Container \'{0}\' must be stopped to be cloned'.format(orig)
)
backing = select('backing')
snapshot = select('snapshot')
if backing in ('dir',):
snapshot = False
if not snapshot:
snapshot = ''
else:
snapshot = '-s'
size = select('size', '1G')
if backing in ('dir', 'overlayfs', 'btrfs'):
size = None
# LXC commands and options changed in 2.0 - CF issue #34086 for details
if _LooseVersion(version()) >= _LooseVersion('2.0'):
# https://linuxcontainers.org/lxc/manpages//man1/lxc-copy.1.html
cmd = 'lxc-copy'
cmd += ' {0} -n {1} -N {2}'.format(snapshot, orig, name)
else:
# https://linuxcontainers.org/lxc/manpages//man1/lxc-clone.1.html
cmd = 'lxc-clone'
cmd += ' {0} -o {1} -n {2}'.format(snapshot, orig, name)
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
if not os.path.exists(path):
os.makedirs(path)
if backing:
backing = backing.lower()
cmd += ' -B {0}'.format(backing)
if backing not in ('dir', 'overlayfs'):
if size:
cmd += ' -L {0}'.format(size)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
# please do not merge extra conflicting stuff
# inside those two line (ret =, return)
return _after_ignition_network_profile(cmd,
ret,
name,
network_profile,
path,
nic_opts)
def ls_(active=None, cache=True, path=None):
'''
Return a list of the containers available on the minion
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
active
If ``True``, return only active (i.e. running) containers
.. versionadded:: 2015.5.0
CLI Example:
.. code-block:: bash
salt '*' lxc.ls
salt '*' lxc.ls active=True
'''
contextvar = 'lxc.ls{0}'.format(path)
if active:
contextvar += '.active'
if cache and (contextvar in __context__):
return __context__[contextvar]
else:
ret = []
cmd = 'lxc-ls'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
if active:
cmd += ' --active'
output = __salt__['cmd.run_stdout'](cmd, python_shell=False)
for line in output.splitlines():
ret.extend(line.split())
__context__[contextvar] = ret
return ret
def list_(extra=False, limit=None, path=None):
'''
List containers classified by state
extra
Also get per-container specific info. This will change the return data.
Instead of returning a list of containers, a dictionary of containers
and each container's output from :mod:`lxc.info
<salt.modules.lxc.info>`.
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
limit
Return output matching a specific state (**frozen**, **running**, or
**stopped**).
.. versionadded:: 2015.5.0
CLI Examples:
.. code-block:: bash
salt '*' lxc.list
salt '*' lxc.list extra=True
salt '*' lxc.list limit=running
'''
ctnrs = ls_(path=path)
if extra:
stopped = {}
frozen = {}
running = {}
else:
stopped = []
frozen = []
running = []
ret = {'running': running,
'stopped': stopped,
'frozen': frozen}
for container in ctnrs:
cmd = 'lxc-info'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0}'.format(container)
c_info = __salt__['cmd.run'](
cmd,
python_shell=False,
output_loglevel='debug'
)
c_state = None
for line in c_info.splitlines():
stat = line.split(':')
if stat[0] in ('State', 'state'):
c_state = stat[1].strip()
break
if not c_state or (limit is not None and c_state.lower() != limit):
continue
if extra:
infos = info(container, path=path)
method = 'update'
value = {container: infos}
else:
method = 'append'
value = container
if c_state == 'STOPPED':
getattr(stopped, method)(value)
continue
if c_state == 'FROZEN':
getattr(frozen, method)(value)
continue
if c_state == 'RUNNING':
getattr(running, method)(value)
continue
if limit is not None:
return ret.get(limit, {} if extra else [])
return ret
def _change_state(cmd,
name,
expected,
stdin=_marker,
stdout=_marker,
stderr=_marker,
with_communicate=_marker,
use_vt=_marker,
path=None):
pre = state(name, path=path)
if pre == expected:
return {'result': True,
'state': {'old': expected, 'new': expected},
'comment': 'Container \'{0}\' already {1}'
.format(name, expected)}
if cmd == 'lxc-destroy':
# Kill the container first
scmd = 'lxc-stop'
if path:
scmd += ' -P {0}'.format(pipes.quote(path))
scmd += ' -k -n {0}'.format(name)
__salt__['cmd.run'](scmd,
python_shell=False)
if path and ' -P ' not in cmd:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0}'.format(name)
# certain lxc commands need to be taken with care (lxc-start)
# as te command itself mess with double forks; we must not
# communicate with it, but just wait for the exit status
pkwargs = {'python_shell': False,
'redirect_stderr': True,
'with_communicate': with_communicate,
'use_vt': use_vt,
'stdin': stdin,
'stdout': stdout}
for i in [a for a in pkwargs]:
val = pkwargs[i]
if val is _marker:
pkwargs.pop(i, None)
_cmdout = __salt__['cmd.run_all'](cmd, **pkwargs)
if _cmdout['retcode'] != 0:
raise CommandExecutionError(
'Error changing state for container \'{0}\' using command '
'\'{1}\': {2}'.format(name, cmd, _cmdout['stdout'])
)
if expected is not None:
# some commands do not wait, so we will
rcmd = 'lxc-wait'
if path:
rcmd += ' -P {0}'.format(pipes.quote(path))
rcmd += ' -n {0} -s {1}'.format(name, expected.upper())
__salt__['cmd.run'](rcmd, python_shell=False, timeout=30)
_clear_context()
post = state(name, path=path)
ret = {'result': post == expected,
'state': {'old': pre, 'new': post}}
return ret
def _ensure_running(name, no_start=False, path=None):
'''
If the container is not currently running, start it. This function returns
the state that the container was in before changing
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
'''
_ensure_exists(name, path=path)
pre = state(name, path=path)
if pre == 'running':
# This will be a no-op but running the function will give us a pretty
# return dict.
return start(name, path=path)
elif pre == 'stopped':
if no_start:
raise CommandExecutionError(
'Container \'{0}\' is not running'.format(name)
)
return start(name, path=path)
elif pre == 'frozen':
if no_start:
raise CommandExecutionError(
'Container \'{0}\' is not running'.format(name)
)
return unfreeze(name, path=path)
def restart(name, path=None, lxc_config=None, force=False):
'''
.. versionadded:: 2015.5.0
Restart the named container. If the container was not running, the
container will merely be started.
name
The name of the container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
lxc_config
path to a lxc config file
config file will be guessed from container name otherwise
.. versionadded:: 2015.8.0
force : False
If ``True``, the container will be force-stopped instead of gracefully
shut down
CLI Example:
.. code-block:: bash
salt myminion lxc.restart name
'''
_ensure_exists(name, path=path)
orig_state = state(name, path=path)
if orig_state != 'stopped':
stop(name, kill=force, path=path)
ret = start(name, path=path, lxc_config=lxc_config)
ret['state']['old'] = orig_state
if orig_state != 'stopped':
ret['restarted'] = True
return ret
def start(name, **kwargs):
'''
Start the named container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
lxc_config
path to a lxc config file
config file will be guessed from container name otherwise
.. versionadded:: 2015.8.0
use_vt
run the command through VT
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.start name
'''
path = kwargs.get('path', None)
cpath = get_root_path(path)
lxc_config = kwargs.get('lxc_config', None)
cmd = 'lxc-start'
if not lxc_config:
lxc_config = os.path.join(cpath, name, 'config')
# we try to start, even without config, if global opts are there
if os.path.exists(lxc_config):
cmd += ' -f {0}'.format(pipes.quote(lxc_config))
cmd += ' -d'
_ensure_exists(name, path=path)
if state(name, path=path) == 'frozen':
raise CommandExecutionError(
'Container \'{0}\' is frozen, use lxc.unfreeze'.format(name)
)
# lxc-start daemonize itself violently, we must not communicate with it
use_vt = kwargs.get('use_vt', None)
with_communicate = kwargs.get('with_communicate', False)
return _change_state(cmd, name, 'running',
stdout=None,
stderr=None,
stdin=None,
with_communicate=with_communicate,
path=path,
use_vt=use_vt)
def stop(name, kill=False, path=None, use_vt=None):
'''
Stop the named container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
kill: False
Do not wait for the container to stop, kill all tasks in the container.
Older LXC versions will stop containers like this irrespective of this
argument.
.. versionchanged:: 2015.5.0
Default value changed to ``False``
use_vt
run the command through VT
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.stop name
'''
_ensure_exists(name, path=path)
orig_state = state(name, path=path)
if orig_state == 'frozen' and not kill:
# Gracefully stopping a frozen container is slower than unfreezing and
# then stopping it (at least in my testing), so if we're not
# force-stopping the container, unfreeze it first.
unfreeze(name, path=path)
cmd = 'lxc-stop'
if kill:
cmd += ' -k'
ret = _change_state(cmd, name, 'stopped', use_vt=use_vt, path=path)
ret['state']['old'] = orig_state
return ret
def freeze(name, **kwargs):
'''
Freeze the named container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
start : False
If ``True`` and the container is stopped, the container will be started
before attempting to freeze.
.. versionadded:: 2015.5.0
use_vt
run the command through VT
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.freeze name
'''
use_vt = kwargs.get('use_vt', None)
path = kwargs.get('path', None)
_ensure_exists(name, path=path)
orig_state = state(name, path=path)
start_ = kwargs.get('start', False)
if orig_state == 'stopped':
if not start_:
raise CommandExecutionError(
'Container \'{0}\' is stopped'.format(name)
)
start(name, path=path)
cmd = 'lxc-freeze'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
ret = _change_state(cmd, name, 'frozen', use_vt=use_vt, path=path)
if orig_state == 'stopped' and start_:
ret['state']['old'] = orig_state
ret['started'] = True
ret['state']['new'] = state(name, path=path)
return ret
def unfreeze(name, path=None, use_vt=None):
'''
Unfreeze the named container.
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
use_vt
run the command through VT
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.unfreeze name
'''
_ensure_exists(name, path=path)
if state(name, path=path) == 'stopped':
raise CommandExecutionError(
'Container \'{0}\' is stopped'.format(name)
)
cmd = 'lxc-unfreeze'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
return _change_state(cmd, name, 'running', path=path, use_vt=use_vt)
def destroy(name, stop=False, path=None):
'''
Destroy the named container.
.. warning::
Destroys all data associated with the container.
path
path to the container parent directory (default: /var/lib/lxc)
.. versionadded:: 2015.8.0
stop : False
If ``True``, the container will be destroyed even if it is
running/frozen.
.. versionchanged:: 2015.5.0
Default value changed to ``False``. This more closely matches the
behavior of ``lxc-destroy(1)``, and also makes it less likely that
an accidental command will destroy a running container that was
being used for important things.
CLI Examples:
.. code-block:: bash
salt '*' lxc.destroy foo
salt '*' lxc.destroy foo stop=True
'''
_ensure_exists(name, path=path)
if not stop and state(name, path=path) != 'stopped':
raise CommandExecutionError(
'Container \'{0}\' is not stopped'.format(name)
)
return _change_state('lxc-destroy', name, None, path=path)
# Compatibility between LXC and nspawn
remove = salt.utils.functools.alias_function(destroy, 'remove')
def exists(name, path=None):
'''
Returns whether the named container exists.
path
path to the container parent directory (default: /var/lib/lxc)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.exists name
'''
_exists = name in ls_(path=path)
# container may be just created but we did cached earlier the
# lxc-ls results
if not _exists:
_exists = name in ls_(cache=False, path=path)
return _exists
def state(name, path=None):
'''
Returns the state of a container.
path
path to the container parent directory (default: /var/lib/lxc)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.state name
'''
# Don't use _ensure_exists() here, it will mess with _change_state()
cachekey = 'lxc.state.{0}{1}'.format(name, path)
try:
return __context__[cachekey]
except KeyError:
if not exists(name, path=path):
__context__[cachekey] = None
else:
cmd = 'lxc-info'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0}'.format(name)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
if ret['retcode'] != 0:
_clear_context()
raise CommandExecutionError(
'Unable to get state of container \'{0}\''.format(name)
)
c_infos = ret['stdout'].splitlines()
c_state = None
for c_info in c_infos:
stat = c_info.split(':')
if stat[0].lower() == 'state':
c_state = stat[1].strip().lower()
break
__context__[cachekey] = c_state
return __context__[cachekey]
def get_parameter(name, parameter, path=None):
'''
Returns the value of a cgroup parameter for a container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.get_parameter container_name memory.limit_in_bytes
'''
_ensure_exists(name, path=path)
cmd = 'lxc-cgroup'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0} {1}'.format(name, parameter)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
if ret['retcode'] != 0:
raise CommandExecutionError(
'Unable to retrieve value for \'{0}\''.format(parameter)
)
return ret['stdout'].strip()
def set_parameter(name, parameter, value, path=None):
'''
Set the value of a cgroup parameter for a container.
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.set_parameter name parameter value
'''
if not exists(name, path=path):
return None
cmd = 'lxc-cgroup'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0} {1} {2}'.format(name, parameter, value)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
if ret['retcode'] != 0:
return False
else:
return True
def info(name, path=None):
'''
Returns information about a container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.info name
'''
cachekey = 'lxc.info.{0}{1}'.format(name, path)
try:
return __context__[cachekey]
except KeyError:
_ensure_exists(name, path=path)
cpath = get_root_path(path)
try:
conf_file = os.path.join(cpath, name, 'config')
except AttributeError:
conf_file = os.path.join(cpath, six.text_type(name), 'config')
if not os.path.isfile(conf_file):
raise CommandExecutionError(
'LXC config file {0} does not exist'.format(conf_file)
)
ret = {}
config = []
with salt.utils.files.fopen(conf_file) as fp_:
for line in fp_:
line = salt.utils.stringutils.to_unicode(line)
comps = [x.strip() for x in
line.split('#', 1)[0].strip().split('=', 1)]
if len(comps) == 2:
config.append(tuple(comps))
ifaces = []
current = None
for key, val in config:
if key == 'lxc.network.type':
current = {'type': val}
ifaces.append(current)
elif not current:
continue
elif key.startswith('lxc.network.'):
current[key.replace('lxc.network.', '', 1)] = val
if ifaces:
ret['nics'] = ifaces
ret['rootfs'] = next(
(x[1] for x in config if x[0] == 'lxc.rootfs'),
None
)
ret['state'] = state(name, path=path)
ret['ips'] = []
ret['public_ips'] = []
ret['private_ips'] = []
ret['public_ipv4_ips'] = []
ret['public_ipv6_ips'] = []
ret['private_ipv4_ips'] = []
ret['private_ipv6_ips'] = []
ret['ipv4_ips'] = []
ret['ipv6_ips'] = []
ret['size'] = None
ret['config'] = conf_file
if ret['state'] == 'running':
try:
limit = int(get_parameter(name, 'memory.limit_in_bytes'))
except (CommandExecutionError, TypeError, ValueError):
limit = 0
try:
usage = int(get_parameter(name, 'memory.usage_in_bytes'))
except (CommandExecutionError, TypeError, ValueError):
usage = 0
free = limit - usage
ret['memory_limit'] = limit
ret['memory_free'] = free
size = run_stdout(name, 'df /', path=path, python_shell=False)
# The size is the 2nd column of the last line
ret['size'] = size.splitlines()[-1].split()[1]
# First try iproute2
ip_cmd = run_all(
name, 'ip link show', path=path, python_shell=False)
if ip_cmd['retcode'] == 0:
ip_data = ip_cmd['stdout']
ip_cmd = run_all(
name, 'ip addr show', path=path, python_shell=False)
ip_data += '\n' + ip_cmd['stdout']
ip_data = salt.utils.network._interfaces_ip(ip_data)
else:
# That didn't work, try ifconfig
ip_cmd = run_all(
name, 'ifconfig', path=path, python_shell=False)
if ip_cmd['retcode'] == 0:
ip_data = \
salt.utils.network._interfaces_ifconfig(
ip_cmd['stdout'])
else:
# Neither was successful, give up
log.warning(
'Unable to run ip or ifconfig in container \'%s\'', name
)
ip_data = {}
ret['ipv4_ips'] = salt.utils.network.ip_addrs(
include_loopback=True,
interface_data=ip_data
)
ret['ipv6_ips'] = salt.utils.network.ip_addrs6(
include_loopback=True,
interface_data=ip_data
)
ret['ips'] = ret['ipv4_ips'] + ret['ipv6_ips']
for address in ret['ipv4_ips']:
if address == '127.0.0.1':
ret['private_ips'].append(address)
ret['private_ipv4_ips'].append(address)
elif salt.utils.cloud.is_public_ip(address):
ret['public_ips'].append(address)
ret['public_ipv4_ips'].append(address)
else:
ret['private_ips'].append(address)
ret['private_ipv4_ips'].append(address)
for address in ret['ipv6_ips']:
if address == '::1' or address.startswith('fe80'):
ret['private_ips'].append(address)
ret['private_ipv6_ips'].append(address)
else:
ret['public_ips'].append(address)
ret['public_ipv6_ips'].append(address)
for key in [x for x in ret if x == 'ips' or x.endswith('ips')]:
ret[key].sort(key=_ip_sort)
__context__[cachekey] = ret
return __context__[cachekey]
def set_password(name, users, password, encrypted=True, path=None):
'''
.. versionchanged:: 2015.5.0
Function renamed from ``set_pass`` to ``set_password``. Additionally,
this function now supports (and defaults to using) a password hash
instead of a plaintext password.
Set the password of one or more system users inside containers
users
Comma-separated list (or python list) of users to change password
password
Password to set for the specified user(s)
encrypted : True
If true, ``password`` must be a password hash. Set to ``False`` to set
a plaintext password (not recommended).
.. versionadded:: 2015.5.0
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.set_pass container-name root '$6$uJ2uAyLU$KoI67t8As/0fXtJOPcHKGXmUpcoYUcVR2K6x93walnShTCQvjRwq25yIkiCBOqgbfdKQSFnAo28/ek6716vEV1'
salt '*' lxc.set_pass container-name root foo encrypted=False
'''
def _bad_user_input():
raise SaltInvocationError('Invalid input for \'users\' parameter')
if not isinstance(users, list):
try:
users = users.split(',')
except AttributeError:
_bad_user_input()
if not users:
_bad_user_input()
failed_users = []
for user in users:
result = retcode(name,
'chpasswd{0}'.format(' -e' if encrypted else ''),
stdin=':'.join((user, password)),
python_shell=False,
path=path,
chroot_fallback=True,
output_loglevel='quiet')
if result != 0:
failed_users.append(user)
if failed_users:
raise CommandExecutionError(
'Password change failed for the following user(s): {0}'
.format(', '.join(failed_users))
)
return True
set_pass = salt.utils.functools.alias_function(set_password, 'set_pass')
def update_lxc_conf(name, lxc_conf, lxc_conf_unset, path=None):
'''
Edit LXC configuration options
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.update_lxc_conf ubuntu \\
lxc_conf="[{'network.ipv4.ip':'10.0.3.5'}]" \\
lxc_conf_unset="['lxc.utsname']"
'''
_ensure_exists(name, path=path)
cpath = get_root_path(path)
lxc_conf_p = os.path.join(cpath, name, 'config')
if not os.path.exists(lxc_conf_p):
raise SaltInvocationError(
'Configuration file {0} does not exist'.format(lxc_conf_p)
)
changes = {'edited': [], 'added': [], 'removed': []}
ret = {'changes': changes, 'result': True, 'comment': ''}
# do not use salt.utils.files.fopen !
with salt.utils.files.fopen(lxc_conf_p, 'r') as fic:
filtered_lxc_conf = []
for row in lxc_conf:
if not row:
continue
for conf in row:
filtered_lxc_conf.append((conf.strip(),
row[conf].strip()))
ret['comment'] = 'lxc.conf is up to date'
lines = []
orig_config = salt.utils.stringutils.to_unicode(fic.read())
for line in orig_config.splitlines():
if line.startswith('#') or not line.strip():
lines.append([line, ''])
else:
line = line.split('=')
index = line.pop(0)
val = (index.strip(), '='.join(line).strip())
if val not in lines:
lines.append(val)
for key, item in filtered_lxc_conf:
matched = False
for idx, line in enumerate(lines[:]):
if line[0] == key:
matched = True
lines[idx] = (key, item)
if '='.join(line[1:]).strip() != item.strip():
changes['edited'].append(
({line[0]: line[1:]}, {key: item}))
break
if not matched:
if (key, item) not in lines:
lines.append((key, item))
changes['added'].append({key: item})
dest_lxc_conf = []
# filter unset
if lxc_conf_unset:
for line in lines:
for opt in lxc_conf_unset:
if (
not line[0].startswith(opt) and
line not in dest_lxc_conf
):
dest_lxc_conf.append(line)
else:
changes['removed'].append(opt)
else:
dest_lxc_conf = lines
conf = ''
for key, val in dest_lxc_conf:
if not val:
conf += '{0}\n'.format(key)
else:
conf += '{0} = {1}\n'.format(key.strip(), val.strip())
conf_changed = conf != orig_config
chrono = datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S')
if conf_changed:
# DO NOT USE salt.utils.files.fopen here, i got (kiorky)
# problems with lxc configs which were wiped !
with salt.utils.files.fopen('{0}.{1}'.format(lxc_conf_p, chrono), 'w') as wfic:
wfic.write(salt.utils.stringutils.to_str(conf))
with salt.utils.files.fopen(lxc_conf_p, 'w') as wfic:
wfic.write(salt.utils.stringutils.to_str(conf))
ret['comment'] = 'Updated'
ret['result'] = True
if not any(changes[x] for x in changes):
# Ensure an empty changes dict if nothing was modified
ret['changes'] = {}
return ret
def set_dns(name, dnsservers=None, searchdomains=None, path=None):
'''
.. versionchanged:: 2015.5.0
The ``dnsservers`` and ``searchdomains`` parameters can now be passed
as a comma-separated list.
Update /etc/resolv.confo
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.set_dns ubuntu "['8.8.8.8', '4.4.4.4']"
'''
if dnsservers is None:
dnsservers = ['8.8.8.8', '4.4.4.4']
elif not isinstance(dnsservers, list):
try:
dnsservers = dnsservers.split(',')
except AttributeError:
raise SaltInvocationError(
'Invalid input for \'dnsservers\' parameter'
)
if searchdomains is None:
searchdomains = []
elif not isinstance(searchdomains, list):
try:
searchdomains = searchdomains.split(',')
except AttributeError:
raise SaltInvocationError(
'Invalid input for \'searchdomains\' parameter'
)
dns = ['nameserver {0}'.format(x) for x in dnsservers]
dns.extend(['search {0}'.format(x) for x in searchdomains])
dns = '\n'.join(dns) + '\n'
# we may be using resolvconf in the container
# We need to handle that case with care:
# - we create the resolv.conf runtime directory (the
# linked directory) as anyway it will be shadowed when the real
# runned tmpfs mountpoint will be mounted.
# ( /etc/resolv.conf -> ../run/resolvconf/resolv.conf)
# Indeed, it can save us in any other case (running, eg, in a
# bare chroot when repairing or preparing the container for
# operation.
# - We also teach resolvconf to use the aforementioned dns.
# - We finally also set /etc/resolv.conf in all cases
rstr = __salt__['test.random_hash']()
# no tmp here, apparmor won't let us execute !
script = '/sbin/{0}_dns.sh'.format(rstr)
DNS_SCRIPT = "\n".join([
# 'set -x',
'#!/usr/bin/env bash',
'if [ -h /etc/resolv.conf ];then',
' if [ "x$(readlink /etc/resolv.conf)"'
' = "x../run/resolvconf/resolv.conf" ];then',
' if [ ! -d /run/resolvconf/ ];then',
' mkdir -p /run/resolvconf',
' fi',
' cat > /etc/resolvconf/resolv.conf.d/head <<EOF',
dns,
'EOF',
'',
' fi',
'fi',
'cat > /etc/resolv.conf <<EOF',
dns,
'EOF',
''])
result = run_all(
name, 'tee {0}'.format(script), path=path,
stdin=DNS_SCRIPT, python_shell=True)
if result['retcode'] == 0:
result = run_all(
name, 'sh -c "chmod +x {0};{0}"'.format(script),
path=path, python_shell=True)
# blindly delete the setter file
run_all(name,
'sh -c \'if [ -f "{0}" ];then rm -f "{0}";fi\''.format(script),
path=path, python_shell=True)
if result['retcode'] != 0:
error = ('Unable to write to /etc/resolv.conf in container \'{0}\''
.format(name))
if result['stderr']:
error += ': {0}'.format(result['stderr'])
raise CommandExecutionError(error)
return True
def running_systemd(name, cache=True, path=None):
'''
Determine if systemD is running
path
path to the container parent
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.running_systemd ubuntu
'''
k = 'lxc.systemd.test.{0}{1}'.format(name, path)
ret = __context__.get(k, None)
if ret is None or not cache:
rstr = __salt__['test.random_hash']()
# no tmp here, apparmor won't let us execute !
script = '/sbin/{0}_testsystemd.sh'.format(rstr)
# ubuntu already had since trusty some bits of systemd but was
# still using upstart ...
# we need to be a bit more careful that just testing that systemd
# is present
_script = textwrap.dedent(
'''\
#!/usr/bin/env bash
set -x
if ! command -v systemctl 1>/dev/null 2>/dev/null;then exit 2;fi
for i in \\
/run/systemd/journal/dev-log\\
/run/systemd/journal/flushed\\
/run/systemd/journal/kernel-seqnum\\
/run/systemd/journal/socket\\
/run/systemd/journal/stdout\\
/var/run/systemd/journal/dev-log\\
/var/run/systemd/journal/flushed\\
/var/run/systemd/journal/kernel-seqnum\\
/var/run/systemd/journal/socket\\
/var/run/systemd/journal/stdout\\
;do\\
if test -e ${i};then exit 0;fi
done
if test -d /var/systemd/system;then exit 0;fi
exit 2
''')
result = run_all(
name, 'tee {0}'.format(script), path=path,
stdin=_script, python_shell=True)
if result['retcode'] == 0:
result = run_all(name,
'sh -c "chmod +x {0};{0}"'''.format(script),
path=path,
python_shell=True)
else:
raise CommandExecutionError(
'lxc {0} failed to copy initd tester'.format(name))
run_all(name,
'sh -c \'if [ -f "{0}" ];then rm -f "{0}";fi\''
''.format(script),
path=path,
ignore_retcode=True,
python_shell=True)
if result['retcode'] != 0:
error = ('Unable to determine if the container \'{0}\''
' was running systemd, assmuming it is not.'
''.format(name))
if result['stderr']:
error += ': {0}'.format(result['stderr'])
# only cache result if we got a known exit code
if result['retcode'] in (0, 2):
__context__[k] = ret = not result['retcode']
return ret
def systemd_running_state(name, path=None):
'''
Get the operational state of a systemd based container
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.systemd_running_state ubuntu
'''
try:
ret = run_all(name,
'systemctl is-system-running',
path=path,
ignore_retcode=True)['stdout']
except CommandExecutionError:
ret = ''
return ret
def test_sd_started_state(name, path=None):
'''
Test if a systemd container is fully started
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.test_sd_started_state ubuntu
'''
qstate = systemd_running_state(name, path=path)
if qstate in ('initializing', 'starting'):
return False
elif qstate == '':
return None
else:
return True
def test_bare_started_state(name, path=None):
'''
Test if a non systemd container is fully started
For now, it consists only to test if the container is attachable
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.test_bare_started_state ubuntu
'''
try:
ret = run_all(
name, 'ls', path=path, ignore_retcode=True
)['retcode'] == 0
except (CommandExecutionError,):
ret = None
return ret
def wait_started(name, path=None, timeout=300):
'''
Check that the system has fully inited
This is actually very important for systemD based containers
see https://github.com/saltstack/salt/issues/23847
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.wait_started ubuntu
'''
if not exists(name, path=path):
raise CommandExecutionError(
'Container {0} does does exists'.format(name))
if not state(name, path=path) == 'running':
raise CommandExecutionError(
'Container {0} is not running'.format(name))
ret = False
if running_systemd(name, path=path):
test_started = test_sd_started_state
logger = log.error
else:
test_started = test_bare_started_state
logger = log.debug
now = time.time()
expire = now + timeout
now = time.time()
started = test_started(name, path=path)
while time.time() < expire and not started:
time.sleep(0.3)
started = test_started(name, path=path)
if started is None:
logger(
'Assuming %s is started, although we failed to detect that'
' is fully started correctly', name)
ret = True
else:
ret = started
return ret
def _needs_install(name, path=None):
ret = 0
has_minion = retcode(name,
'which salt-minion',
path=path,
ignore_retcode=True)
# we assume that installing is when no minion is running
# but testing the executable presence is not enougth for custom
# installs where the bootstrap can do much more than installing
# the bare salt binaries.
if has_minion:
processes = run_stdout(name, "ps aux", path=path)
if 'salt-minion' not in processes:
ret = 1
else:
retcode(name, 'salt-call --local service.stop salt-minion')
else:
ret = 1
return ret
def bootstrap(name,
config=None,
approve_key=True,
install=True,
pub_key=None,
priv_key=None,
bootstrap_url=None,
force_install=False,
unconditional_install=False,
path=None,
bootstrap_delay=None,
bootstrap_args=None,
bootstrap_shell=None):
'''
Install and configure salt in a container.
config
Minion configuration options. By default, the ``master`` option is set
to the target host's master.
approve_key
Request a pre-approval of the generated minion key. Requires
that the salt-master be configured to either auto-accept all keys or
expect a signing request from the target host. Default: ``True``
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
pub_key
Explicit public key to pressed the minion with (optional).
This can be either a filepath or a string representing the key
priv_key
Explicit private key to pressed the minion with (optional).
This can be either a filepath or a string representing the key
bootstrap_delay
Delay in seconds between end of container creation and bootstrapping.
Useful when waiting for container to obtain a DHCP lease.
.. versionadded:: 2015.5.0
bootstrap_url
url, content or filepath to the salt bootstrap script
bootstrap_args
salt bootstrap script arguments
bootstrap_shell
shell to execute the script into
install
Whether to attempt a full installation of salt-minion if needed.
force_install
Force installation even if salt-minion is detected,
this is the way to run vendor bootstrap scripts even
if a salt minion is already present in the container
unconditional_install
Run the script even if the container seems seeded
CLI Examples:
.. code-block:: bash
salt 'minion' lxc.bootstrap container_name [config=config_data] \\
[approve_key=(True|False)] [install=(True|False)]
'''
wait_started(name, path=path)
if bootstrap_delay is not None:
try:
log.info('LXC %s: bootstrap_delay: %s', name, bootstrap_delay)
time.sleep(bootstrap_delay)
except TypeError:
# Bad input, but assume since a value was passed that
# a delay was desired, and sleep for 5 seconds
time.sleep(5)
c_info = info(name, path=path)
if not c_info:
return None
# default set here as we cannot set them
# in def as it can come from a chain of procedures.
if bootstrap_args:
# custom bootstrap args can be totally customized, and user could
# have inserted the placeholder for the config directory.
# For example, some salt bootstrap script do not use at all -c
if '{0}' not in bootstrap_args:
bootstrap_args += ' -c {0}'
else:
bootstrap_args = '-c {0}'
if not bootstrap_shell:
bootstrap_shell = 'sh'
orig_state = _ensure_running(name, path=path)
if not orig_state:
return orig_state
if not force_install:
needs_install = _needs_install(name, path=path)
else:
needs_install = True
seeded = retcode(name,
'test -e \'{0}\''.format(SEED_MARKER),
path=path,
chroot_fallback=True,
ignore_retcode=True) == 0
tmp = tempfile.mkdtemp()
if seeded and not unconditional_install:
ret = True
else:
ret = False
cfg_files = __salt__['seed.mkconfig'](
config, tmp=tmp, id_=name, approve_key=approve_key,
pub_key=pub_key, priv_key=priv_key)
if needs_install or force_install or unconditional_install:
if install:
rstr = __salt__['test.random_hash']()
configdir = '/var/tmp/.c_{0}'.format(rstr)
cmd = 'install -m 0700 -d {0}'.format(configdir)
if run_all(
name, cmd, path=path, python_shell=False
)['retcode'] != 0:
log.error('tmpdir %s creation failed %s', configdir, cmd)
return False
bs_ = __salt__['config.gather_bootstrap_script'](
bootstrap=bootstrap_url)
script = '/sbin/{0}_bootstrap.sh'.format(rstr)
copy_to(name, bs_, script, path=path)
result = run_all(name,
'sh -c "chmod +x {0}"'.format(script),
path=path,
python_shell=True)
copy_to(name, cfg_files['config'],
os.path.join(configdir, 'minion'),
path=path)
copy_to(name, cfg_files['privkey'],
os.path.join(configdir, 'minion.pem'),
path=path)
copy_to(name, cfg_files['pubkey'],
os.path.join(configdir, 'minion.pub'),
path=path)
bootstrap_args = bootstrap_args.format(configdir)
cmd = ('{0} {2} {1}'
.format(bootstrap_shell,
bootstrap_args.replace("'", "''"),
script))
# log ASAP the forged bootstrap command which can be wrapped
# out of the output in case of unexpected problem
log.info('Running %s in LXC container \'%s\'', cmd, name)
ret = retcode(name, cmd, output_loglevel='info',
path=path, use_vt=True) == 0
run_all(name,
'sh -c \'if [ -f "{0}" ];then rm -f "{0}";fi\''
''.format(script),
path=path,
ignore_retcode=True,
python_shell=True)
else:
ret = False
else:
minion_config = salt.config.minion_config(cfg_files['config'])
pki_dir = minion_config['pki_dir']
copy_to(name,
cfg_files['config'],
'/etc/salt/minion',
path=path)
copy_to(name,
cfg_files['privkey'],
os.path.join(pki_dir, 'minion.pem'),
path=path)
copy_to(name,
cfg_files['pubkey'],
os.path.join(pki_dir, 'minion.pub'),
path=path)
run(name,
'salt-call --local service.enable salt-minion',
path=path,
python_shell=False)
ret = True
shutil.rmtree(tmp)
if orig_state == 'stopped':
stop(name, path=path)
elif orig_state == 'frozen':
freeze(name, path=path)
# mark seeded upon successful install
if ret:
run(name,
'touch \'{0}\''.format(SEED_MARKER),
path=path,
python_shell=False)
return ret
def attachable(name, path=None):
'''
Return True if the named container can be attached to via the lxc-attach
command
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt 'minion' lxc.attachable ubuntu
'''
cachekey = 'lxc.attachable{0}{1}'.format(name, path)
try:
return __context__[cachekey]
except KeyError:
_ensure_exists(name, path=path)
# Can't use run() here because it uses attachable() and would
# endlessly recurse, resulting in a traceback
log.debug('Checking if LXC container %s is attachable', name)
cmd = 'lxc-attach'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' --clear-env -n {0} -- /usr/bin/env'.format(name)
result = __salt__['cmd.retcode'](cmd,
python_shell=False,
output_loglevel='quiet',
ignore_retcode=True) == 0
__context__[cachekey] = result
return __context__[cachekey]
def _run(name,
cmd,
output=None,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=None,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
Common logic for lxc.run functions
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
'''
orig_state = state(name, path=path)
try:
if attachable(name, path=path):
ret = __salt__['container_resource.run'](
name,
cmd,
path=path,
container_type=__virtualname__,
exec_driver=EXEC_DRIVER,
output=output,
no_start=no_start,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
ignore_retcode=ignore_retcode,
use_vt=use_vt,
keep_env=keep_env)
else:
if not chroot_fallback:
raise CommandExecutionError(
'{0} is not attachable.'.format(name))
rootfs = info(name, path=path).get('rootfs')
# Set context var to make cmd.run_chroot run cmd.run instead of
# cmd.run_all.
__context__['cmd.run_chroot.func'] = __salt__['cmd.run']
ret = __salt__['cmd.run_chroot'](rootfs,
cmd,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
ignore_retcode=ignore_retcode)
except Exception:
raise
finally:
# Make sure we honor preserve_state, even if there was an exception
new_state = state(name, path=path)
if preserve_state:
if orig_state == 'stopped' and new_state != 'stopped':
stop(name, path=path)
elif orig_state == 'frozen' and new_state != 'frozen':
freeze(name, start=True, path=path)
if output in (None, 'all'):
return ret
else:
return ret[output]
def run(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.8.0
Run :mod:`cmd.run <salt.modules.cmdmod.run>` within a container
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed in stderr if the command being run
does not exist. If no output is returned using this function, try using
:mod:`lxc.run_stderr <salt.modules.lxc.run_stderr>` or
:mod:`lxc.run_all <salt.modules.lxc.run_all>`.
name
Name of the container in which to run the command
cmd
Command to run
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console. Assumes
``output=all``.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
CLI Example:
.. code-block:: bash
salt myminion lxc.run mycontainer 'ifconfig -a'
'''
return _run(name,
cmd,
path=path,
output=None,
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def run_stdout(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.5.0
Run :mod:`cmd.run_stdout <salt.modules.cmdmod.run_stdout>` within a container
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed in stderr if the command being run
does not exist. If no output is returned using this function, try using
:mod:`lxc.run_stderr <salt.modules.lxc.run_stderr>` or
:mod:`lxc.run_all <salt.modules.lxc.run_all>`.
name
Name of the container in which to run the command
cmd
Command to run
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console
``output=all``.
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
CLI Example:
.. code-block:: bash
salt myminion lxc.run_stdout mycontainer 'ifconfig -a'
'''
return _run(name,
cmd,
path=path,
output='stdout',
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def run_stderr(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.5.0
Run :mod:`cmd.run_stderr <salt.modules.cmdmod.run_stderr>` within a container
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed if the command being run does not
exist.
name
Name of the container in which to run the command
cmd
Command to run
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console
``output=all``.
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
CLI Example:
.. code-block:: bash
salt myminion lxc.run_stderr mycontainer 'ip addr show'
'''
return _run(name,
cmd,
path=path,
output='stderr',
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def retcode(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.5.0
Run :mod:`cmd.retcode <salt.modules.cmdmod.retcode>` within a container
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed in stderr if the command being run
does not exist. If the retcode is nonzero and not what was expected,
try using :mod:`lxc.run_stderr <salt.modules.lxc.run_stderr>`
or :mod:`lxc.run_all <salt.modules.lxc.run_all>`.
name
Name of the container in which to run the command
cmd
Command to run
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console
``output=all``.
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
CLI Example:
.. code-block:: bash
salt myminion lxc.retcode mycontainer 'ip addr show'
'''
return _run(name,
cmd,
output='retcode',
path=path,
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def run_all(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.5.0
Run :mod:`cmd.run_all <salt.modules.cmdmod.run_all>` within a container
.. note::
While the command is run within the container, it is initiated from the
host. Therefore, the PID in the return dict is from the host, not from
the container.
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed in stderr if the command being run
does not exist.
name
Name of the container in which to run the command
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
cmd
Command to run
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console
``output=all``.
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
CLI Example:
.. code-block:: bash
salt myminion lxc.run_all mycontainer 'ip addr show'
'''
return _run(name,
cmd,
output='all',
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
path=path,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def _get_md5(name, path):
'''
Get the MD5 checksum of a file from a container
'''
output = run_stdout(name, 'md5sum "{0}"'.format(path),
chroot_fallback=True,
ignore_retcode=True)
try:
return output.split()[0]
except IndexError:
# Destination file does not exist or could not be accessed
return None
def copy_to(name, source, dest, overwrite=False, makedirs=False, path=None):
'''
.. versionchanged:: 2015.8.0
Function renamed from ``lxc.cp`` to ``lxc.copy_to`` for consistency
with other container types. ``lxc.cp`` will continue to work, however.
For versions 2015.2.x and earlier, use ``lxc.cp``.
Copy a file or directory from the host into a container
name
Container name
source
File to be copied to the container
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
dest
Destination on the container. Must be an absolute path.
.. versionchanged:: 2015.5.0
If the destination is a directory, the file will be copied into
that directory.
overwrite : False
Unless this option is set to ``True``, then if a file exists at the
location specified by the ``dest`` argument, an error will be raised.
.. versionadded:: 2015.8.0
makedirs : False
Create the parent directory on the container if it does not already
exist.
.. versionadded:: 2015.5.0
CLI Example:
.. code-block:: bash
salt 'minion' lxc.copy_to /tmp/foo /root/foo
salt 'minion' lxc.cp /tmp/foo /root/foo
'''
_ensure_running(name, no_start=True, path=path)
return __salt__['container_resource.copy_to'](
name,
source,
dest,
container_type=__virtualname__,
path=path,
exec_driver=EXEC_DRIVER,
overwrite=overwrite,
makedirs=makedirs)
cp = salt.utils.functools.alias_function(copy_to, 'cp')
def read_conf(conf_file, out_format='simple'):
'''
Read in an LXC configuration file. By default returns a simple, unsorted
dict, but can also return a more detailed structure including blank lines
and comments.
out_format:
set to 'simple' if you need the old and unsupported behavior.
This won't support the multiple lxc values (eg: multiple network nics)
CLI Examples:
.. code-block:: bash
salt 'minion' lxc.read_conf /etc/lxc/mycontainer.conf
salt 'minion' lxc.read_conf /etc/lxc/mycontainer.conf out_format=commented
'''
ret_commented = []
ret_simple = {}
with salt.utils.files.fopen(conf_file, 'r') as fp_:
for line in salt.utils.data.decode(fp_.readlines()):
if '=' not in line:
ret_commented.append(line)
continue
comps = line.split('=')
value = '='.join(comps[1:]).strip()
comment = None
if value.strip().startswith('#'):
vcomps = value.strip().split('#')
value = vcomps[1].strip()
comment = '#'.join(vcomps[1:]).strip()
ret_commented.append({comps[0].strip(): {
'value': value,
'comment': comment,
}})
else:
ret_commented.append({comps[0].strip(): value})
ret_simple[comps[0].strip()] = value
if out_format == 'simple':
return ret_simple
return ret_commented
def write_conf(conf_file, conf):
'''
Write out an LXC configuration file
This is normally only used internally. The format of the data structure
must match that which is returned from ``lxc.read_conf()``, with
``out_format`` set to ``commented``.
An example might look like:
.. code-block:: python
[
{'lxc.utsname': '$CONTAINER_NAME'},
'# This is a commented line\\n',
'\\n',
{'lxc.mount': '$CONTAINER_FSTAB'},
{'lxc.rootfs': {'comment': 'This is another test',
'value': 'This is another test'}},
'\\n',
{'lxc.network.type': 'veth'},
{'lxc.network.flags': 'up'},
{'lxc.network.link': 'br0'},
{'lxc.network.mac': '$CONTAINER_MACADDR'},
{'lxc.network.ipv4': '$CONTAINER_IPADDR'},
{'lxc.network.name': '$CONTAINER_DEVICENAME'},
]
CLI Example:
.. code-block:: bash
salt 'minion' lxc.write_conf /etc/lxc/mycontainer.conf \\
out_format=commented
'''
if not isinstance(conf, list):
raise SaltInvocationError('Configuration must be passed as a list')
# construct the content prior to write to the file
# to avoid half written configs
content = ''
for line in conf:
if isinstance(line, (six.text_type, six.string_types)):
content += line
elif isinstance(line, dict):
for key in list(line.keys()):
out_line = None
if isinstance(
line[key],
(six.text_type, six.string_types, six.integer_types, float)
):
out_line = ' = '.join((key, "{0}".format(line[key])))
elif isinstance(line[key], dict):
out_line = ' = '.join((key, line[key]['value']))
if 'comment' in line[key]:
out_line = ' # '.join((out_line, line[key]['comment']))
if out_line:
content += out_line
content += '\n'
with salt.utils.files.fopen(conf_file, 'w') as fp_:
fp_.write(salt.utils.stringutils.to_str(content))
return {}
def edit_conf(conf_file,
out_format='simple',
read_only=False,
lxc_config=None,
**kwargs):
'''
Edit an LXC configuration file. If a setting is already present inside the
file, its value will be replaced. If it does not exist, it will be appended
to the end of the file. Comments and blank lines will be kept in-tact if
they already exist in the file.
out_format:
Set to simple if you need backward compatibility (multiple items for a
simple key is not supported)
read_only:
return only the edited configuration without applying it
to the underlying lxc configuration file
lxc_config:
List of dict containning lxc configuration items
For network configuration, you also need to add the device it belongs
to, otherwise it will default to eth0.
Also, any change to a network parameter will result in the whole
network reconfiguration to avoid mismatchs, be aware of that !
After the file is edited, its contents will be returned. By default, it
will be returned in ``simple`` format, meaning an unordered dict (which
may not represent the actual file order). Passing in an ``out_format`` of
``commented`` will return a data structure which accurately represents the
order and content of the file.
CLI Example:
.. code-block:: bash
salt 'minion' lxc.edit_conf /etc/lxc/mycontainer.conf \\
out_format=commented lxc.network.type=veth
salt 'minion' lxc.edit_conf /etc/lxc/mycontainer.conf \\
out_format=commented \\
lxc_config="[{'lxc.network.name': 'eth0', \\
'lxc.network.ipv4': '1.2.3.4'},
{'lxc.network.name': 'eth2', \\
'lxc.network.ipv4': '1.2.3.5',\\
'lxc.network.gateway': '1.2.3.1'}]"
'''
data = []
try:
conf = read_conf(conf_file, out_format=out_format)
except Exception:
conf = []
if not lxc_config:
lxc_config = []
lxc_config = copy.deepcopy(lxc_config)
# search if we want to access net config
# in that case, we will replace all the net configuration
net_config = []
for lxc_kws in lxc_config + [kwargs]:
net_params = {}
for kwarg in [a for a in lxc_kws]:
if kwarg.startswith('__'):
continue
if kwarg.startswith('lxc.network.'):
net_params[kwarg] = lxc_kws[kwarg]
lxc_kws.pop(kwarg, None)
if net_params:
net_config.append(net_params)
nic_opts = salt.utils.odict.OrderedDict()
for params in net_config:
dev = params.get('lxc.network.name', DEFAULT_NIC)
dev_opts = nic_opts.setdefault(dev, salt.utils.odict.OrderedDict())
for param in params:
opt = param.replace('lxc.network.', '')
opt = {'hwaddr': 'mac'}.get(opt, opt)
dev_opts[opt] = params[param]
net_changes = []
if nic_opts:
net_changes = _config_list(conf, only_net=True,
**{'network_profile': DEFAULT_NIC,
'nic_opts': nic_opts})
if net_changes:
lxc_config.extend(net_changes)
for line in conf:
if not isinstance(line, dict):
data.append(line)
continue
else:
for key in list(line.keys()):
val = line[key]
if net_changes and key.startswith('lxc.network.'):
continue
found = False
for ix in range(len(lxc_config)):
kw = lxc_config[ix]
if key in kw:
found = True
data.append({key: kw[key]})
del kw[key]
if not found:
data.append({key: val})
for lxc_kws in lxc_config:
for kwarg in lxc_kws:
data.append({kwarg: lxc_kws[kwarg]})
if read_only:
return data
write_conf(conf_file, data)
return read_conf(conf_file, out_format)
def reboot(name, path=None):
'''
Reboot a container.
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Examples:
.. code-block:: bash
salt 'minion' lxc.reboot myvm
'''
ret = {'result': True,
'changes': {},
'comment': '{0} rebooted'.format(name)}
does_exist = exists(name, path=path)
if does_exist and (state(name, path=path) == 'running'):
try:
stop(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
ret['result'] = False
return ret
if does_exist and (state(name, path=path) != 'running'):
try:
start(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
ret['result'] = False
return ret
ret['changes'][name] = 'rebooted'
return ret
def reconfigure(name,
cpu=None,
cpuset=None,
cpushare=None,
memory=None,
profile=None,
network_profile=None,
nic_opts=None,
bridge=None,
gateway=None,
autostart=None,
utsname=None,
rootfs=None,
path=None,
**kwargs):
'''
Reconfigure a container.
This only applies to a few property
name
Name of the container.
utsname
utsname of the container.
.. versionadded:: 2016.3.0
rootfs
rootfs of the container.
.. versionadded:: 2016.3.0
cpu
Select a random number of cpu cores and assign it to the cpuset, if the
cpuset option is set then this option will be ignored
cpuset
Explicitly define the cpus this container will be bound to
cpushare
cgroups cpu shares.
autostart
autostart container on reboot
memory
cgroups memory limit, in MB.
(0 for nolimit, None for old default 1024MB)
gateway
the ipv4 gateway to use
the default does nothing more than lxcutils does
bridge
the bridge to use
the default does nothing more than lxcutils does
nic
Network interfaces profile (defined in config or pillar).
nic_opts
Extra options for network interfaces, will override
``{"eth0": {"mac": "aa:bb:cc:dd:ee:ff", "ipv4": "10.1.1.1", "ipv6": "2001:db8::ff00:42:8329"}}``
or
``{"eth0": {"mac": "aa:bb:cc:dd:ee:ff", "ipv4": "10.1.1.1/24", "ipv6": "2001:db8::ff00:42:8329"}}``
path
path to the container parent
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt-call -lall mc_lxc_fork.reconfigure foobar nic_opts="{'eth1': {'mac': '00:16:3e:dd:ee:44'}}" memory=4
'''
changes = {}
cpath = get_root_path(path)
path = os.path.join(cpath, name, 'config')
ret = {'name': name,
'comment': 'config for {0} up to date'.format(name),
'result': True,
'changes': changes}
profile = get_container_profile(copy.deepcopy(profile))
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, _marker)
profile_match = profile.pop(key, default)
# let kwarg overrides be the preferred choice
if kw_overrides_match is _marker:
return profile_match
return kw_overrides_match
if nic_opts is not None and not network_profile:
network_profile = DEFAULT_NIC
if autostart is not None:
autostart = select('autostart', autostart)
else:
autostart = 'keep'
if not utsname:
utsname = select('utsname', utsname)
if os.path.exists(path):
old_chunks = read_conf(path, out_format='commented')
make_kw = salt.utils.odict.OrderedDict([
('utsname', utsname),
('rootfs', rootfs),
('autostart', autostart),
('cpu', cpu),
('gateway', gateway),
('cpuset', cpuset),
('cpushare', cpushare),
('network_profile', network_profile),
('nic_opts', nic_opts),
('bridge', bridge)])
# match 0 and none as memory = 0 in lxc config is harmful
if memory:
make_kw['memory'] = memory
kw = salt.utils.odict.OrderedDict()
for key, val in six.iteritems(make_kw):
if val is not None:
kw[key] = val
new_cfg = _config_list(conf_tuples=old_chunks, **kw)
if new_cfg:
edit_conf(path, out_format='commented', lxc_config=new_cfg)
chunks = read_conf(path, out_format='commented')
if old_chunks != chunks:
ret['comment'] = '{0} lxc config updated'.format(name)
if state(name, path=path) == 'running':
cret = reboot(name, path=path)
ret['result'] = cret['result']
return ret
def apply_network_profile(name, network_profile, nic_opts=None, path=None):
'''
.. versionadded:: 2015.5.0
Apply a network profile to a container
network_profile
profile name or default values (dict)
nic_opts
values to override in defaults (dict)
indexed by nic card names
path
path to the container parent
.. versionadded:: 2015.8.0
CLI Examples:
.. code-block:: bash
salt 'minion' lxc.apply_network_profile web1 centos
salt 'minion' lxc.apply_network_profile web1 centos \\
nic_opts="{'eth0': {'mac': 'xx:xx:xx:xx:xx:xx'}}"
salt 'minion' lxc.apply_network_profile web1 \\
"{'eth0': {'mac': 'xx:xx:xx:xx:xx:yy'}}"
nic_opts="{'eth0': {'mac': 'xx:xx:xx:xx:xx:xx'}}"
The special case to disable use of ethernet nics:
.. code-block:: bash
salt 'minion' lxc.apply_network_profile web1 centos \\
"{eth0: {disable: true}}"
'''
cpath = get_root_path(path)
cfgpath = os.path.join(cpath, name, 'config')
before = []
with salt.utils.files.fopen(cfgpath, 'r') as fp_:
for line in fp_:
before.append(line)
lxcconfig = _LXCConfig(name=name, path=path)
old_net = lxcconfig._filter_data('lxc.network')
network_params = {}
for param in _network_conf(
conf_tuples=old_net,
network_profile=network_profile, nic_opts=nic_opts
):
network_params.update(param)
if network_params:
edit_conf(cfgpath, out_format='commented', **network_params)
after = []
with salt.utils.files.fopen(cfgpath, 'r') as fp_:
for line in fp_:
after.append(line)
diff = ''
for line in difflib.unified_diff(before,
after,
fromfile='before',
tofile='after'):
diff += line
return diff
def get_pid(name, path=None):
'''
Returns a container pid.
Throw an exception if the container isn't running.
CLI Example:
.. code-block:: bash
salt '*' lxc.get_pid name
'''
if name not in list_(limit='running', path=path):
raise CommandExecutionError('Container {0} is not running, can\'t determine PID'.format(name))
info = __salt__['cmd.run']('lxc-info -n {0}'.format(name)).split("\n")
pid = [line.split(':')[1].strip() for line in info if re.match(r'\s*PID', line)][0]
return pid
def add_veth(name, interface_name, bridge=None, path=None):
'''
Add a veth to a container.
Note : this function doesn't update the container config, just add the interface at runtime
name
Name of the container
interface_name
Name of the interface in the container
bridge
Name of the bridge to attach the interface to (facultative)
CLI Examples:
.. code-block:: bash
salt '*' lxc.add_veth container_name eth1 br1
salt '*' lxc.add_veth container_name eth1
'''
# Get container init PID
pid = get_pid(name, path=path)
# Generate a ramdom string for veth and ensure that is isn't present on the system
while True:
random_veth = 'veth'+''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(6))
if random_veth not in __salt__['network.interfaces']().keys():
break
# Check prerequisites
if not __salt__['file.directory_exists']('/var/run/'):
raise CommandExecutionError('Directory /var/run required for lxc.add_veth doesn\'t exists')
if not __salt__['file.file_exists']('/proc/{0}/ns/net'.format(pid)):
raise CommandExecutionError('Proc file for container {0} network namespace doesn\'t exists'.format(name))
if not __salt__['file.directory_exists']('/var/run/netns'):
__salt__['file.mkdir']('/var/run/netns')
# Ensure that the symlink is up to date (change on container restart)
if __salt__['file.is_link']('/var/run/netns/{0}'.format(name)):
__salt__['file.remove']('/var/run/netns/{0}'.format(name))
__salt__['file.symlink']('/proc/{0}/ns/net'.format(pid), '/var/run/netns/{0}'.format(name))
# Ensure that interface doesn't exists
interface_exists = 0 == __salt__['cmd.retcode']('ip netns exec {netns} ip address list {interface}'.format(
netns=name,
interface=interface_name
))
if interface_exists:
raise CommandExecutionError('Interface {interface} already exists in {container}'.format(
interface=interface_name,
container=name
))
# Create veth and bring it up
if __salt__['cmd.retcode']('ip link add name {veth} type veth peer name {veth}_c'.format(veth=random_veth)) != 0:
raise CommandExecutionError('Error while creating the veth pair {0}'.format(random_veth))
if __salt__['cmd.retcode']('ip link set dev {0} up'.format(random_veth)) != 0:
raise CommandExecutionError('Error while bringing up host-side veth {0}'.format(random_veth))
# Attach it to the container
attached = 0 == __salt__['cmd.retcode']('ip link set dev {veth}_c netns {container} name {interface_name}'.format(
veth=random_veth,
container=name,
interface_name=interface_name
))
if not attached:
raise CommandExecutionError('Error while attaching the veth {veth} to container {container}'.format(
veth=random_veth,
container=name
))
__salt__['file.remove']('/var/run/netns/{0}'.format(name))
if bridge is not None:
__salt__['bridge.addif'](bridge, random_veth)
|
saltstack/salt
|
salt/modules/lxc.py
|
_ensure_running
|
python
|
def _ensure_running(name, no_start=False, path=None):
'''
If the container is not currently running, start it. This function returns
the state that the container was in before changing
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
'''
_ensure_exists(name, path=path)
pre = state(name, path=path)
if pre == 'running':
# This will be a no-op but running the function will give us a pretty
# return dict.
return start(name, path=path)
elif pre == 'stopped':
if no_start:
raise CommandExecutionError(
'Container \'{0}\' is not running'.format(name)
)
return start(name, path=path)
elif pre == 'frozen':
if no_start:
raise CommandExecutionError(
'Container \'{0}\' is not running'.format(name)
)
return unfreeze(name, path=path)
|
If the container is not currently running, start it. This function returns
the state that the container was in before changing
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/lxc.py#L2312-L2340
|
[
"def start(name, **kwargs):\n '''\n Start the named container\n\n path\n path to the container parent directory\n default: /var/lib/lxc (system)\n\n .. versionadded:: 2015.8.0\n\n lxc_config\n path to a lxc config file\n config file will be guessed from container name otherwise\n\n .. versionadded:: 2015.8.0\n\n use_vt\n run the command through VT\n\n .. versionadded:: 2015.8.0\n\n CLI Example:\n\n .. code-block:: bash\n\n salt myminion lxc.start name\n '''\n path = kwargs.get('path', None)\n cpath = get_root_path(path)\n lxc_config = kwargs.get('lxc_config', None)\n cmd = 'lxc-start'\n if not lxc_config:\n lxc_config = os.path.join(cpath, name, 'config')\n # we try to start, even without config, if global opts are there\n if os.path.exists(lxc_config):\n cmd += ' -f {0}'.format(pipes.quote(lxc_config))\n cmd += ' -d'\n _ensure_exists(name, path=path)\n if state(name, path=path) == 'frozen':\n raise CommandExecutionError(\n 'Container \\'{0}\\' is frozen, use lxc.unfreeze'.format(name)\n )\n # lxc-start daemonize itself violently, we must not communicate with it\n use_vt = kwargs.get('use_vt', None)\n with_communicate = kwargs.get('with_communicate', False)\n return _change_state(cmd, name, 'running',\n stdout=None,\n stderr=None,\n stdin=None,\n with_communicate=with_communicate,\n path=path,\n use_vt=use_vt)\n",
"def state(name, path=None):\n '''\n Returns the state of a container.\n\n path\n path to the container parent directory (default: /var/lib/lxc)\n\n .. versionadded:: 2015.8.0\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' lxc.state name\n '''\n # Don't use _ensure_exists() here, it will mess with _change_state()\n\n cachekey = 'lxc.state.{0}{1}'.format(name, path)\n try:\n return __context__[cachekey]\n except KeyError:\n if not exists(name, path=path):\n __context__[cachekey] = None\n else:\n cmd = 'lxc-info'\n if path:\n cmd += ' -P {0}'.format(pipes.quote(path))\n cmd += ' -n {0}'.format(name)\n ret = __salt__['cmd.run_all'](cmd, python_shell=False)\n if ret['retcode'] != 0:\n _clear_context()\n raise CommandExecutionError(\n 'Unable to get state of container \\'{0}\\''.format(name)\n )\n c_infos = ret['stdout'].splitlines()\n c_state = None\n for c_info in c_infos:\n stat = c_info.split(':')\n if stat[0].lower() == 'state':\n c_state = stat[1].strip().lower()\n break\n __context__[cachekey] = c_state\n return __context__[cachekey]\n",
"def _ensure_exists(name, path=None):\n '''\n Raise an exception if the container does not exist\n '''\n if not exists(name, path=path):\n raise CommandExecutionError(\n 'Container \\'{0}\\' does not exist'.format(name)\n )\n"
] |
# -*- coding: utf-8 -*-
'''
Control Linux Containers via Salt
:depends: lxc package for distribution
lxc >= 1.0 (even beta alpha) is required
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import datetime
import copy
import string
import textwrap
import difflib
import logging
import tempfile
import os
import pipes
import time
import shutil
import re
import random
# Import salt libs
import salt.utils.args
import salt.utils.cloud
import salt.utils.data
import salt.utils.dictupdate
import salt.utils.files
import salt.utils.functools
import salt.utils.hashutils
import salt.utils.network
import salt.utils.odict
import salt.utils.path
import salt.utils.stringutils
from salt.exceptions import CommandExecutionError, SaltInvocationError
import salt.config
from salt.utils.versions import LooseVersion as _LooseVersion
# Import 3rd-party libs
from salt.ext import six
# pylint: disable=import-error,no-name-in-module
from salt.ext.six.moves import range # pylint: disable=redefined-builtin
from salt.ext.six.moves.urllib.parse import urlparse as _urlparse
# pylint: enable=import-error,no-name-in-module
# Set up logging
log = logging.getLogger(__name__)
# Don't shadow built-in's.
__func_alias__ = {
'list_': 'list',
'ls_': 'ls'
}
__virtualname__ = 'lxc'
DEFAULT_NIC = 'eth0'
DEFAULT_BR = 'br0'
SEED_MARKER = '/lxc.initial_seed'
EXEC_DRIVER = 'lxc-attach'
DEFAULT_PATH = '/var/lib/lxc'
_marker = object()
def __virtual__():
if salt.utils.path.which('lxc-start'):
return __virtualname__
# To speed up the whole thing, we decided to not use the
# subshell way and assume things are in place for lxc
# Discussion made by @kiorky and @thatch45
# lxc-version presence is not sufficient, in lxc1.0 alpha
# (precise backports), we have it and it is sufficient
# for the module to execute.
# elif salt.utils.path.which('lxc-version'):
# passed = False
# try:
# passed = subprocess.check_output(
# 'lxc-version').split(':')[1].strip() >= '1.0'
# except Exception:
# pass
# if not passed:
# log.warning('Support for lxc < 1.0 may be incomplete.')
# return 'lxc'
# return False
#
return (False, 'The lxc execution module cannot be loaded: the lxc-start binary is not in the path.')
def get_root_path(path):
'''
Get the configured lxc root for containers
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.get_root_path
'''
if not path:
path = __opts__.get('lxc.root_path', DEFAULT_PATH)
return path
def version():
'''
Return the actual lxc client version
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.version
'''
k = 'lxc.version'
if not __context__.get(k, None):
cversion = __salt__['cmd.run_all']('lxc-info --version')
if not cversion['retcode']:
ver = _LooseVersion(cversion['stdout'])
if ver < _LooseVersion('1.0'):
raise CommandExecutionError('LXC should be at least 1.0')
__context__[k] = "{0}".format(ver)
return __context__.get(k, None)
def _clear_context():
'''
Clear any lxc variables set in __context__
'''
for var in [x for x in __context__ if x.startswith('lxc.')]:
log.trace('Clearing __context__[\'%s\']', var)
__context__.pop(var, None)
def _ip_sort(ip):
'''Ip sorting'''
idx = '001'
if ip == '127.0.0.1':
idx = '200'
if ip == '::1':
idx = '201'
elif '::' in ip:
idx = '100'
return '{0}___{1}'.format(idx, ip)
def search_lxc_bridges():
'''
Search which bridges are potentially available as LXC bridges
CLI Example:
.. code-block:: bash
salt '*' lxc.search_lxc_bridges
'''
bridges = __context__.get('lxc.bridges', None)
# either match not yet called or no bridges were found
# to handle the case where lxc was not installed on the first
# call
if not bridges:
bridges = set()
running_bridges = set()
bridges.add(DEFAULT_BR)
try:
output = __salt__['cmd.run_all']('brctl show')
for line in output['stdout'].splitlines()[1:]:
if not line.startswith(' '):
running_bridges.add(line.split()[0].strip())
except (SaltInvocationError, CommandExecutionError):
pass
for ifc, ip in six.iteritems(
__grains__.get('ip_interfaces', {})
):
if ifc in running_bridges:
bridges.add(ifc)
elif os.path.exists(
'/sys/devices/virtual/net/{0}/bridge'.format(ifc)
):
bridges.add(ifc)
bridges = list(bridges)
# if we found interfaces that have lxc in their names
# we filter them as being the potential lxc bridges
# we also try to default on br0 on other cases
def sort_bridges(a):
pref = 'z'
if 'lxc' in a:
pref = 'a'
elif 'br0' == a:
pref = 'c'
return '{0}_{1}'.format(pref, a)
bridges.sort(key=sort_bridges)
__context__['lxc.bridges'] = bridges
return bridges
def search_lxc_bridge():
'''
Search the first bridge which is potentially available as LXC bridge
CLI Example:
.. code-block:: bash
salt '*' lxc.search_lxc_bridge
'''
return search_lxc_bridges()[0]
def _get_salt_config(config, **kwargs):
if not config:
config = kwargs.get('minion', {})
if not config:
config = {}
config.setdefault('master',
kwargs.get('master',
__opts__.get('master',
__opts__['id'])))
config.setdefault(
'master_port',
kwargs.get('master_port',
__opts__.get('master_port',
__opts__.get('ret_port',
__opts__.get('4506')))))
if not config['master']:
config = {}
return config
def cloud_init_interface(name, vm_=None, **kwargs):
'''
Interface between salt.cloud.lxc driver and lxc.init
``vm_`` is a mapping of vm opts in the salt.cloud format
as documented for the lxc driver.
This can be used either:
- from the salt cloud driver
- because you find the argument to give easier here
than using directly lxc.init
.. warning::
BE REALLY CAREFUL CHANGING DEFAULTS !!!
IT'S A RETRO COMPATIBLE INTERFACE WITH
THE SALT CLOUD DRIVER (ask kiorky).
name
name of the lxc container to create
pub_key
public key to preseed the minion with.
Can be the keycontent or a filepath
priv_key
private key to preseed the minion with.
Can be the keycontent or a filepath
path
path to the container parent directory (default: /var/lib/lxc)
.. versionadded:: 2015.8.0
profile
:ref:`profile <tutorial-lxc-profiles-container>` selection
network_profile
:ref:`network profile <tutorial-lxc-profiles-network>` selection
nic_opts
per interface settings compatibles with
network profile (ipv4/ipv6/link/gateway/mac/netmask)
eg::
- {'eth0': {'mac': '00:16:3e:01:29:40',
'gateway': None, (default)
'link': 'br0', (default)
'gateway': None, (default)
'netmask': '', (default)
'ip': '22.1.4.25'}}
unconditional_install
given to lxc.bootstrap (see relative doc)
force_install
given to lxc.bootstrap (see relative doc)
config
any extra argument for the salt minion config
dnsservers
list of DNS servers to set inside the container
dns_via_dhcp
do not set the dns servers, let them be set by the dhcp.
autostart
autostart the container at boot time
password
administrative password for the container
bootstrap_delay
delay before launching bootstrap script at Container init
.. warning::
Legacy but still supported options:
from_container
which container we use as a template
when running lxc.clone
image
which template do we use when we
are using lxc.create. This is the default
mode unless you specify something in from_container
backing
which backing store to use.
Values can be: overlayfs, dir(default), lvm, zfs, brtfs
fstype
When using a blockdevice level backing store,
which filesystem to use on
size
When using a blockdevice level backing store,
which size for the filesystem to use on
snapshot
Use snapshot when cloning the container source
vgname
if using LVM: vgname
lvname
if using LVM: lvname
thinpool:
if using LVM: thinpool
ip
ip for the primary nic
mac
mac address for the primary nic
netmask
netmask for the primary nic (24)
= ``vm_.get('netmask', '24')``
bridge
bridge for the primary nic (lxcbr0)
gateway
network gateway for the container
additional_ips
additional ips which will be wired on the main bridge (br0)
which is connected to internet.
Be aware that you may use manual virtual mac addresses
providen by you provider (online, ovh, etc).
This is a list of mappings {ip: '', mac: '', netmask:''}
Set gateway to None and an interface with a gateway
to escape from another interface that eth0.
eg::
- {'mac': '00:16:3e:01:29:40',
'gateway': None, (default)
'link': 'br0', (default)
'netmask': '', (default)
'ip': '22.1.4.25'}
users
administrative users for the container
default: [root] and [root, ubuntu] on ubuntu
default_nic
name of the first interface, you should
really not override this
CLI Example:
.. code-block:: bash
salt '*' lxc.cloud_init_interface foo
'''
if vm_ is None:
vm_ = {}
vm_ = copy.deepcopy(vm_)
vm_ = salt.utils.dictupdate.update(vm_, kwargs)
profile_data = copy.deepcopy(
vm_.get('lxc_profile',
vm_.get('profile', {})))
if not isinstance(profile_data, (dict, six.string_types)):
profile_data = {}
profile = get_container_profile(profile_data)
def _cloud_get(k, default=None):
return vm_.get(k, profile.get(k, default))
if name is None:
name = vm_['name']
# if we are on ubuntu, default to ubuntu
default_template = ''
if __grains__.get('os', '') in ['Ubuntu']:
default_template = 'ubuntu'
image = _cloud_get('image')
if not image:
_cloud_get('template', default_template)
backing = _cloud_get('backing', 'dir')
if image:
profile['template'] = image
vgname = _cloud_get('vgname', None)
if vgname:
profile['vgname'] = vgname
if backing:
profile['backing'] = backing
snapshot = _cloud_get('snapshot', False)
autostart = bool(_cloud_get('autostart', True))
dnsservers = _cloud_get('dnsservers', [])
dns_via_dhcp = _cloud_get('dns_via_dhcp', True)
password = _cloud_get('password', 's3cr3t')
password_encrypted = _cloud_get('password_encrypted', False)
fstype = _cloud_get('fstype', None)
lvname = _cloud_get('lvname', None)
thinpool = _cloud_get('thinpool', None)
pub_key = _cloud_get('pub_key', None)
priv_key = _cloud_get('priv_key', None)
size = _cloud_get('size', '20G')
script = _cloud_get('script', None)
script_args = _cloud_get('script_args', None)
users = _cloud_get('users', None)
if users is None:
users = []
ssh_username = _cloud_get('ssh_username', None)
if ssh_username and (ssh_username not in users):
users.append(ssh_username)
network_profile = _cloud_get('network_profile', None)
nic_opts = kwargs.get('nic_opts', None)
netmask = _cloud_get('netmask', '24')
path = _cloud_get('path', None)
bridge = _cloud_get('bridge', None)
gateway = _cloud_get('gateway', None)
unconditional_install = _cloud_get('unconditional_install', False)
force_install = _cloud_get('force_install', True)
config = _get_salt_config(_cloud_get('config', {}), **vm_)
default_nic = _cloud_get('default_nic', DEFAULT_NIC)
# do the interface with lxc.init mainly via nic_opts
# to avoid extra and confusing extra use cases.
if not isinstance(nic_opts, dict):
nic_opts = salt.utils.odict.OrderedDict()
# have a reference to the default nic
eth0 = nic_opts.setdefault(default_nic,
salt.utils.odict.OrderedDict())
# lxc config is based of ifc order, be sure to use odicts.
if not isinstance(nic_opts, salt.utils.odict.OrderedDict):
bnic_opts = salt.utils.odict.OrderedDict()
bnic_opts.update(nic_opts)
nic_opts = bnic_opts
gw = None
# legacy salt.cloud scheme for network interfaces settings support
bridge = _cloud_get('bridge', None)
ip = _cloud_get('ip', None)
mac = _cloud_get('mac', None)
if ip:
fullip = ip
if netmask:
fullip += '/{0}'.format(netmask)
eth0['ipv4'] = fullip
if mac is not None:
eth0['mac'] = mac
for ix, iopts in enumerate(_cloud_get("additional_ips", [])):
ifh = "eth{0}".format(ix+1)
ethx = nic_opts.setdefault(ifh, {})
if gw is None:
gw = iopts.get('gateway', ethx.get('gateway', None))
if gw:
# only one and only one default gateway is allowed !
eth0.pop('gateway', None)
gateway = None
# even if the gateway if on default "eth0" nic
# and we popped it will work
# as we reinject or set it here.
ethx['gateway'] = gw
elink = iopts.get('link', ethx.get('link', None))
if elink:
ethx['link'] = elink
# allow dhcp
aip = iopts.get('ipv4', iopts.get('ip', None))
if aip:
ethx['ipv4'] = aip
nm = iopts.get('netmask', '')
if nm:
ethx['ipv4'] += '/{0}'.format(nm)
for i in ('mac', 'hwaddr'):
if i in iopts:
ethx['mac'] = iopts[i]
break
if 'mac' not in ethx:
ethx['mac'] = salt.utils.network.gen_mac()
# last round checking for unique gateway and such
gw = None
for ethx in [a for a in nic_opts]:
ndata = nic_opts[ethx]
if gw:
ndata.pop('gateway', None)
if 'gateway' in ndata:
gw = ndata['gateway']
gateway = None
# only use a default bridge / gateway if we configured them
# via the legacy salt cloud configuration style.
# On other cases, we should rely on settings provided by the new
# salt lxc network profile style configuration which can
# be also be overridden or a per interface basis via the nic_opts dict.
if bridge:
eth0['link'] = bridge
if gateway:
eth0['gateway'] = gateway
#
lxc_init_interface = {}
lxc_init_interface['name'] = name
lxc_init_interface['config'] = config
lxc_init_interface['memory'] = _cloud_get('memory', 0) # nolimit
lxc_init_interface['pub_key'] = pub_key
lxc_init_interface['priv_key'] = priv_key
lxc_init_interface['nic_opts'] = nic_opts
for clone_from in ['clone_from', 'clone', 'from_container']:
# clone_from should default to None if not available
lxc_init_interface['clone_from'] = _cloud_get(clone_from, None)
if lxc_init_interface['clone_from'] is not None:
break
lxc_init_interface['profile'] = profile
lxc_init_interface['snapshot'] = snapshot
lxc_init_interface['dnsservers'] = dnsservers
lxc_init_interface['fstype'] = fstype
lxc_init_interface['path'] = path
lxc_init_interface['vgname'] = vgname
lxc_init_interface['size'] = size
lxc_init_interface['lvname'] = lvname
lxc_init_interface['thinpool'] = thinpool
lxc_init_interface['force_install'] = force_install
lxc_init_interface['unconditional_install'] = (
unconditional_install
)
lxc_init_interface['bootstrap_url'] = script
lxc_init_interface['bootstrap_args'] = script_args
lxc_init_interface['bootstrap_shell'] = _cloud_get('bootstrap_shell', 'sh')
lxc_init_interface['bootstrap_delay'] = _cloud_get('bootstrap_delay', None)
lxc_init_interface['autostart'] = autostart
lxc_init_interface['users'] = users
lxc_init_interface['password'] = password
lxc_init_interface['password_encrypted'] = password_encrypted
# be sure not to let objects goes inside the return
# as this return will be msgpacked for use in the runner !
lxc_init_interface['network_profile'] = network_profile
for i in ['cpu', 'cpuset', 'cpushare']:
if _cloud_get(i, None):
try:
lxc_init_interface[i] = vm_[i]
except KeyError:
lxc_init_interface[i] = profile[i]
return lxc_init_interface
def _get_profile(key, name, **kwargs):
if isinstance(name, dict):
profilename = name.pop('name', None)
return _get_profile(key, profilename, **name)
if name is None:
profile_match = {}
else:
profile_match = \
__salt__['config.get'](
'lxc.{1}:{0}'.format(name, key),
default=None,
merge='recurse'
)
if profile_match is None:
# No matching profile, make the profile an empty dict so that
# overrides can be applied below.
profile_match = {}
if not isinstance(profile_match, dict):
raise CommandExecutionError('lxc.{0} must be a dictionary'.format(key))
# Overlay the kwargs to override matched profile data
overrides = salt.utils.args.clean_kwargs(**copy.deepcopy(kwargs))
profile_match = salt.utils.dictupdate.update(
copy.deepcopy(profile_match),
overrides
)
return profile_match
def get_container_profile(name=None, **kwargs):
'''
.. versionadded:: 2015.5.0
Gather a pre-configured set of container configuration parameters. If no
arguments are passed, an empty profile is returned.
Profiles can be defined in the minion or master config files, or in pillar
or grains, and are loaded using :mod:`config.get
<salt.modules.config.get>`. The key under which LXC profiles must be
configured is ``lxc.container_profile.profile_name``. An example container
profile would be as follows:
.. code-block:: yaml
lxc.container_profile:
ubuntu:
template: ubuntu
backing: lvm
vgname: lxc
size: 1G
Parameters set in a profile can be overridden by passing additional
container creation arguments (such as the ones passed to :mod:`lxc.create
<salt.modules.lxc.create>`) to this function.
A profile can be defined either as the name of the profile, or a dictionary
of variable names and values. See the :ref:`LXC Tutorial
<tutorial-lxc-profiles>` for more information on how to use LXC profiles.
CLI Example:
.. code-block:: bash
salt-call lxc.get_container_profile centos
salt-call lxc.get_container_profile ubuntu template=ubuntu backing=overlayfs
'''
profile = _get_profile('container_profile', name, **kwargs)
return profile
def get_network_profile(name=None, **kwargs):
'''
.. versionadded:: 2015.5.0
Gather a pre-configured set of network configuration parameters. If no
arguments are passed, the following default profile is returned:
.. code-block:: python
{'eth0': {'link': 'br0', 'type': 'veth', 'flags': 'up'}}
Profiles can be defined in the minion or master config files, or in pillar
or grains, and are loaded using :mod:`config.get
<salt.modules.config.get>`. The key under which LXC profiles must be
configured is ``lxc.network_profile``. An example network profile would be
as follows:
.. code-block:: yaml
lxc.network_profile.centos:
eth0:
link: br0
type: veth
flags: up
To disable networking entirely:
.. code-block:: yaml
lxc.network_profile.centos:
eth0:
disable: true
Parameters set in a profile can be overridden by passing additional
arguments to this function.
A profile can be passed either as the name of the profile, or a
dictionary of variable names and values. See the :ref:`LXC Tutorial
<tutorial-lxc-profiles>` for more information on how to use network
profiles.
.. warning::
The ``ipv4``, ``ipv6``, ``gateway``, and ``link`` (bridge) settings in
network profiles will only work if the container doesn't redefine the
network configuration (for example in
``/etc/sysconfig/network-scripts/ifcfg-<interface_name>`` on
RHEL/CentOS, or ``/etc/network/interfaces`` on Debian/Ubuntu/etc.)
CLI Example:
.. code-block:: bash
salt-call lxc.get_network_profile default
'''
profile = _get_profile('network_profile', name, **kwargs)
return profile
def _rand_cpu_str(cpu):
'''
Return a random subset of cpus for the cpuset config
'''
cpu = int(cpu)
avail = __salt__['status.nproc']()
if cpu < avail:
return '0-{0}'.format(avail)
to_set = set()
while len(to_set) < cpu:
choice = random.randint(0, avail - 1)
if choice not in to_set:
to_set.add(six.text_type(choice))
return ','.join(sorted(to_set))
def _network_conf(conf_tuples=None, **kwargs):
'''
Network configuration defaults
network_profile
as for containers, we can either call this function
either with a network_profile dict or network profile name
in the kwargs
nic_opts
overrides or extra nics in the form {nic_name: {set: tings}
'''
nic = kwargs.get('network_profile', None)
ret = []
nic_opts = kwargs.get('nic_opts', {})
if nic_opts is None:
# coming from elsewhere
nic_opts = {}
if not conf_tuples:
conf_tuples = []
old = _get_veths(conf_tuples)
if not old:
old = {}
# if we have a profile name, get the profile and load the network settings
# this will obviously by default look for a profile called "eth0"
# or by what is defined in nic_opts
# and complete each nic settings by sane defaults
if nic and isinstance(nic, (six.string_types, dict)):
nicp = get_network_profile(nic)
else:
nicp = {}
if DEFAULT_NIC not in nicp:
nicp[DEFAULT_NIC] = {}
kwargs = copy.deepcopy(kwargs)
gateway = kwargs.pop('gateway', None)
bridge = kwargs.get('bridge', None)
if nic_opts:
for dev, args in six.iteritems(nic_opts):
ethx = nicp.setdefault(dev, {})
try:
ethx = salt.utils.dictupdate.update(ethx, args)
except AttributeError:
raise SaltInvocationError('Invalid nic_opts configuration')
ifs = [a for a in nicp]
ifs += [a for a in old if a not in nicp]
ifs.sort()
gateway_set = False
for dev in ifs:
args = nicp.get(dev, {})
opts = nic_opts.get(dev, {}) if nic_opts else {}
old_if = old.get(dev, {})
disable = opts.get('disable', args.get('disable', False))
if disable:
continue
mac = opts.get('mac',
opts.get('hwaddr',
args.get('mac',
args.get('hwaddr', ''))))
type_ = opts.get('type', args.get('type', ''))
flags = opts.get('flags', args.get('flags', ''))
link = opts.get('link', args.get('link', ''))
ipv4 = opts.get('ipv4', args.get('ipv4', ''))
ipv6 = opts.get('ipv6', args.get('ipv6', ''))
infos = salt.utils.odict.OrderedDict([
('lxc.network.type', {
'test': not type_,
'value': type_,
'old': old_if.get('lxc.network.type'),
'default': 'veth'}),
('lxc.network.name', {
'test': False,
'value': dev,
'old': dev,
'default': dev}),
('lxc.network.flags', {
'test': not flags,
'value': flags,
'old': old_if.get('lxc.network.flags'),
'default': 'up'}),
('lxc.network.link', {
'test': not link,
'value': link,
'old': old_if.get('lxc.network.link'),
'default': search_lxc_bridge()}),
('lxc.network.hwaddr', {
'test': not mac,
'value': mac,
'old': old_if.get('lxc.network.hwaddr'),
'default': salt.utils.network.gen_mac()}),
('lxc.network.ipv4', {
'test': not ipv4,
'value': ipv4,
'old': old_if.get('lxc.network.ipv4', ''),
'default': None}),
('lxc.network.ipv6', {
'test': not ipv6,
'value': ipv6,
'old': old_if.get('lxc.network.ipv6', ''),
'default': None})])
# for each parameter, if not explicitly set, the
# config value present in the LXC configuration should
# take precedence over the profile configuration
for info in list(infos.keys()):
bundle = infos[info]
if bundle['test']:
if bundle['old']:
bundle['value'] = bundle['old']
elif bundle['default']:
bundle['value'] = bundle['default']
for info, data in six.iteritems(infos):
if data['value']:
ret.append({info: data['value']})
for key, val in six.iteritems(args):
if key == 'link' and bridge:
val = bridge
val = opts.get(key, val)
if key in [
'type', 'flags', 'name',
'gateway', 'mac', 'link', 'ipv4', 'ipv6'
]:
continue
ret.append({'lxc.network.{0}'.format(key): val})
# gateway (in automode) must be appended following network conf !
if not gateway:
gateway = args.get('gateway', None)
if gateway is not None and not gateway_set:
ret.append({'lxc.network.ipv4.gateway': gateway})
# only one network gateway ;)
gateway_set = True
# normally, this won't happen
# set the gateway if specified even if we did
# not managed the network underlying
if gateway is not None and not gateway_set:
ret.append({'lxc.network.ipv4.gateway': gateway})
# only one network gateway ;)
gateway_set = True
new = _get_veths(ret)
# verify that we did not loose the mac settings
for iface in [a for a in new]:
ndata = new[iface]
nmac = ndata.get('lxc.network.hwaddr', '')
ntype = ndata.get('lxc.network.type', '')
omac, otype = '', ''
if iface in old:
odata = old[iface]
omac = odata.get('lxc.network.hwaddr', '')
otype = odata.get('lxc.network.type', '')
# default for network type is setted here
# attention not to change the network type
# without a good and explicit reason to.
if otype and not ntype:
ntype = otype
if not ntype:
ntype = 'veth'
new[iface]['lxc.network.type'] = ntype
if omac and not nmac:
new[iface]['lxc.network.hwaddr'] = omac
ret = []
for val in six.itervalues(new):
for row in val:
ret.append(salt.utils.odict.OrderedDict([(row, val[row])]))
# on old versions of lxc, still support the gateway auto mode
# if we didn't explicitly say no to
# (lxc.network.ipv4.gateway: auto)
if _LooseVersion(version()) <= _LooseVersion('1.0.7') and \
True not in ['lxc.network.ipv4.gateway' in a for a in ret] and \
True in ['lxc.network.ipv4' in a for a in ret]:
ret.append({'lxc.network.ipv4.gateway': 'auto'})
return ret
def _get_lxc_default_data(**kwargs):
kwargs = copy.deepcopy(kwargs)
ret = {}
for k in ['utsname', 'rootfs']:
val = kwargs.get(k, None)
if val is not None:
ret['lxc.{0}'.format(k)] = val
autostart = kwargs.get('autostart')
# autostart can have made in kwargs, but with the None
# value which is invalid, we need an explicit boolean
# autostart = on is the default.
if autostart is None:
autostart = True
# we will set the regular lxc marker to restart container at
# machine (re)boot only if we did not explicitly ask
# not to touch to the autostart settings via
# autostart == 'keep'
if autostart != 'keep':
if autostart:
ret['lxc.start.auto'] = '1'
else:
ret['lxc.start.auto'] = '0'
memory = kwargs.get('memory')
if memory is not None:
# converting the config value from MB to bytes
ret['lxc.cgroup.memory.limit_in_bytes'] = memory * 1024 * 1024
cpuset = kwargs.get('cpuset')
if cpuset:
ret['lxc.cgroup.cpuset.cpus'] = cpuset
cpushare = kwargs.get('cpushare')
cpu = kwargs.get('cpu')
if cpushare:
ret['lxc.cgroup.cpu.shares'] = cpushare
if cpu and not cpuset:
ret['lxc.cgroup.cpuset.cpus'] = _rand_cpu_str(cpu)
return ret
def _config_list(conf_tuples=None, only_net=False, **kwargs):
'''
Return a list of dicts from the salt level configurations
conf_tuples
_LXCConfig compatible list of entries which can contain
- string line
- tuple (lxc config param,value)
- dict of one entry: {lxc config param: value)
only_net
by default we add to the tuples a reflection of both
the real config if avalaible and a certain amount of
default values like the cpu parameters, the memory
and etc.
On the other hand, we also no matter the case reflect
the network configuration computed from the actual config if
available and given values.
if no_default_loads is set, we will only
reflect the network configuration back to the conf tuples
list
'''
# explicit cast
only_net = bool(only_net)
if not conf_tuples:
conf_tuples = []
kwargs = copy.deepcopy(kwargs)
ret = []
if not only_net:
default_data = _get_lxc_default_data(**kwargs)
for k, val in six.iteritems(default_data):
ret.append({k: val})
net_datas = _network_conf(conf_tuples=conf_tuples, **kwargs)
ret.extend(net_datas)
return ret
def _get_veths(net_data):
'''
Parse the nic setup inside lxc conf tuples back to a dictionary indexed by
network interface
'''
if isinstance(net_data, dict):
net_data = list(net_data.items())
nics = salt.utils.odict.OrderedDict()
current_nic = salt.utils.odict.OrderedDict()
no_names = True
for item in net_data:
if item and isinstance(item, dict):
item = list(item.items())[0]
# skip LXC configuration comment lines, and play only with tuples conf
elif isinstance(item, six.string_types):
# deal with reflection of commented lxc configs
sitem = item.strip()
if sitem.startswith('#') or not sitem:
continue
elif '=' in item:
item = tuple([a.strip() for a in item.split('=', 1)])
if item[0] == 'lxc.network.type':
current_nic = salt.utils.odict.OrderedDict()
if item[0] == 'lxc.network.name':
no_names = False
nics[item[1].strip()] = current_nic
current_nic[item[0].strip()] = item[1].strip()
# if not ethernet card name has been collected, assuming we collected
# data for eth0
if no_names and current_nic:
nics[DEFAULT_NIC] = current_nic
return nics
class _LXCConfig(object):
'''
LXC configuration data
'''
pattern = re.compile(r'^(\S+)(\s*)(=)(\s*)(.*)')
non_interpretable_pattern = re.compile(r'^((#.*)|(\s*))$')
def __init__(self, **kwargs):
kwargs = copy.deepcopy(kwargs)
self.name = kwargs.pop('name', None)
path = get_root_path(kwargs.get('path', None))
self.data = []
if self.name:
self.path = os.path.join(path, self.name, 'config')
if os.path.isfile(self.path):
with salt.utils.files.fopen(self.path) as fhr:
for line in salt.utils.data.decode(fhr.readlines()):
match = self.pattern.findall((line.strip()))
if match:
self.data.append((match[0][0], match[0][-1]))
match = self.non_interpretable_pattern.findall(
(line.strip()))
if match:
self.data.append(('', match[0][0]))
else:
self.path = None
def _replace(key, val):
if val:
self._filter_data(key)
self.data.append((key, val))
default_data = _get_lxc_default_data(**kwargs)
for key, val in six.iteritems(default_data):
_replace(key, val)
old_net = self._filter_data('lxc.network')
net_datas = _network_conf(conf_tuples=old_net, **kwargs)
if net_datas:
for row in net_datas:
self.data.extend(list(row.items()))
# be sure to reset harmful settings
for idx in ['lxc.cgroup.memory.limit_in_bytes']:
if not default_data.get(idx):
self._filter_data(idx)
def as_string(self):
chunks = ('{0[0]}{1}{0[1]}'.format(item, (' = ' if item[0] else '')) for item in self.data)
return '\n'.join(chunks) + '\n'
def write(self):
if self.path:
content = self.as_string()
# 2 step rendering to be sure not to open/wipe the config
# before as_string succeeds.
with salt.utils.files.fopen(self.path, 'w') as fic:
fic.write(salt.utils.stringutils.to_str(content))
fic.flush()
def tempfile(self):
# this might look like the function name is shadowing the
# module, but it's not since the method belongs to the class
ntf = tempfile.NamedTemporaryFile()
ntf.write(self.as_string())
ntf.flush()
return ntf
def _filter_data(self, pattern):
'''
Removes parameters which match the pattern from the config data
'''
removed = []
filtered = []
for param in self.data:
if not param[0].startswith(pattern):
filtered.append(param)
else:
removed.append(param)
self.data = filtered
return removed
def _get_base(**kwargs):
'''
If the needed base does not exist, then create it, if it does exist
create nothing and return the name of the base lxc container so
it can be cloned.
'''
profile = get_container_profile(copy.deepcopy(kwargs.get('profile')))
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, _marker)
profile_match = profile.pop(key, default)
# let kwarg overrides be the preferred choice
if kw_overrides_match is _marker:
return profile_match
return kw_overrides_match
template = select('template')
image = select('image')
vgname = select('vgname')
path = kwargs.get('path', None)
# remove the above three variables from kwargs, if they exist, to avoid
# duplicates if create() is invoked below.
for param in ('path', 'image', 'vgname', 'template'):
kwargs.pop(param, None)
if image:
proto = _urlparse(image).scheme
img_tar = __salt__['cp.cache_file'](image)
img_name = os.path.basename(img_tar)
hash_ = salt.utils.hashutils.get_hash(
img_tar,
__salt__['config.get']('hash_type'))
name = '__base_{0}_{1}_{2}'.format(proto, img_name, hash_)
if not exists(name, path=path):
create(name, template=template, image=image,
path=path, vgname=vgname, **kwargs)
if vgname:
rootfs = os.path.join('/dev', vgname, name)
edit_conf(info(name, path=path)['config'],
out_format='commented', **{'lxc.rootfs': rootfs})
return name
elif template:
name = '__base_{0}'.format(template)
if not exists(name, path=path):
create(name, template=template, image=image, path=path,
vgname=vgname, **kwargs)
if vgname:
rootfs = os.path.join('/dev', vgname, name)
edit_conf(info(name, path=path)['config'],
out_format='commented', **{'lxc.rootfs': rootfs})
return name
return ''
def init(name,
config=None,
cpuset=None,
cpushare=None,
memory=None,
profile=None,
network_profile=None,
nic_opts=None,
cpu=None,
autostart=True,
password=None,
password_encrypted=None,
users=None,
dnsservers=None,
searchdomains=None,
bridge=None,
gateway=None,
pub_key=None,
priv_key=None,
force_install=False,
unconditional_install=False,
bootstrap_delay=None,
bootstrap_args=None,
bootstrap_shell=None,
bootstrap_url=None,
**kwargs):
'''
Initialize a new container.
This is a partial idempotent function as if it is already provisioned, we
will reset a bit the lxc configuration file but much of the hard work will
be escaped as markers will prevent re-execution of harmful tasks.
name
Name of the container
image
A tar archive to use as the rootfs for the container. Conflicts with
the ``template`` argument.
cpus
Select a random number of cpu cores and assign it to the cpuset, if the
cpuset option is set then this option will be ignored
cpuset
Explicitly define the cpus this container will be bound to
cpushare
cgroups cpu shares
autostart
autostart container on reboot
memory
cgroups memory limit, in MB
.. versionchanged:: 2015.5.0
If no value is passed, no limit is set. In earlier Salt versions,
not passing this value causes a 1024MB memory limit to be set, and
it was necessary to pass ``memory=0`` to set no limit.
gateway
the ipv4 gateway to use
the default does nothing more than lxcutils does
bridge
the bridge to use
the default does nothing more than lxcutils does
network_profile
Network profile to use for the container
.. versionadded:: 2015.5.0
nic_opts
Extra options for network interfaces, will override
``{"eth0": {"hwaddr": "aa:bb:cc:dd:ee:ff", "ipv4": "10.1.1.1", "ipv6": "2001:db8::ff00:42:8329"}}``
or
``{"eth0": {"hwaddr": "aa:bb:cc:dd:ee:ff", "ipv4": "10.1.1.1/24", "ipv6": "2001:db8::ff00:42:8329"}}``
users
Users for which the password defined in the ``password`` param should
be set. Can be passed as a comma separated list or a python list.
Defaults to just the ``root`` user.
password
Set the initial password for the users defined in the ``users``
parameter
password_encrypted : False
Set to ``True`` to denote a password hash instead of a plaintext
password
.. versionadded:: 2015.5.0
profile
A LXC profile (defined in config or pillar).
This can be either a real profile mapping or a string
to retrieve it in configuration
start
Start the newly-created container
dnsservers
list of dns servers to set in the container, default [] (no setting)
seed
Seed the container with the minion config. Default: ``True``
install
If salt-minion is not already installed, install it. Default: ``True``
config
Optional config parameters. By default, the id is set to
the name of the container.
master
salt master (default to minion's master)
master_port
salt master port (default to minion's master port)
pub_key
Explicit public key to preseed the minion with (optional).
This can be either a filepath or a string representing the key
priv_key
Explicit private key to preseed the minion with (optional).
This can be either a filepath or a string representing the key
approve_key
If explicit preseeding is not used;
Attempt to request key approval from the master. Default: ``True``
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
clone_from
Original from which to use a clone operation to create the container.
Default: ``None``
bootstrap_delay
Delay in seconds between end of container creation and bootstrapping.
Useful when waiting for container to obtain a DHCP lease.
.. versionadded:: 2015.5.0
bootstrap_url
See lxc.bootstrap
bootstrap_shell
See lxc.bootstrap
bootstrap_args
See lxc.bootstrap
force_install
Force installation even if salt-minion is detected,
this is the way to run vendor bootstrap scripts even
if a salt minion is already present in the container
unconditional_install
Run the script even if the container seems seeded
CLI Example:
.. code-block:: bash
salt 'minion' lxc.init name [cpuset=cgroups_cpuset] \\
[cpushare=cgroups_cpushare] [memory=cgroups_memory] \\
[nic=nic_profile] [profile=lxc_profile] \\
[nic_opts=nic_opts] [start=(True|False)] \\
[seed=(True|False)] [install=(True|False)] \\
[config=minion_config] [approve_key=(True|False) \\
[clone_from=original] [autostart=True] \\
[priv_key=/path_or_content] [pub_key=/path_or_content] \\
[bridge=lxcbr0] [gateway=10.0.3.1] \\
[dnsservers[dns1,dns2]] \\
[users=[foo]] [password='secret'] \\
[password_encrypted=(True|False)]
'''
ret = {'name': name,
'changes': {}}
profile = get_container_profile(copy.deepcopy(profile))
if not network_profile:
network_profile = profile.get('network_profile')
if not network_profile:
network_profile = DEFAULT_NIC
# Changes is a pointer to changes_dict['init']. This method is used so that
# we can have a list of changes as they are made, providing an ordered list
# of things that were changed.
changes_dict = {'init': []}
changes = changes_dict.get('init')
if users is None:
users = []
dusers = ['root']
for user in dusers:
if user not in users:
users.append(user)
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, _marker)
profile_match = profile.pop(key, default)
# let kwarg overrides be the preferred choice
if kw_overrides_match is _marker:
return profile_match
return kw_overrides_match
path = select('path')
bpath = get_root_path(path)
state_pre = state(name, path=path)
tvg = select('vgname')
vgname = tvg if tvg else __salt__['config.get']('lxc.vgname')
start_ = select('start', True)
autostart = select('autostart', autostart)
seed = select('seed', True)
install = select('install', True)
seed_cmd = select('seed_cmd')
salt_config = _get_salt_config(config, **kwargs)
approve_key = select('approve_key', True)
clone_from = select('clone_from')
# If using a volume group then set up to make snapshot cow clones
if vgname and not clone_from:
try:
kwargs['vgname'] = vgname
clone_from = _get_base(profile=profile, **kwargs)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = exc.strerror
if changes:
ret['changes'] = changes_dict
return ret
if not kwargs.get('snapshot') is False:
kwargs['snapshot'] = True
does_exist = exists(name, path=path)
to_reboot = False
remove_seed_marker = False
if does_exist:
pass
elif clone_from:
remove_seed_marker = True
try:
clone(name, clone_from, profile=profile, **kwargs)
changes.append({'create': 'Container cloned'})
except (SaltInvocationError, CommandExecutionError) as exc:
if 'already exists' in exc.strerror:
changes.append({'create': 'Container already exists'})
else:
ret['result'] = False
ret['comment'] = exc.strerror
if changes:
ret['changes'] = changes_dict
return ret
cfg = _LXCConfig(name=name, network_profile=network_profile,
nic_opts=nic_opts, bridge=bridge, path=path,
gateway=gateway, autostart=autostart,
cpuset=cpuset, cpushare=cpushare, memory=memory)
old_chunks = read_conf(cfg.path, out_format='commented')
cfg.write()
chunks = read_conf(cfg.path, out_format='commented')
if old_chunks != chunks:
to_reboot = True
else:
remove_seed_marker = True
cfg = _LXCConfig(network_profile=network_profile,
nic_opts=nic_opts, cpuset=cpuset, path=path,
bridge=bridge, gateway=gateway,
autostart=autostart,
cpushare=cpushare, memory=memory)
with cfg.tempfile() as cfile:
try:
create(name, config=cfile.name, profile=profile, **kwargs)
changes.append({'create': 'Container created'})
except (SaltInvocationError, CommandExecutionError) as exc:
if 'already exists' in exc.strerror:
changes.append({'create': 'Container already exists'})
else:
ret['comment'] = exc.strerror
if changes:
ret['changes'] = changes_dict
return ret
cpath = os.path.join(bpath, name, 'config')
old_chunks = []
if os.path.exists(cpath):
old_chunks = read_conf(cpath, out_format='commented')
new_cfg = _config_list(conf_tuples=old_chunks,
cpu=cpu,
network_profile=network_profile,
nic_opts=nic_opts, bridge=bridge,
cpuset=cpuset, cpushare=cpushare,
memory=memory)
if new_cfg:
edit_conf(cpath, out_format='commented', lxc_config=new_cfg)
chunks = read_conf(cpath, out_format='commented')
if old_chunks != chunks:
to_reboot = True
# last time to be sure any of our property is correctly applied
cfg = _LXCConfig(name=name, network_profile=network_profile,
nic_opts=nic_opts, bridge=bridge, path=path,
gateway=gateway, autostart=autostart,
cpuset=cpuset, cpushare=cpushare, memory=memory)
old_chunks = []
if os.path.exists(cfg.path):
old_chunks = read_conf(cfg.path, out_format='commented')
cfg.write()
chunks = read_conf(cfg.path, out_format='commented')
if old_chunks != chunks:
changes.append({'config': 'Container configuration updated'})
to_reboot = True
if to_reboot:
try:
stop(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
if changes:
ret['changes'] = changes_dict
return ret
if not does_exist or (does_exist and state(name, path=path) != 'running'):
try:
start(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
if changes:
ret['changes'] = changes_dict
return ret
if remove_seed_marker:
run(name,
'rm -f \'{0}\''.format(SEED_MARKER),
path=path,
chroot_fallback=False,
python_shell=False)
# set the default user/password, only the first time
if ret.get('result', True) and password:
gid = '/.lxc.initial_pass'
gids = [gid,
'/lxc.initial_pass',
'/.lxc.{0}.initial_pass'.format(name)]
if not any(retcode(name,
'test -e "{0}"'.format(x),
chroot_fallback=True,
path=path,
ignore_retcode=True) == 0
for x in gids):
# think to touch the default user generated by default templates
# which has a really unsecure passwords...
# root is defined as a member earlier in the code
for default_user in ['ubuntu']:
if (
default_user not in users and
retcode(name,
'id {0}'.format(default_user),
python_shell=False,
path=path,
chroot_fallback=True,
ignore_retcode=True) == 0
):
users.append(default_user)
for user in users:
try:
cret = set_password(name,
users=[user],
path=path,
password=password,
encrypted=password_encrypted)
except (SaltInvocationError, CommandExecutionError) as exc:
msg = '{0}: Failed to set password'.format(
user) + exc.strerror
# only hardfail in unrecoverable situation:
# root cannot be setted up
if user == 'root':
ret['comment'] = msg
ret['result'] = False
else:
log.debug(msg)
if ret.get('result', True):
changes.append({'password': 'Password(s) updated'})
if retcode(name,
('sh -c \'touch "{0}"; test -e "{0}"\''
.format(gid)),
path=path,
chroot_fallback=True,
ignore_retcode=True) != 0:
ret['comment'] = 'Failed to set password marker'
changes[-1]['password'] += '. ' + ret['comment'] + '.'
ret['result'] = False
# set dns servers if any, only the first time
if ret.get('result', True) and dnsservers:
# retro compatibility, test also old markers
gid = '/.lxc.initial_dns'
gids = [gid,
'/lxc.initial_dns',
'/lxc.{0}.initial_dns'.format(name)]
if not any(retcode(name,
'test -e "{0}"'.format(x),
chroot_fallback=True,
path=path,
ignore_retcode=True) == 0
for x in gids):
try:
set_dns(name,
path=path,
dnsservers=dnsservers,
searchdomains=searchdomains)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Failed to set DNS: ' + exc.strerror
ret['result'] = False
else:
changes.append({'dns': 'DNS updated'})
if retcode(name,
('sh -c \'touch "{0}"; test -e "{0}"\''
.format(gid)),
chroot_fallback=True,
path=path,
ignore_retcode=True) != 0:
ret['comment'] = 'Failed to set DNS marker'
changes[-1]['dns'] += '. ' + ret['comment'] + '.'
ret['result'] = False
# retro compatibility, test also old markers
if remove_seed_marker:
run(name,
'rm -f \'{0}\''.format(SEED_MARKER),
path=path,
python_shell=False)
gid = '/.lxc.initial_seed'
gids = [gid, '/lxc.initial_seed']
if (
any(retcode(name,
'test -e {0}'.format(x),
path=path,
chroot_fallback=True,
ignore_retcode=True) == 0
for x in gids) or not ret.get('result', True)
):
pass
elif seed or seed_cmd:
if seed:
try:
result = bootstrap(
name, config=salt_config, path=path,
approve_key=approve_key,
pub_key=pub_key, priv_key=priv_key,
install=install,
force_install=force_install,
unconditional_install=unconditional_install,
bootstrap_delay=bootstrap_delay,
bootstrap_url=bootstrap_url,
bootstrap_shell=bootstrap_shell,
bootstrap_args=bootstrap_args)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Bootstrap failed: ' + exc.strerror
ret['result'] = False
else:
if not result:
ret['comment'] = ('Bootstrap failed, see minion log for '
'more information')
ret['result'] = False
else:
changes.append(
{'bootstrap': 'Container successfully bootstrapped'}
)
elif seed_cmd:
try:
result = __salt__[seed_cmd](info(name, path=path)['rootfs'],
name,
salt_config)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = ('Bootstrap via seed_cmd \'{0}\' failed: {1}'
.format(seed_cmd, exc.strerror))
ret['result'] = False
else:
if not result:
ret['comment'] = ('Bootstrap via seed_cmd \'{0}\' failed, '
'see minion log for more information '
.format(seed_cmd))
ret['result'] = False
else:
changes.append(
{'bootstrap': 'Container successfully bootstrapped '
'using seed_cmd \'{0}\''
.format(seed_cmd)}
)
if ret.get('result', True) and not start_:
try:
stop(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
ret['result'] = False
state_post = state(name, path=path)
if state_pre != state_post:
changes.append({'state': {'old': state_pre, 'new': state_post}})
if ret.get('result', True):
ret['comment'] = ('Container \'{0}\' successfully initialized'
.format(name))
ret['result'] = True
if changes:
ret['changes'] = changes_dict
return ret
def cloud_init(name, vm_=None, **kwargs):
'''
Thin wrapper to lxc.init to be used from the saltcloud lxc driver
name
Name of the container
may be None and then guessed from saltcloud mapping
`vm_`
saltcloud mapping defaults for the vm
CLI Example:
.. code-block:: bash
salt '*' lxc.cloud_init foo
'''
init_interface = cloud_init_interface(name, vm_, **kwargs)
name = init_interface.pop('name', name)
return init(name, **init_interface)
def images(dist=None):
'''
.. versionadded:: 2015.5.0
List the available images for LXC's ``download`` template.
dist : None
Filter results to a single Linux distribution
CLI Examples:
.. code-block:: bash
salt myminion lxc.images
salt myminion lxc.images dist=centos
'''
out = __salt__['cmd.run_stdout'](
'lxc-create -n __imgcheck -t download -- --list',
ignore_retcode=True
)
if 'DIST' not in out:
raise CommandExecutionError(
'Unable to run the \'download\' template script. Is it installed?'
)
ret = {}
passed_header = False
for line in out.splitlines():
try:
distro, release, arch, variant, build_time = line.split()
except ValueError:
continue
if not passed_header:
if distro == 'DIST':
passed_header = True
continue
dist_list = ret.setdefault(distro, [])
dist_list.append({
'release': release,
'arch': arch,
'variant': variant,
'build_time': build_time,
})
if dist is not None:
return dict([(dist, ret.get(dist, []))])
return ret
def templates():
'''
.. versionadded:: 2015.5.0
List the available LXC template scripts installed on the minion
CLI Examples:
.. code-block:: bash
salt myminion lxc.templates
'''
try:
template_scripts = os.listdir('/usr/share/lxc/templates')
except OSError:
return []
else:
return [x[4:] for x in template_scripts if x.startswith('lxc-')]
def _after_ignition_network_profile(cmd,
ret,
name,
network_profile,
path,
nic_opts):
_clear_context()
if ret['retcode'] == 0 and exists(name, path=path):
if network_profile:
network_changes = apply_network_profile(name,
network_profile,
path=path,
nic_opts=nic_opts)
if network_changes:
log.info(
'Network changes from applying network profile \'%s\' '
'to newly-created container \'%s\':\n%s',
network_profile, name, network_changes
)
c_state = state(name, path=path)
return {'result': True,
'state': {'old': None, 'new': c_state}}
else:
if exists(name, path=path):
# destroy the container if it was partially created
cmd = 'lxc-destroy'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0}'.format(name)
__salt__['cmd.retcode'](cmd, python_shell=False)
raise CommandExecutionError(
'Container could not be created with cmd \'{0}\': {1}'
.format(cmd, ret['stderr'])
)
def create(name,
config=None,
profile=None,
network_profile=None,
nic_opts=None,
**kwargs):
'''
Create a new container.
name
Name of the container
config
The config file to use for the container. Defaults to system-wide
config (usually in /etc/lxc/lxc.conf).
profile
Profile to use in container creation (see
:mod:`lxc.get_container_profile
<salt.modules.lxc.get_container_profile>`). Values in a profile will be
overridden by the **Container Creation Arguments** listed below.
network_profile
Network profile to use for container
.. versionadded:: 2015.5.0
**Container Creation Arguments**
template
The template to use. For example, ``ubuntu`` or ``fedora``.
For a full list of available templates, check out
the :mod:`lxc.templates <salt.modules.lxc.templates>` function.
Conflicts with the ``image`` argument.
.. note::
The ``download`` template requires the following three parameters
to be defined in ``options``:
* **dist** - The name of the distribution
* **release** - Release name/version
* **arch** - Architecture of the container
The available images can be listed using the :mod:`lxc.images
<salt.modules.lxc.images>` function.
options
Template-specific options to pass to the lxc-create command. These
correspond to the long options (ones beginning with two dashes) that
the template script accepts. For example:
.. code-block:: bash
options='{"dist": "centos", "release": "6", "arch": "amd64"}'
For available template options, refer to the lxc template scripts
which are ususally located under ``/usr/share/lxc/templates``,
or run ``lxc-create -t <template> -h``.
image
A tar archive to use as the rootfs for the container. Conflicts with
the ``template`` argument.
backing
The type of storage to use. Set to ``lvm`` to use an LVM group.
Defaults to filesystem within /var/lib/lxc.
fstype
Filesystem type to use on LVM logical volume
size : 1G
Size of the volume to create. Only applicable if ``backing=lvm``.
vgname : lxc
Name of the LVM volume group in which to create the volume for this
container. Only applicable if ``backing=lvm``.
lvname
Name of the LVM logical volume in which to create the volume for this
container. Only applicable if ``backing=lvm``.
thinpool
Name of a pool volume that will be used for thin-provisioning this
container. Only applicable if ``backing=lvm``.
nic_opts
give extra opts overriding network profile values
path
parent path for the container creation (default: /var/lib/lxc)
zfsroot
Name of the ZFS root in which to create the volume for this container.
Only applicable if ``backing=zfs``. (default: tank/lxc)
.. versionadded:: 2015.8.0
'''
# Required params for 'download' template
download_template_deps = ('dist', 'release', 'arch')
cmd = 'lxc-create -n {0}'.format(name)
profile = get_container_profile(copy.deepcopy(profile))
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, None)
profile_match = profile.pop(key, default)
# Return the profile match if the the kwarg match was None, as the
# lxc.present state will pass these kwargs set to None by default.
if kw_overrides_match is None:
return profile_match
return kw_overrides_match
path = select('path')
if exists(name, path=path):
raise CommandExecutionError(
'Container \'{0}\' already exists'.format(name)
)
tvg = select('vgname')
vgname = tvg if tvg else __salt__['config.get']('lxc.vgname')
# The 'template' and 'image' params conflict
template = select('template')
image = select('image')
if template and image:
raise SaltInvocationError(
'Only one of \'template\' and \'image\' is permitted'
)
elif not any((template, image, profile)):
raise SaltInvocationError(
'At least one of \'template\', \'image\', and \'profile\' is '
'required'
)
options = select('options') or {}
backing = select('backing')
if vgname and not backing:
backing = 'lvm'
lvname = select('lvname')
thinpool = select('thinpool')
fstype = select('fstype')
size = select('size', '1G')
zfsroot = select('zfsroot')
if backing in ('dir', 'overlayfs', 'btrfs', 'zfs'):
fstype = None
size = None
# some backends won't support some parameters
if backing in ('aufs', 'dir', 'overlayfs', 'btrfs'):
lvname = vgname = thinpool = None
if image:
img_tar = __salt__['cp.cache_file'](image)
template = os.path.join(
os.path.dirname(salt.__file__),
'templates',
'lxc',
'salt_tarball')
options['imgtar'] = img_tar
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
if not os.path.exists(path):
os.makedirs(path)
if config:
cmd += ' -f {0}'.format(config)
if template:
cmd += ' -t {0}'.format(template)
if backing:
backing = backing.lower()
cmd += ' -B {0}'.format(backing)
if backing in ('zfs',):
if zfsroot:
cmd += ' --zfsroot {0}'.format(zfsroot)
if backing in ('lvm',):
if lvname:
cmd += ' --lvname {0}'.format(lvname)
if vgname:
cmd += ' --vgname {0}'.format(vgname)
if thinpool:
cmd += ' --thinpool {0}'.format(thinpool)
if backing not in ('dir', 'overlayfs'):
if fstype:
cmd += ' --fstype {0}'.format(fstype)
if size:
cmd += ' --fssize {0}'.format(size)
if options:
if template == 'download':
missing_deps = [x for x in download_template_deps
if x not in options]
if missing_deps:
raise SaltInvocationError(
'Missing params in \'options\' dict: {0}'
.format(', '.join(missing_deps))
)
cmd += ' --'
for key, val in six.iteritems(options):
cmd += ' --{0} {1}'.format(key, val)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
# please do not merge extra conflicting stuff
# inside those two line (ret =, return)
return _after_ignition_network_profile(cmd,
ret,
name,
network_profile,
path,
nic_opts)
def clone(name,
orig,
profile=None,
network_profile=None,
nic_opts=None,
**kwargs):
'''
Create a new container as a clone of another container
name
Name of the container
orig
Name of the original container to be cloned
profile
Profile to use in container cloning (see
:mod:`lxc.get_container_profile
<salt.modules.lxc.get_container_profile>`). Values in a profile will be
overridden by the **Container Cloning Arguments** listed below.
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
**Container Cloning Arguments**
snapshot
Use Copy On Write snapshots (LVM)
size : 1G
Size of the volume to create. Only applicable if ``backing=lvm``.
backing
The type of storage to use. Set to ``lvm`` to use an LVM group.
Defaults to filesystem within /var/lib/lxc.
network_profile
Network profile to use for container
.. versionadded:: 2015.8.0
nic_opts
give extra opts overriding network profile values
.. versionadded:: 2015.8.0
CLI Examples:
.. code-block:: bash
salt '*' lxc.clone myclone orig=orig_container
salt '*' lxc.clone myclone orig=orig_container snapshot=True
'''
profile = get_container_profile(copy.deepcopy(profile))
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, None)
profile_match = profile.pop(key, default)
# let kwarg overrides be the preferred choice
if kw_overrides_match is None:
return profile_match
return kw_overrides_match
path = select('path')
if exists(name, path=path):
raise CommandExecutionError(
'Container \'{0}\' already exists'.format(name)
)
_ensure_exists(orig, path=path)
if state(orig, path=path) != 'stopped':
raise CommandExecutionError(
'Container \'{0}\' must be stopped to be cloned'.format(orig)
)
backing = select('backing')
snapshot = select('snapshot')
if backing in ('dir',):
snapshot = False
if not snapshot:
snapshot = ''
else:
snapshot = '-s'
size = select('size', '1G')
if backing in ('dir', 'overlayfs', 'btrfs'):
size = None
# LXC commands and options changed in 2.0 - CF issue #34086 for details
if _LooseVersion(version()) >= _LooseVersion('2.0'):
# https://linuxcontainers.org/lxc/manpages//man1/lxc-copy.1.html
cmd = 'lxc-copy'
cmd += ' {0} -n {1} -N {2}'.format(snapshot, orig, name)
else:
# https://linuxcontainers.org/lxc/manpages//man1/lxc-clone.1.html
cmd = 'lxc-clone'
cmd += ' {0} -o {1} -n {2}'.format(snapshot, orig, name)
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
if not os.path.exists(path):
os.makedirs(path)
if backing:
backing = backing.lower()
cmd += ' -B {0}'.format(backing)
if backing not in ('dir', 'overlayfs'):
if size:
cmd += ' -L {0}'.format(size)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
# please do not merge extra conflicting stuff
# inside those two line (ret =, return)
return _after_ignition_network_profile(cmd,
ret,
name,
network_profile,
path,
nic_opts)
def ls_(active=None, cache=True, path=None):
'''
Return a list of the containers available on the minion
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
active
If ``True``, return only active (i.e. running) containers
.. versionadded:: 2015.5.0
CLI Example:
.. code-block:: bash
salt '*' lxc.ls
salt '*' lxc.ls active=True
'''
contextvar = 'lxc.ls{0}'.format(path)
if active:
contextvar += '.active'
if cache and (contextvar in __context__):
return __context__[contextvar]
else:
ret = []
cmd = 'lxc-ls'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
if active:
cmd += ' --active'
output = __salt__['cmd.run_stdout'](cmd, python_shell=False)
for line in output.splitlines():
ret.extend(line.split())
__context__[contextvar] = ret
return ret
def list_(extra=False, limit=None, path=None):
'''
List containers classified by state
extra
Also get per-container specific info. This will change the return data.
Instead of returning a list of containers, a dictionary of containers
and each container's output from :mod:`lxc.info
<salt.modules.lxc.info>`.
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
limit
Return output matching a specific state (**frozen**, **running**, or
**stopped**).
.. versionadded:: 2015.5.0
CLI Examples:
.. code-block:: bash
salt '*' lxc.list
salt '*' lxc.list extra=True
salt '*' lxc.list limit=running
'''
ctnrs = ls_(path=path)
if extra:
stopped = {}
frozen = {}
running = {}
else:
stopped = []
frozen = []
running = []
ret = {'running': running,
'stopped': stopped,
'frozen': frozen}
for container in ctnrs:
cmd = 'lxc-info'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0}'.format(container)
c_info = __salt__['cmd.run'](
cmd,
python_shell=False,
output_loglevel='debug'
)
c_state = None
for line in c_info.splitlines():
stat = line.split(':')
if stat[0] in ('State', 'state'):
c_state = stat[1].strip()
break
if not c_state or (limit is not None and c_state.lower() != limit):
continue
if extra:
infos = info(container, path=path)
method = 'update'
value = {container: infos}
else:
method = 'append'
value = container
if c_state == 'STOPPED':
getattr(stopped, method)(value)
continue
if c_state == 'FROZEN':
getattr(frozen, method)(value)
continue
if c_state == 'RUNNING':
getattr(running, method)(value)
continue
if limit is not None:
return ret.get(limit, {} if extra else [])
return ret
def _change_state(cmd,
name,
expected,
stdin=_marker,
stdout=_marker,
stderr=_marker,
with_communicate=_marker,
use_vt=_marker,
path=None):
pre = state(name, path=path)
if pre == expected:
return {'result': True,
'state': {'old': expected, 'new': expected},
'comment': 'Container \'{0}\' already {1}'
.format(name, expected)}
if cmd == 'lxc-destroy':
# Kill the container first
scmd = 'lxc-stop'
if path:
scmd += ' -P {0}'.format(pipes.quote(path))
scmd += ' -k -n {0}'.format(name)
__salt__['cmd.run'](scmd,
python_shell=False)
if path and ' -P ' not in cmd:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0}'.format(name)
# certain lxc commands need to be taken with care (lxc-start)
# as te command itself mess with double forks; we must not
# communicate with it, but just wait for the exit status
pkwargs = {'python_shell': False,
'redirect_stderr': True,
'with_communicate': with_communicate,
'use_vt': use_vt,
'stdin': stdin,
'stdout': stdout}
for i in [a for a in pkwargs]:
val = pkwargs[i]
if val is _marker:
pkwargs.pop(i, None)
_cmdout = __salt__['cmd.run_all'](cmd, **pkwargs)
if _cmdout['retcode'] != 0:
raise CommandExecutionError(
'Error changing state for container \'{0}\' using command '
'\'{1}\': {2}'.format(name, cmd, _cmdout['stdout'])
)
if expected is not None:
# some commands do not wait, so we will
rcmd = 'lxc-wait'
if path:
rcmd += ' -P {0}'.format(pipes.quote(path))
rcmd += ' -n {0} -s {1}'.format(name, expected.upper())
__salt__['cmd.run'](rcmd, python_shell=False, timeout=30)
_clear_context()
post = state(name, path=path)
ret = {'result': post == expected,
'state': {'old': pre, 'new': post}}
return ret
def _ensure_exists(name, path=None):
'''
Raise an exception if the container does not exist
'''
if not exists(name, path=path):
raise CommandExecutionError(
'Container \'{0}\' does not exist'.format(name)
)
def restart(name, path=None, lxc_config=None, force=False):
'''
.. versionadded:: 2015.5.0
Restart the named container. If the container was not running, the
container will merely be started.
name
The name of the container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
lxc_config
path to a lxc config file
config file will be guessed from container name otherwise
.. versionadded:: 2015.8.0
force : False
If ``True``, the container will be force-stopped instead of gracefully
shut down
CLI Example:
.. code-block:: bash
salt myminion lxc.restart name
'''
_ensure_exists(name, path=path)
orig_state = state(name, path=path)
if orig_state != 'stopped':
stop(name, kill=force, path=path)
ret = start(name, path=path, lxc_config=lxc_config)
ret['state']['old'] = orig_state
if orig_state != 'stopped':
ret['restarted'] = True
return ret
def start(name, **kwargs):
'''
Start the named container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
lxc_config
path to a lxc config file
config file will be guessed from container name otherwise
.. versionadded:: 2015.8.0
use_vt
run the command through VT
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.start name
'''
path = kwargs.get('path', None)
cpath = get_root_path(path)
lxc_config = kwargs.get('lxc_config', None)
cmd = 'lxc-start'
if not lxc_config:
lxc_config = os.path.join(cpath, name, 'config')
# we try to start, even without config, if global opts are there
if os.path.exists(lxc_config):
cmd += ' -f {0}'.format(pipes.quote(lxc_config))
cmd += ' -d'
_ensure_exists(name, path=path)
if state(name, path=path) == 'frozen':
raise CommandExecutionError(
'Container \'{0}\' is frozen, use lxc.unfreeze'.format(name)
)
# lxc-start daemonize itself violently, we must not communicate with it
use_vt = kwargs.get('use_vt', None)
with_communicate = kwargs.get('with_communicate', False)
return _change_state(cmd, name, 'running',
stdout=None,
stderr=None,
stdin=None,
with_communicate=with_communicate,
path=path,
use_vt=use_vt)
def stop(name, kill=False, path=None, use_vt=None):
'''
Stop the named container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
kill: False
Do not wait for the container to stop, kill all tasks in the container.
Older LXC versions will stop containers like this irrespective of this
argument.
.. versionchanged:: 2015.5.0
Default value changed to ``False``
use_vt
run the command through VT
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.stop name
'''
_ensure_exists(name, path=path)
orig_state = state(name, path=path)
if orig_state == 'frozen' and not kill:
# Gracefully stopping a frozen container is slower than unfreezing and
# then stopping it (at least in my testing), so if we're not
# force-stopping the container, unfreeze it first.
unfreeze(name, path=path)
cmd = 'lxc-stop'
if kill:
cmd += ' -k'
ret = _change_state(cmd, name, 'stopped', use_vt=use_vt, path=path)
ret['state']['old'] = orig_state
return ret
def freeze(name, **kwargs):
'''
Freeze the named container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
start : False
If ``True`` and the container is stopped, the container will be started
before attempting to freeze.
.. versionadded:: 2015.5.0
use_vt
run the command through VT
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.freeze name
'''
use_vt = kwargs.get('use_vt', None)
path = kwargs.get('path', None)
_ensure_exists(name, path=path)
orig_state = state(name, path=path)
start_ = kwargs.get('start', False)
if orig_state == 'stopped':
if not start_:
raise CommandExecutionError(
'Container \'{0}\' is stopped'.format(name)
)
start(name, path=path)
cmd = 'lxc-freeze'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
ret = _change_state(cmd, name, 'frozen', use_vt=use_vt, path=path)
if orig_state == 'stopped' and start_:
ret['state']['old'] = orig_state
ret['started'] = True
ret['state']['new'] = state(name, path=path)
return ret
def unfreeze(name, path=None, use_vt=None):
'''
Unfreeze the named container.
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
use_vt
run the command through VT
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.unfreeze name
'''
_ensure_exists(name, path=path)
if state(name, path=path) == 'stopped':
raise CommandExecutionError(
'Container \'{0}\' is stopped'.format(name)
)
cmd = 'lxc-unfreeze'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
return _change_state(cmd, name, 'running', path=path, use_vt=use_vt)
def destroy(name, stop=False, path=None):
'''
Destroy the named container.
.. warning::
Destroys all data associated with the container.
path
path to the container parent directory (default: /var/lib/lxc)
.. versionadded:: 2015.8.0
stop : False
If ``True``, the container will be destroyed even if it is
running/frozen.
.. versionchanged:: 2015.5.0
Default value changed to ``False``. This more closely matches the
behavior of ``lxc-destroy(1)``, and also makes it less likely that
an accidental command will destroy a running container that was
being used for important things.
CLI Examples:
.. code-block:: bash
salt '*' lxc.destroy foo
salt '*' lxc.destroy foo stop=True
'''
_ensure_exists(name, path=path)
if not stop and state(name, path=path) != 'stopped':
raise CommandExecutionError(
'Container \'{0}\' is not stopped'.format(name)
)
return _change_state('lxc-destroy', name, None, path=path)
# Compatibility between LXC and nspawn
remove = salt.utils.functools.alias_function(destroy, 'remove')
def exists(name, path=None):
'''
Returns whether the named container exists.
path
path to the container parent directory (default: /var/lib/lxc)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.exists name
'''
_exists = name in ls_(path=path)
# container may be just created but we did cached earlier the
# lxc-ls results
if not _exists:
_exists = name in ls_(cache=False, path=path)
return _exists
def state(name, path=None):
'''
Returns the state of a container.
path
path to the container parent directory (default: /var/lib/lxc)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.state name
'''
# Don't use _ensure_exists() here, it will mess with _change_state()
cachekey = 'lxc.state.{0}{1}'.format(name, path)
try:
return __context__[cachekey]
except KeyError:
if not exists(name, path=path):
__context__[cachekey] = None
else:
cmd = 'lxc-info'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0}'.format(name)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
if ret['retcode'] != 0:
_clear_context()
raise CommandExecutionError(
'Unable to get state of container \'{0}\''.format(name)
)
c_infos = ret['stdout'].splitlines()
c_state = None
for c_info in c_infos:
stat = c_info.split(':')
if stat[0].lower() == 'state':
c_state = stat[1].strip().lower()
break
__context__[cachekey] = c_state
return __context__[cachekey]
def get_parameter(name, parameter, path=None):
'''
Returns the value of a cgroup parameter for a container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.get_parameter container_name memory.limit_in_bytes
'''
_ensure_exists(name, path=path)
cmd = 'lxc-cgroup'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0} {1}'.format(name, parameter)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
if ret['retcode'] != 0:
raise CommandExecutionError(
'Unable to retrieve value for \'{0}\''.format(parameter)
)
return ret['stdout'].strip()
def set_parameter(name, parameter, value, path=None):
'''
Set the value of a cgroup parameter for a container.
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.set_parameter name parameter value
'''
if not exists(name, path=path):
return None
cmd = 'lxc-cgroup'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0} {1} {2}'.format(name, parameter, value)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
if ret['retcode'] != 0:
return False
else:
return True
def info(name, path=None):
'''
Returns information about a container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.info name
'''
cachekey = 'lxc.info.{0}{1}'.format(name, path)
try:
return __context__[cachekey]
except KeyError:
_ensure_exists(name, path=path)
cpath = get_root_path(path)
try:
conf_file = os.path.join(cpath, name, 'config')
except AttributeError:
conf_file = os.path.join(cpath, six.text_type(name), 'config')
if not os.path.isfile(conf_file):
raise CommandExecutionError(
'LXC config file {0} does not exist'.format(conf_file)
)
ret = {}
config = []
with salt.utils.files.fopen(conf_file) as fp_:
for line in fp_:
line = salt.utils.stringutils.to_unicode(line)
comps = [x.strip() for x in
line.split('#', 1)[0].strip().split('=', 1)]
if len(comps) == 2:
config.append(tuple(comps))
ifaces = []
current = None
for key, val in config:
if key == 'lxc.network.type':
current = {'type': val}
ifaces.append(current)
elif not current:
continue
elif key.startswith('lxc.network.'):
current[key.replace('lxc.network.', '', 1)] = val
if ifaces:
ret['nics'] = ifaces
ret['rootfs'] = next(
(x[1] for x in config if x[0] == 'lxc.rootfs'),
None
)
ret['state'] = state(name, path=path)
ret['ips'] = []
ret['public_ips'] = []
ret['private_ips'] = []
ret['public_ipv4_ips'] = []
ret['public_ipv6_ips'] = []
ret['private_ipv4_ips'] = []
ret['private_ipv6_ips'] = []
ret['ipv4_ips'] = []
ret['ipv6_ips'] = []
ret['size'] = None
ret['config'] = conf_file
if ret['state'] == 'running':
try:
limit = int(get_parameter(name, 'memory.limit_in_bytes'))
except (CommandExecutionError, TypeError, ValueError):
limit = 0
try:
usage = int(get_parameter(name, 'memory.usage_in_bytes'))
except (CommandExecutionError, TypeError, ValueError):
usage = 0
free = limit - usage
ret['memory_limit'] = limit
ret['memory_free'] = free
size = run_stdout(name, 'df /', path=path, python_shell=False)
# The size is the 2nd column of the last line
ret['size'] = size.splitlines()[-1].split()[1]
# First try iproute2
ip_cmd = run_all(
name, 'ip link show', path=path, python_shell=False)
if ip_cmd['retcode'] == 0:
ip_data = ip_cmd['stdout']
ip_cmd = run_all(
name, 'ip addr show', path=path, python_shell=False)
ip_data += '\n' + ip_cmd['stdout']
ip_data = salt.utils.network._interfaces_ip(ip_data)
else:
# That didn't work, try ifconfig
ip_cmd = run_all(
name, 'ifconfig', path=path, python_shell=False)
if ip_cmd['retcode'] == 0:
ip_data = \
salt.utils.network._interfaces_ifconfig(
ip_cmd['stdout'])
else:
# Neither was successful, give up
log.warning(
'Unable to run ip or ifconfig in container \'%s\'', name
)
ip_data = {}
ret['ipv4_ips'] = salt.utils.network.ip_addrs(
include_loopback=True,
interface_data=ip_data
)
ret['ipv6_ips'] = salt.utils.network.ip_addrs6(
include_loopback=True,
interface_data=ip_data
)
ret['ips'] = ret['ipv4_ips'] + ret['ipv6_ips']
for address in ret['ipv4_ips']:
if address == '127.0.0.1':
ret['private_ips'].append(address)
ret['private_ipv4_ips'].append(address)
elif salt.utils.cloud.is_public_ip(address):
ret['public_ips'].append(address)
ret['public_ipv4_ips'].append(address)
else:
ret['private_ips'].append(address)
ret['private_ipv4_ips'].append(address)
for address in ret['ipv6_ips']:
if address == '::1' or address.startswith('fe80'):
ret['private_ips'].append(address)
ret['private_ipv6_ips'].append(address)
else:
ret['public_ips'].append(address)
ret['public_ipv6_ips'].append(address)
for key in [x for x in ret if x == 'ips' or x.endswith('ips')]:
ret[key].sort(key=_ip_sort)
__context__[cachekey] = ret
return __context__[cachekey]
def set_password(name, users, password, encrypted=True, path=None):
'''
.. versionchanged:: 2015.5.0
Function renamed from ``set_pass`` to ``set_password``. Additionally,
this function now supports (and defaults to using) a password hash
instead of a plaintext password.
Set the password of one or more system users inside containers
users
Comma-separated list (or python list) of users to change password
password
Password to set for the specified user(s)
encrypted : True
If true, ``password`` must be a password hash. Set to ``False`` to set
a plaintext password (not recommended).
.. versionadded:: 2015.5.0
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.set_pass container-name root '$6$uJ2uAyLU$KoI67t8As/0fXtJOPcHKGXmUpcoYUcVR2K6x93walnShTCQvjRwq25yIkiCBOqgbfdKQSFnAo28/ek6716vEV1'
salt '*' lxc.set_pass container-name root foo encrypted=False
'''
def _bad_user_input():
raise SaltInvocationError('Invalid input for \'users\' parameter')
if not isinstance(users, list):
try:
users = users.split(',')
except AttributeError:
_bad_user_input()
if not users:
_bad_user_input()
failed_users = []
for user in users:
result = retcode(name,
'chpasswd{0}'.format(' -e' if encrypted else ''),
stdin=':'.join((user, password)),
python_shell=False,
path=path,
chroot_fallback=True,
output_loglevel='quiet')
if result != 0:
failed_users.append(user)
if failed_users:
raise CommandExecutionError(
'Password change failed for the following user(s): {0}'
.format(', '.join(failed_users))
)
return True
set_pass = salt.utils.functools.alias_function(set_password, 'set_pass')
def update_lxc_conf(name, lxc_conf, lxc_conf_unset, path=None):
'''
Edit LXC configuration options
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.update_lxc_conf ubuntu \\
lxc_conf="[{'network.ipv4.ip':'10.0.3.5'}]" \\
lxc_conf_unset="['lxc.utsname']"
'''
_ensure_exists(name, path=path)
cpath = get_root_path(path)
lxc_conf_p = os.path.join(cpath, name, 'config')
if not os.path.exists(lxc_conf_p):
raise SaltInvocationError(
'Configuration file {0} does not exist'.format(lxc_conf_p)
)
changes = {'edited': [], 'added': [], 'removed': []}
ret = {'changes': changes, 'result': True, 'comment': ''}
# do not use salt.utils.files.fopen !
with salt.utils.files.fopen(lxc_conf_p, 'r') as fic:
filtered_lxc_conf = []
for row in lxc_conf:
if not row:
continue
for conf in row:
filtered_lxc_conf.append((conf.strip(),
row[conf].strip()))
ret['comment'] = 'lxc.conf is up to date'
lines = []
orig_config = salt.utils.stringutils.to_unicode(fic.read())
for line in orig_config.splitlines():
if line.startswith('#') or not line.strip():
lines.append([line, ''])
else:
line = line.split('=')
index = line.pop(0)
val = (index.strip(), '='.join(line).strip())
if val not in lines:
lines.append(val)
for key, item in filtered_lxc_conf:
matched = False
for idx, line in enumerate(lines[:]):
if line[0] == key:
matched = True
lines[idx] = (key, item)
if '='.join(line[1:]).strip() != item.strip():
changes['edited'].append(
({line[0]: line[1:]}, {key: item}))
break
if not matched:
if (key, item) not in lines:
lines.append((key, item))
changes['added'].append({key: item})
dest_lxc_conf = []
# filter unset
if lxc_conf_unset:
for line in lines:
for opt in lxc_conf_unset:
if (
not line[0].startswith(opt) and
line not in dest_lxc_conf
):
dest_lxc_conf.append(line)
else:
changes['removed'].append(opt)
else:
dest_lxc_conf = lines
conf = ''
for key, val in dest_lxc_conf:
if not val:
conf += '{0}\n'.format(key)
else:
conf += '{0} = {1}\n'.format(key.strip(), val.strip())
conf_changed = conf != orig_config
chrono = datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S')
if conf_changed:
# DO NOT USE salt.utils.files.fopen here, i got (kiorky)
# problems with lxc configs which were wiped !
with salt.utils.files.fopen('{0}.{1}'.format(lxc_conf_p, chrono), 'w') as wfic:
wfic.write(salt.utils.stringutils.to_str(conf))
with salt.utils.files.fopen(lxc_conf_p, 'w') as wfic:
wfic.write(salt.utils.stringutils.to_str(conf))
ret['comment'] = 'Updated'
ret['result'] = True
if not any(changes[x] for x in changes):
# Ensure an empty changes dict if nothing was modified
ret['changes'] = {}
return ret
def set_dns(name, dnsservers=None, searchdomains=None, path=None):
'''
.. versionchanged:: 2015.5.0
The ``dnsservers`` and ``searchdomains`` parameters can now be passed
as a comma-separated list.
Update /etc/resolv.confo
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.set_dns ubuntu "['8.8.8.8', '4.4.4.4']"
'''
if dnsservers is None:
dnsservers = ['8.8.8.8', '4.4.4.4']
elif not isinstance(dnsservers, list):
try:
dnsservers = dnsservers.split(',')
except AttributeError:
raise SaltInvocationError(
'Invalid input for \'dnsservers\' parameter'
)
if searchdomains is None:
searchdomains = []
elif not isinstance(searchdomains, list):
try:
searchdomains = searchdomains.split(',')
except AttributeError:
raise SaltInvocationError(
'Invalid input for \'searchdomains\' parameter'
)
dns = ['nameserver {0}'.format(x) for x in dnsservers]
dns.extend(['search {0}'.format(x) for x in searchdomains])
dns = '\n'.join(dns) + '\n'
# we may be using resolvconf in the container
# We need to handle that case with care:
# - we create the resolv.conf runtime directory (the
# linked directory) as anyway it will be shadowed when the real
# runned tmpfs mountpoint will be mounted.
# ( /etc/resolv.conf -> ../run/resolvconf/resolv.conf)
# Indeed, it can save us in any other case (running, eg, in a
# bare chroot when repairing or preparing the container for
# operation.
# - We also teach resolvconf to use the aforementioned dns.
# - We finally also set /etc/resolv.conf in all cases
rstr = __salt__['test.random_hash']()
# no tmp here, apparmor won't let us execute !
script = '/sbin/{0}_dns.sh'.format(rstr)
DNS_SCRIPT = "\n".join([
# 'set -x',
'#!/usr/bin/env bash',
'if [ -h /etc/resolv.conf ];then',
' if [ "x$(readlink /etc/resolv.conf)"'
' = "x../run/resolvconf/resolv.conf" ];then',
' if [ ! -d /run/resolvconf/ ];then',
' mkdir -p /run/resolvconf',
' fi',
' cat > /etc/resolvconf/resolv.conf.d/head <<EOF',
dns,
'EOF',
'',
' fi',
'fi',
'cat > /etc/resolv.conf <<EOF',
dns,
'EOF',
''])
result = run_all(
name, 'tee {0}'.format(script), path=path,
stdin=DNS_SCRIPT, python_shell=True)
if result['retcode'] == 0:
result = run_all(
name, 'sh -c "chmod +x {0};{0}"'.format(script),
path=path, python_shell=True)
# blindly delete the setter file
run_all(name,
'sh -c \'if [ -f "{0}" ];then rm -f "{0}";fi\''.format(script),
path=path, python_shell=True)
if result['retcode'] != 0:
error = ('Unable to write to /etc/resolv.conf in container \'{0}\''
.format(name))
if result['stderr']:
error += ': {0}'.format(result['stderr'])
raise CommandExecutionError(error)
return True
def running_systemd(name, cache=True, path=None):
'''
Determine if systemD is running
path
path to the container parent
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.running_systemd ubuntu
'''
k = 'lxc.systemd.test.{0}{1}'.format(name, path)
ret = __context__.get(k, None)
if ret is None or not cache:
rstr = __salt__['test.random_hash']()
# no tmp here, apparmor won't let us execute !
script = '/sbin/{0}_testsystemd.sh'.format(rstr)
# ubuntu already had since trusty some bits of systemd but was
# still using upstart ...
# we need to be a bit more careful that just testing that systemd
# is present
_script = textwrap.dedent(
'''\
#!/usr/bin/env bash
set -x
if ! command -v systemctl 1>/dev/null 2>/dev/null;then exit 2;fi
for i in \\
/run/systemd/journal/dev-log\\
/run/systemd/journal/flushed\\
/run/systemd/journal/kernel-seqnum\\
/run/systemd/journal/socket\\
/run/systemd/journal/stdout\\
/var/run/systemd/journal/dev-log\\
/var/run/systemd/journal/flushed\\
/var/run/systemd/journal/kernel-seqnum\\
/var/run/systemd/journal/socket\\
/var/run/systemd/journal/stdout\\
;do\\
if test -e ${i};then exit 0;fi
done
if test -d /var/systemd/system;then exit 0;fi
exit 2
''')
result = run_all(
name, 'tee {0}'.format(script), path=path,
stdin=_script, python_shell=True)
if result['retcode'] == 0:
result = run_all(name,
'sh -c "chmod +x {0};{0}"'''.format(script),
path=path,
python_shell=True)
else:
raise CommandExecutionError(
'lxc {0} failed to copy initd tester'.format(name))
run_all(name,
'sh -c \'if [ -f "{0}" ];then rm -f "{0}";fi\''
''.format(script),
path=path,
ignore_retcode=True,
python_shell=True)
if result['retcode'] != 0:
error = ('Unable to determine if the container \'{0}\''
' was running systemd, assmuming it is not.'
''.format(name))
if result['stderr']:
error += ': {0}'.format(result['stderr'])
# only cache result if we got a known exit code
if result['retcode'] in (0, 2):
__context__[k] = ret = not result['retcode']
return ret
def systemd_running_state(name, path=None):
'''
Get the operational state of a systemd based container
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.systemd_running_state ubuntu
'''
try:
ret = run_all(name,
'systemctl is-system-running',
path=path,
ignore_retcode=True)['stdout']
except CommandExecutionError:
ret = ''
return ret
def test_sd_started_state(name, path=None):
'''
Test if a systemd container is fully started
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.test_sd_started_state ubuntu
'''
qstate = systemd_running_state(name, path=path)
if qstate in ('initializing', 'starting'):
return False
elif qstate == '':
return None
else:
return True
def test_bare_started_state(name, path=None):
'''
Test if a non systemd container is fully started
For now, it consists only to test if the container is attachable
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.test_bare_started_state ubuntu
'''
try:
ret = run_all(
name, 'ls', path=path, ignore_retcode=True
)['retcode'] == 0
except (CommandExecutionError,):
ret = None
return ret
def wait_started(name, path=None, timeout=300):
'''
Check that the system has fully inited
This is actually very important for systemD based containers
see https://github.com/saltstack/salt/issues/23847
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.wait_started ubuntu
'''
if not exists(name, path=path):
raise CommandExecutionError(
'Container {0} does does exists'.format(name))
if not state(name, path=path) == 'running':
raise CommandExecutionError(
'Container {0} is not running'.format(name))
ret = False
if running_systemd(name, path=path):
test_started = test_sd_started_state
logger = log.error
else:
test_started = test_bare_started_state
logger = log.debug
now = time.time()
expire = now + timeout
now = time.time()
started = test_started(name, path=path)
while time.time() < expire and not started:
time.sleep(0.3)
started = test_started(name, path=path)
if started is None:
logger(
'Assuming %s is started, although we failed to detect that'
' is fully started correctly', name)
ret = True
else:
ret = started
return ret
def _needs_install(name, path=None):
ret = 0
has_minion = retcode(name,
'which salt-minion',
path=path,
ignore_retcode=True)
# we assume that installing is when no minion is running
# but testing the executable presence is not enougth for custom
# installs where the bootstrap can do much more than installing
# the bare salt binaries.
if has_minion:
processes = run_stdout(name, "ps aux", path=path)
if 'salt-minion' not in processes:
ret = 1
else:
retcode(name, 'salt-call --local service.stop salt-minion')
else:
ret = 1
return ret
def bootstrap(name,
config=None,
approve_key=True,
install=True,
pub_key=None,
priv_key=None,
bootstrap_url=None,
force_install=False,
unconditional_install=False,
path=None,
bootstrap_delay=None,
bootstrap_args=None,
bootstrap_shell=None):
'''
Install and configure salt in a container.
config
Minion configuration options. By default, the ``master`` option is set
to the target host's master.
approve_key
Request a pre-approval of the generated minion key. Requires
that the salt-master be configured to either auto-accept all keys or
expect a signing request from the target host. Default: ``True``
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
pub_key
Explicit public key to pressed the minion with (optional).
This can be either a filepath or a string representing the key
priv_key
Explicit private key to pressed the minion with (optional).
This can be either a filepath or a string representing the key
bootstrap_delay
Delay in seconds between end of container creation and bootstrapping.
Useful when waiting for container to obtain a DHCP lease.
.. versionadded:: 2015.5.0
bootstrap_url
url, content or filepath to the salt bootstrap script
bootstrap_args
salt bootstrap script arguments
bootstrap_shell
shell to execute the script into
install
Whether to attempt a full installation of salt-minion if needed.
force_install
Force installation even if salt-minion is detected,
this is the way to run vendor bootstrap scripts even
if a salt minion is already present in the container
unconditional_install
Run the script even if the container seems seeded
CLI Examples:
.. code-block:: bash
salt 'minion' lxc.bootstrap container_name [config=config_data] \\
[approve_key=(True|False)] [install=(True|False)]
'''
wait_started(name, path=path)
if bootstrap_delay is not None:
try:
log.info('LXC %s: bootstrap_delay: %s', name, bootstrap_delay)
time.sleep(bootstrap_delay)
except TypeError:
# Bad input, but assume since a value was passed that
# a delay was desired, and sleep for 5 seconds
time.sleep(5)
c_info = info(name, path=path)
if not c_info:
return None
# default set here as we cannot set them
# in def as it can come from a chain of procedures.
if bootstrap_args:
# custom bootstrap args can be totally customized, and user could
# have inserted the placeholder for the config directory.
# For example, some salt bootstrap script do not use at all -c
if '{0}' not in bootstrap_args:
bootstrap_args += ' -c {0}'
else:
bootstrap_args = '-c {0}'
if not bootstrap_shell:
bootstrap_shell = 'sh'
orig_state = _ensure_running(name, path=path)
if not orig_state:
return orig_state
if not force_install:
needs_install = _needs_install(name, path=path)
else:
needs_install = True
seeded = retcode(name,
'test -e \'{0}\''.format(SEED_MARKER),
path=path,
chroot_fallback=True,
ignore_retcode=True) == 0
tmp = tempfile.mkdtemp()
if seeded and not unconditional_install:
ret = True
else:
ret = False
cfg_files = __salt__['seed.mkconfig'](
config, tmp=tmp, id_=name, approve_key=approve_key,
pub_key=pub_key, priv_key=priv_key)
if needs_install or force_install or unconditional_install:
if install:
rstr = __salt__['test.random_hash']()
configdir = '/var/tmp/.c_{0}'.format(rstr)
cmd = 'install -m 0700 -d {0}'.format(configdir)
if run_all(
name, cmd, path=path, python_shell=False
)['retcode'] != 0:
log.error('tmpdir %s creation failed %s', configdir, cmd)
return False
bs_ = __salt__['config.gather_bootstrap_script'](
bootstrap=bootstrap_url)
script = '/sbin/{0}_bootstrap.sh'.format(rstr)
copy_to(name, bs_, script, path=path)
result = run_all(name,
'sh -c "chmod +x {0}"'.format(script),
path=path,
python_shell=True)
copy_to(name, cfg_files['config'],
os.path.join(configdir, 'minion'),
path=path)
copy_to(name, cfg_files['privkey'],
os.path.join(configdir, 'minion.pem'),
path=path)
copy_to(name, cfg_files['pubkey'],
os.path.join(configdir, 'minion.pub'),
path=path)
bootstrap_args = bootstrap_args.format(configdir)
cmd = ('{0} {2} {1}'
.format(bootstrap_shell,
bootstrap_args.replace("'", "''"),
script))
# log ASAP the forged bootstrap command which can be wrapped
# out of the output in case of unexpected problem
log.info('Running %s in LXC container \'%s\'', cmd, name)
ret = retcode(name, cmd, output_loglevel='info',
path=path, use_vt=True) == 0
run_all(name,
'sh -c \'if [ -f "{0}" ];then rm -f "{0}";fi\''
''.format(script),
path=path,
ignore_retcode=True,
python_shell=True)
else:
ret = False
else:
minion_config = salt.config.minion_config(cfg_files['config'])
pki_dir = minion_config['pki_dir']
copy_to(name,
cfg_files['config'],
'/etc/salt/minion',
path=path)
copy_to(name,
cfg_files['privkey'],
os.path.join(pki_dir, 'minion.pem'),
path=path)
copy_to(name,
cfg_files['pubkey'],
os.path.join(pki_dir, 'minion.pub'),
path=path)
run(name,
'salt-call --local service.enable salt-minion',
path=path,
python_shell=False)
ret = True
shutil.rmtree(tmp)
if orig_state == 'stopped':
stop(name, path=path)
elif orig_state == 'frozen':
freeze(name, path=path)
# mark seeded upon successful install
if ret:
run(name,
'touch \'{0}\''.format(SEED_MARKER),
path=path,
python_shell=False)
return ret
def attachable(name, path=None):
'''
Return True if the named container can be attached to via the lxc-attach
command
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt 'minion' lxc.attachable ubuntu
'''
cachekey = 'lxc.attachable{0}{1}'.format(name, path)
try:
return __context__[cachekey]
except KeyError:
_ensure_exists(name, path=path)
# Can't use run() here because it uses attachable() and would
# endlessly recurse, resulting in a traceback
log.debug('Checking if LXC container %s is attachable', name)
cmd = 'lxc-attach'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' --clear-env -n {0} -- /usr/bin/env'.format(name)
result = __salt__['cmd.retcode'](cmd,
python_shell=False,
output_loglevel='quiet',
ignore_retcode=True) == 0
__context__[cachekey] = result
return __context__[cachekey]
def _run(name,
cmd,
output=None,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=None,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
Common logic for lxc.run functions
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
'''
orig_state = state(name, path=path)
try:
if attachable(name, path=path):
ret = __salt__['container_resource.run'](
name,
cmd,
path=path,
container_type=__virtualname__,
exec_driver=EXEC_DRIVER,
output=output,
no_start=no_start,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
ignore_retcode=ignore_retcode,
use_vt=use_vt,
keep_env=keep_env)
else:
if not chroot_fallback:
raise CommandExecutionError(
'{0} is not attachable.'.format(name))
rootfs = info(name, path=path).get('rootfs')
# Set context var to make cmd.run_chroot run cmd.run instead of
# cmd.run_all.
__context__['cmd.run_chroot.func'] = __salt__['cmd.run']
ret = __salt__['cmd.run_chroot'](rootfs,
cmd,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
ignore_retcode=ignore_retcode)
except Exception:
raise
finally:
# Make sure we honor preserve_state, even if there was an exception
new_state = state(name, path=path)
if preserve_state:
if orig_state == 'stopped' and new_state != 'stopped':
stop(name, path=path)
elif orig_state == 'frozen' and new_state != 'frozen':
freeze(name, start=True, path=path)
if output in (None, 'all'):
return ret
else:
return ret[output]
def run(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.8.0
Run :mod:`cmd.run <salt.modules.cmdmod.run>` within a container
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed in stderr if the command being run
does not exist. If no output is returned using this function, try using
:mod:`lxc.run_stderr <salt.modules.lxc.run_stderr>` or
:mod:`lxc.run_all <salt.modules.lxc.run_all>`.
name
Name of the container in which to run the command
cmd
Command to run
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console. Assumes
``output=all``.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
CLI Example:
.. code-block:: bash
salt myminion lxc.run mycontainer 'ifconfig -a'
'''
return _run(name,
cmd,
path=path,
output=None,
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def run_stdout(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.5.0
Run :mod:`cmd.run_stdout <salt.modules.cmdmod.run_stdout>` within a container
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed in stderr if the command being run
does not exist. If no output is returned using this function, try using
:mod:`lxc.run_stderr <salt.modules.lxc.run_stderr>` or
:mod:`lxc.run_all <salt.modules.lxc.run_all>`.
name
Name of the container in which to run the command
cmd
Command to run
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console
``output=all``.
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
CLI Example:
.. code-block:: bash
salt myminion lxc.run_stdout mycontainer 'ifconfig -a'
'''
return _run(name,
cmd,
path=path,
output='stdout',
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def run_stderr(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.5.0
Run :mod:`cmd.run_stderr <salt.modules.cmdmod.run_stderr>` within a container
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed if the command being run does not
exist.
name
Name of the container in which to run the command
cmd
Command to run
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console
``output=all``.
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
CLI Example:
.. code-block:: bash
salt myminion lxc.run_stderr mycontainer 'ip addr show'
'''
return _run(name,
cmd,
path=path,
output='stderr',
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def retcode(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.5.0
Run :mod:`cmd.retcode <salt.modules.cmdmod.retcode>` within a container
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed in stderr if the command being run
does not exist. If the retcode is nonzero and not what was expected,
try using :mod:`lxc.run_stderr <salt.modules.lxc.run_stderr>`
or :mod:`lxc.run_all <salt.modules.lxc.run_all>`.
name
Name of the container in which to run the command
cmd
Command to run
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console
``output=all``.
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
CLI Example:
.. code-block:: bash
salt myminion lxc.retcode mycontainer 'ip addr show'
'''
return _run(name,
cmd,
output='retcode',
path=path,
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def run_all(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.5.0
Run :mod:`cmd.run_all <salt.modules.cmdmod.run_all>` within a container
.. note::
While the command is run within the container, it is initiated from the
host. Therefore, the PID in the return dict is from the host, not from
the container.
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed in stderr if the command being run
does not exist.
name
Name of the container in which to run the command
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
cmd
Command to run
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console
``output=all``.
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
CLI Example:
.. code-block:: bash
salt myminion lxc.run_all mycontainer 'ip addr show'
'''
return _run(name,
cmd,
output='all',
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
path=path,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def _get_md5(name, path):
'''
Get the MD5 checksum of a file from a container
'''
output = run_stdout(name, 'md5sum "{0}"'.format(path),
chroot_fallback=True,
ignore_retcode=True)
try:
return output.split()[0]
except IndexError:
# Destination file does not exist or could not be accessed
return None
def copy_to(name, source, dest, overwrite=False, makedirs=False, path=None):
'''
.. versionchanged:: 2015.8.0
Function renamed from ``lxc.cp`` to ``lxc.copy_to`` for consistency
with other container types. ``lxc.cp`` will continue to work, however.
For versions 2015.2.x and earlier, use ``lxc.cp``.
Copy a file or directory from the host into a container
name
Container name
source
File to be copied to the container
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
dest
Destination on the container. Must be an absolute path.
.. versionchanged:: 2015.5.0
If the destination is a directory, the file will be copied into
that directory.
overwrite : False
Unless this option is set to ``True``, then if a file exists at the
location specified by the ``dest`` argument, an error will be raised.
.. versionadded:: 2015.8.0
makedirs : False
Create the parent directory on the container if it does not already
exist.
.. versionadded:: 2015.5.0
CLI Example:
.. code-block:: bash
salt 'minion' lxc.copy_to /tmp/foo /root/foo
salt 'minion' lxc.cp /tmp/foo /root/foo
'''
_ensure_running(name, no_start=True, path=path)
return __salt__['container_resource.copy_to'](
name,
source,
dest,
container_type=__virtualname__,
path=path,
exec_driver=EXEC_DRIVER,
overwrite=overwrite,
makedirs=makedirs)
cp = salt.utils.functools.alias_function(copy_to, 'cp')
def read_conf(conf_file, out_format='simple'):
'''
Read in an LXC configuration file. By default returns a simple, unsorted
dict, but can also return a more detailed structure including blank lines
and comments.
out_format:
set to 'simple' if you need the old and unsupported behavior.
This won't support the multiple lxc values (eg: multiple network nics)
CLI Examples:
.. code-block:: bash
salt 'minion' lxc.read_conf /etc/lxc/mycontainer.conf
salt 'minion' lxc.read_conf /etc/lxc/mycontainer.conf out_format=commented
'''
ret_commented = []
ret_simple = {}
with salt.utils.files.fopen(conf_file, 'r') as fp_:
for line in salt.utils.data.decode(fp_.readlines()):
if '=' not in line:
ret_commented.append(line)
continue
comps = line.split('=')
value = '='.join(comps[1:]).strip()
comment = None
if value.strip().startswith('#'):
vcomps = value.strip().split('#')
value = vcomps[1].strip()
comment = '#'.join(vcomps[1:]).strip()
ret_commented.append({comps[0].strip(): {
'value': value,
'comment': comment,
}})
else:
ret_commented.append({comps[0].strip(): value})
ret_simple[comps[0].strip()] = value
if out_format == 'simple':
return ret_simple
return ret_commented
def write_conf(conf_file, conf):
'''
Write out an LXC configuration file
This is normally only used internally. The format of the data structure
must match that which is returned from ``lxc.read_conf()``, with
``out_format`` set to ``commented``.
An example might look like:
.. code-block:: python
[
{'lxc.utsname': '$CONTAINER_NAME'},
'# This is a commented line\\n',
'\\n',
{'lxc.mount': '$CONTAINER_FSTAB'},
{'lxc.rootfs': {'comment': 'This is another test',
'value': 'This is another test'}},
'\\n',
{'lxc.network.type': 'veth'},
{'lxc.network.flags': 'up'},
{'lxc.network.link': 'br0'},
{'lxc.network.mac': '$CONTAINER_MACADDR'},
{'lxc.network.ipv4': '$CONTAINER_IPADDR'},
{'lxc.network.name': '$CONTAINER_DEVICENAME'},
]
CLI Example:
.. code-block:: bash
salt 'minion' lxc.write_conf /etc/lxc/mycontainer.conf \\
out_format=commented
'''
if not isinstance(conf, list):
raise SaltInvocationError('Configuration must be passed as a list')
# construct the content prior to write to the file
# to avoid half written configs
content = ''
for line in conf:
if isinstance(line, (six.text_type, six.string_types)):
content += line
elif isinstance(line, dict):
for key in list(line.keys()):
out_line = None
if isinstance(
line[key],
(six.text_type, six.string_types, six.integer_types, float)
):
out_line = ' = '.join((key, "{0}".format(line[key])))
elif isinstance(line[key], dict):
out_line = ' = '.join((key, line[key]['value']))
if 'comment' in line[key]:
out_line = ' # '.join((out_line, line[key]['comment']))
if out_line:
content += out_line
content += '\n'
with salt.utils.files.fopen(conf_file, 'w') as fp_:
fp_.write(salt.utils.stringutils.to_str(content))
return {}
def edit_conf(conf_file,
out_format='simple',
read_only=False,
lxc_config=None,
**kwargs):
'''
Edit an LXC configuration file. If a setting is already present inside the
file, its value will be replaced. If it does not exist, it will be appended
to the end of the file. Comments and blank lines will be kept in-tact if
they already exist in the file.
out_format:
Set to simple if you need backward compatibility (multiple items for a
simple key is not supported)
read_only:
return only the edited configuration without applying it
to the underlying lxc configuration file
lxc_config:
List of dict containning lxc configuration items
For network configuration, you also need to add the device it belongs
to, otherwise it will default to eth0.
Also, any change to a network parameter will result in the whole
network reconfiguration to avoid mismatchs, be aware of that !
After the file is edited, its contents will be returned. By default, it
will be returned in ``simple`` format, meaning an unordered dict (which
may not represent the actual file order). Passing in an ``out_format`` of
``commented`` will return a data structure which accurately represents the
order and content of the file.
CLI Example:
.. code-block:: bash
salt 'minion' lxc.edit_conf /etc/lxc/mycontainer.conf \\
out_format=commented lxc.network.type=veth
salt 'minion' lxc.edit_conf /etc/lxc/mycontainer.conf \\
out_format=commented \\
lxc_config="[{'lxc.network.name': 'eth0', \\
'lxc.network.ipv4': '1.2.3.4'},
{'lxc.network.name': 'eth2', \\
'lxc.network.ipv4': '1.2.3.5',\\
'lxc.network.gateway': '1.2.3.1'}]"
'''
data = []
try:
conf = read_conf(conf_file, out_format=out_format)
except Exception:
conf = []
if not lxc_config:
lxc_config = []
lxc_config = copy.deepcopy(lxc_config)
# search if we want to access net config
# in that case, we will replace all the net configuration
net_config = []
for lxc_kws in lxc_config + [kwargs]:
net_params = {}
for kwarg in [a for a in lxc_kws]:
if kwarg.startswith('__'):
continue
if kwarg.startswith('lxc.network.'):
net_params[kwarg] = lxc_kws[kwarg]
lxc_kws.pop(kwarg, None)
if net_params:
net_config.append(net_params)
nic_opts = salt.utils.odict.OrderedDict()
for params in net_config:
dev = params.get('lxc.network.name', DEFAULT_NIC)
dev_opts = nic_opts.setdefault(dev, salt.utils.odict.OrderedDict())
for param in params:
opt = param.replace('lxc.network.', '')
opt = {'hwaddr': 'mac'}.get(opt, opt)
dev_opts[opt] = params[param]
net_changes = []
if nic_opts:
net_changes = _config_list(conf, only_net=True,
**{'network_profile': DEFAULT_NIC,
'nic_opts': nic_opts})
if net_changes:
lxc_config.extend(net_changes)
for line in conf:
if not isinstance(line, dict):
data.append(line)
continue
else:
for key in list(line.keys()):
val = line[key]
if net_changes and key.startswith('lxc.network.'):
continue
found = False
for ix in range(len(lxc_config)):
kw = lxc_config[ix]
if key in kw:
found = True
data.append({key: kw[key]})
del kw[key]
if not found:
data.append({key: val})
for lxc_kws in lxc_config:
for kwarg in lxc_kws:
data.append({kwarg: lxc_kws[kwarg]})
if read_only:
return data
write_conf(conf_file, data)
return read_conf(conf_file, out_format)
def reboot(name, path=None):
'''
Reboot a container.
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Examples:
.. code-block:: bash
salt 'minion' lxc.reboot myvm
'''
ret = {'result': True,
'changes': {},
'comment': '{0} rebooted'.format(name)}
does_exist = exists(name, path=path)
if does_exist and (state(name, path=path) == 'running'):
try:
stop(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
ret['result'] = False
return ret
if does_exist and (state(name, path=path) != 'running'):
try:
start(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
ret['result'] = False
return ret
ret['changes'][name] = 'rebooted'
return ret
def reconfigure(name,
cpu=None,
cpuset=None,
cpushare=None,
memory=None,
profile=None,
network_profile=None,
nic_opts=None,
bridge=None,
gateway=None,
autostart=None,
utsname=None,
rootfs=None,
path=None,
**kwargs):
'''
Reconfigure a container.
This only applies to a few property
name
Name of the container.
utsname
utsname of the container.
.. versionadded:: 2016.3.0
rootfs
rootfs of the container.
.. versionadded:: 2016.3.0
cpu
Select a random number of cpu cores and assign it to the cpuset, if the
cpuset option is set then this option will be ignored
cpuset
Explicitly define the cpus this container will be bound to
cpushare
cgroups cpu shares.
autostart
autostart container on reboot
memory
cgroups memory limit, in MB.
(0 for nolimit, None for old default 1024MB)
gateway
the ipv4 gateway to use
the default does nothing more than lxcutils does
bridge
the bridge to use
the default does nothing more than lxcutils does
nic
Network interfaces profile (defined in config or pillar).
nic_opts
Extra options for network interfaces, will override
``{"eth0": {"mac": "aa:bb:cc:dd:ee:ff", "ipv4": "10.1.1.1", "ipv6": "2001:db8::ff00:42:8329"}}``
or
``{"eth0": {"mac": "aa:bb:cc:dd:ee:ff", "ipv4": "10.1.1.1/24", "ipv6": "2001:db8::ff00:42:8329"}}``
path
path to the container parent
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt-call -lall mc_lxc_fork.reconfigure foobar nic_opts="{'eth1': {'mac': '00:16:3e:dd:ee:44'}}" memory=4
'''
changes = {}
cpath = get_root_path(path)
path = os.path.join(cpath, name, 'config')
ret = {'name': name,
'comment': 'config for {0} up to date'.format(name),
'result': True,
'changes': changes}
profile = get_container_profile(copy.deepcopy(profile))
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, _marker)
profile_match = profile.pop(key, default)
# let kwarg overrides be the preferred choice
if kw_overrides_match is _marker:
return profile_match
return kw_overrides_match
if nic_opts is not None and not network_profile:
network_profile = DEFAULT_NIC
if autostart is not None:
autostart = select('autostart', autostart)
else:
autostart = 'keep'
if not utsname:
utsname = select('utsname', utsname)
if os.path.exists(path):
old_chunks = read_conf(path, out_format='commented')
make_kw = salt.utils.odict.OrderedDict([
('utsname', utsname),
('rootfs', rootfs),
('autostart', autostart),
('cpu', cpu),
('gateway', gateway),
('cpuset', cpuset),
('cpushare', cpushare),
('network_profile', network_profile),
('nic_opts', nic_opts),
('bridge', bridge)])
# match 0 and none as memory = 0 in lxc config is harmful
if memory:
make_kw['memory'] = memory
kw = salt.utils.odict.OrderedDict()
for key, val in six.iteritems(make_kw):
if val is not None:
kw[key] = val
new_cfg = _config_list(conf_tuples=old_chunks, **kw)
if new_cfg:
edit_conf(path, out_format='commented', lxc_config=new_cfg)
chunks = read_conf(path, out_format='commented')
if old_chunks != chunks:
ret['comment'] = '{0} lxc config updated'.format(name)
if state(name, path=path) == 'running':
cret = reboot(name, path=path)
ret['result'] = cret['result']
return ret
def apply_network_profile(name, network_profile, nic_opts=None, path=None):
'''
.. versionadded:: 2015.5.0
Apply a network profile to a container
network_profile
profile name or default values (dict)
nic_opts
values to override in defaults (dict)
indexed by nic card names
path
path to the container parent
.. versionadded:: 2015.8.0
CLI Examples:
.. code-block:: bash
salt 'minion' lxc.apply_network_profile web1 centos
salt 'minion' lxc.apply_network_profile web1 centos \\
nic_opts="{'eth0': {'mac': 'xx:xx:xx:xx:xx:xx'}}"
salt 'minion' lxc.apply_network_profile web1 \\
"{'eth0': {'mac': 'xx:xx:xx:xx:xx:yy'}}"
nic_opts="{'eth0': {'mac': 'xx:xx:xx:xx:xx:xx'}}"
The special case to disable use of ethernet nics:
.. code-block:: bash
salt 'minion' lxc.apply_network_profile web1 centos \\
"{eth0: {disable: true}}"
'''
cpath = get_root_path(path)
cfgpath = os.path.join(cpath, name, 'config')
before = []
with salt.utils.files.fopen(cfgpath, 'r') as fp_:
for line in fp_:
before.append(line)
lxcconfig = _LXCConfig(name=name, path=path)
old_net = lxcconfig._filter_data('lxc.network')
network_params = {}
for param in _network_conf(
conf_tuples=old_net,
network_profile=network_profile, nic_opts=nic_opts
):
network_params.update(param)
if network_params:
edit_conf(cfgpath, out_format='commented', **network_params)
after = []
with salt.utils.files.fopen(cfgpath, 'r') as fp_:
for line in fp_:
after.append(line)
diff = ''
for line in difflib.unified_diff(before,
after,
fromfile='before',
tofile='after'):
diff += line
return diff
def get_pid(name, path=None):
'''
Returns a container pid.
Throw an exception if the container isn't running.
CLI Example:
.. code-block:: bash
salt '*' lxc.get_pid name
'''
if name not in list_(limit='running', path=path):
raise CommandExecutionError('Container {0} is not running, can\'t determine PID'.format(name))
info = __salt__['cmd.run']('lxc-info -n {0}'.format(name)).split("\n")
pid = [line.split(':')[1].strip() for line in info if re.match(r'\s*PID', line)][0]
return pid
def add_veth(name, interface_name, bridge=None, path=None):
'''
Add a veth to a container.
Note : this function doesn't update the container config, just add the interface at runtime
name
Name of the container
interface_name
Name of the interface in the container
bridge
Name of the bridge to attach the interface to (facultative)
CLI Examples:
.. code-block:: bash
salt '*' lxc.add_veth container_name eth1 br1
salt '*' lxc.add_veth container_name eth1
'''
# Get container init PID
pid = get_pid(name, path=path)
# Generate a ramdom string for veth and ensure that is isn't present on the system
while True:
random_veth = 'veth'+''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(6))
if random_veth not in __salt__['network.interfaces']().keys():
break
# Check prerequisites
if not __salt__['file.directory_exists']('/var/run/'):
raise CommandExecutionError('Directory /var/run required for lxc.add_veth doesn\'t exists')
if not __salt__['file.file_exists']('/proc/{0}/ns/net'.format(pid)):
raise CommandExecutionError('Proc file for container {0} network namespace doesn\'t exists'.format(name))
if not __salt__['file.directory_exists']('/var/run/netns'):
__salt__['file.mkdir']('/var/run/netns')
# Ensure that the symlink is up to date (change on container restart)
if __salt__['file.is_link']('/var/run/netns/{0}'.format(name)):
__salt__['file.remove']('/var/run/netns/{0}'.format(name))
__salt__['file.symlink']('/proc/{0}/ns/net'.format(pid), '/var/run/netns/{0}'.format(name))
# Ensure that interface doesn't exists
interface_exists = 0 == __salt__['cmd.retcode']('ip netns exec {netns} ip address list {interface}'.format(
netns=name,
interface=interface_name
))
if interface_exists:
raise CommandExecutionError('Interface {interface} already exists in {container}'.format(
interface=interface_name,
container=name
))
# Create veth and bring it up
if __salt__['cmd.retcode']('ip link add name {veth} type veth peer name {veth}_c'.format(veth=random_veth)) != 0:
raise CommandExecutionError('Error while creating the veth pair {0}'.format(random_veth))
if __salt__['cmd.retcode']('ip link set dev {0} up'.format(random_veth)) != 0:
raise CommandExecutionError('Error while bringing up host-side veth {0}'.format(random_veth))
# Attach it to the container
attached = 0 == __salt__['cmd.retcode']('ip link set dev {veth}_c netns {container} name {interface_name}'.format(
veth=random_veth,
container=name,
interface_name=interface_name
))
if not attached:
raise CommandExecutionError('Error while attaching the veth {veth} to container {container}'.format(
veth=random_veth,
container=name
))
__salt__['file.remove']('/var/run/netns/{0}'.format(name))
if bridge is not None:
__salt__['bridge.addif'](bridge, random_veth)
|
saltstack/salt
|
salt/modules/lxc.py
|
restart
|
python
|
def restart(name, path=None, lxc_config=None, force=False):
'''
.. versionadded:: 2015.5.0
Restart the named container. If the container was not running, the
container will merely be started.
name
The name of the container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
lxc_config
path to a lxc config file
config file will be guessed from container name otherwise
.. versionadded:: 2015.8.0
force : False
If ``True``, the container will be force-stopped instead of gracefully
shut down
CLI Example:
.. code-block:: bash
salt myminion lxc.restart name
'''
_ensure_exists(name, path=path)
orig_state = state(name, path=path)
if orig_state != 'stopped':
stop(name, kill=force, path=path)
ret = start(name, path=path, lxc_config=lxc_config)
ret['state']['old'] = orig_state
if orig_state != 'stopped':
ret['restarted'] = True
return ret
|
.. versionadded:: 2015.5.0
Restart the named container. If the container was not running, the
container will merely be started.
name
The name of the container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
lxc_config
path to a lxc config file
config file will be guessed from container name otherwise
.. versionadded:: 2015.8.0
force : False
If ``True``, the container will be force-stopped instead of gracefully
shut down
CLI Example:
.. code-block:: bash
salt myminion lxc.restart name
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/lxc.py#L2343-L2383
|
[
"def start(name, **kwargs):\n '''\n Start the named container\n\n path\n path to the container parent directory\n default: /var/lib/lxc (system)\n\n .. versionadded:: 2015.8.0\n\n lxc_config\n path to a lxc config file\n config file will be guessed from container name otherwise\n\n .. versionadded:: 2015.8.0\n\n use_vt\n run the command through VT\n\n .. versionadded:: 2015.8.0\n\n CLI Example:\n\n .. code-block:: bash\n\n salt myminion lxc.start name\n '''\n path = kwargs.get('path', None)\n cpath = get_root_path(path)\n lxc_config = kwargs.get('lxc_config', None)\n cmd = 'lxc-start'\n if not lxc_config:\n lxc_config = os.path.join(cpath, name, 'config')\n # we try to start, even without config, if global opts are there\n if os.path.exists(lxc_config):\n cmd += ' -f {0}'.format(pipes.quote(lxc_config))\n cmd += ' -d'\n _ensure_exists(name, path=path)\n if state(name, path=path) == 'frozen':\n raise CommandExecutionError(\n 'Container \\'{0}\\' is frozen, use lxc.unfreeze'.format(name)\n )\n # lxc-start daemonize itself violently, we must not communicate with it\n use_vt = kwargs.get('use_vt', None)\n with_communicate = kwargs.get('with_communicate', False)\n return _change_state(cmd, name, 'running',\n stdout=None,\n stderr=None,\n stdin=None,\n with_communicate=with_communicate,\n path=path,\n use_vt=use_vt)\n",
"def stop(name, kill=False, path=None, use_vt=None):\n '''\n Stop the named container\n\n path\n path to the container parent directory\n default: /var/lib/lxc (system)\n\n .. versionadded:: 2015.8.0\n\n kill: False\n Do not wait for the container to stop, kill all tasks in the container.\n Older LXC versions will stop containers like this irrespective of this\n argument.\n\n .. versionchanged:: 2015.5.0\n Default value changed to ``False``\n\n use_vt\n run the command through VT\n\n .. versionadded:: 2015.8.0\n\n CLI Example:\n\n .. code-block:: bash\n\n salt myminion lxc.stop name\n '''\n _ensure_exists(name, path=path)\n orig_state = state(name, path=path)\n if orig_state == 'frozen' and not kill:\n # Gracefully stopping a frozen container is slower than unfreezing and\n # then stopping it (at least in my testing), so if we're not\n # force-stopping the container, unfreeze it first.\n unfreeze(name, path=path)\n cmd = 'lxc-stop'\n if kill:\n cmd += ' -k'\n ret = _change_state(cmd, name, 'stopped', use_vt=use_vt, path=path)\n ret['state']['old'] = orig_state\n return ret\n",
"def state(name, path=None):\n '''\n Returns the state of a container.\n\n path\n path to the container parent directory (default: /var/lib/lxc)\n\n .. versionadded:: 2015.8.0\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' lxc.state name\n '''\n # Don't use _ensure_exists() here, it will mess with _change_state()\n\n cachekey = 'lxc.state.{0}{1}'.format(name, path)\n try:\n return __context__[cachekey]\n except KeyError:\n if not exists(name, path=path):\n __context__[cachekey] = None\n else:\n cmd = 'lxc-info'\n if path:\n cmd += ' -P {0}'.format(pipes.quote(path))\n cmd += ' -n {0}'.format(name)\n ret = __salt__['cmd.run_all'](cmd, python_shell=False)\n if ret['retcode'] != 0:\n _clear_context()\n raise CommandExecutionError(\n 'Unable to get state of container \\'{0}\\''.format(name)\n )\n c_infos = ret['stdout'].splitlines()\n c_state = None\n for c_info in c_infos:\n stat = c_info.split(':')\n if stat[0].lower() == 'state':\n c_state = stat[1].strip().lower()\n break\n __context__[cachekey] = c_state\n return __context__[cachekey]\n",
"def _ensure_exists(name, path=None):\n '''\n Raise an exception if the container does not exist\n '''\n if not exists(name, path=path):\n raise CommandExecutionError(\n 'Container \\'{0}\\' does not exist'.format(name)\n )\n"
] |
# -*- coding: utf-8 -*-
'''
Control Linux Containers via Salt
:depends: lxc package for distribution
lxc >= 1.0 (even beta alpha) is required
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import datetime
import copy
import string
import textwrap
import difflib
import logging
import tempfile
import os
import pipes
import time
import shutil
import re
import random
# Import salt libs
import salt.utils.args
import salt.utils.cloud
import salt.utils.data
import salt.utils.dictupdate
import salt.utils.files
import salt.utils.functools
import salt.utils.hashutils
import salt.utils.network
import salt.utils.odict
import salt.utils.path
import salt.utils.stringutils
from salt.exceptions import CommandExecutionError, SaltInvocationError
import salt.config
from salt.utils.versions import LooseVersion as _LooseVersion
# Import 3rd-party libs
from salt.ext import six
# pylint: disable=import-error,no-name-in-module
from salt.ext.six.moves import range # pylint: disable=redefined-builtin
from salt.ext.six.moves.urllib.parse import urlparse as _urlparse
# pylint: enable=import-error,no-name-in-module
# Set up logging
log = logging.getLogger(__name__)
# Don't shadow built-in's.
__func_alias__ = {
'list_': 'list',
'ls_': 'ls'
}
__virtualname__ = 'lxc'
DEFAULT_NIC = 'eth0'
DEFAULT_BR = 'br0'
SEED_MARKER = '/lxc.initial_seed'
EXEC_DRIVER = 'lxc-attach'
DEFAULT_PATH = '/var/lib/lxc'
_marker = object()
def __virtual__():
if salt.utils.path.which('lxc-start'):
return __virtualname__
# To speed up the whole thing, we decided to not use the
# subshell way and assume things are in place for lxc
# Discussion made by @kiorky and @thatch45
# lxc-version presence is not sufficient, in lxc1.0 alpha
# (precise backports), we have it and it is sufficient
# for the module to execute.
# elif salt.utils.path.which('lxc-version'):
# passed = False
# try:
# passed = subprocess.check_output(
# 'lxc-version').split(':')[1].strip() >= '1.0'
# except Exception:
# pass
# if not passed:
# log.warning('Support for lxc < 1.0 may be incomplete.')
# return 'lxc'
# return False
#
return (False, 'The lxc execution module cannot be loaded: the lxc-start binary is not in the path.')
def get_root_path(path):
'''
Get the configured lxc root for containers
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.get_root_path
'''
if not path:
path = __opts__.get('lxc.root_path', DEFAULT_PATH)
return path
def version():
'''
Return the actual lxc client version
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.version
'''
k = 'lxc.version'
if not __context__.get(k, None):
cversion = __salt__['cmd.run_all']('lxc-info --version')
if not cversion['retcode']:
ver = _LooseVersion(cversion['stdout'])
if ver < _LooseVersion('1.0'):
raise CommandExecutionError('LXC should be at least 1.0')
__context__[k] = "{0}".format(ver)
return __context__.get(k, None)
def _clear_context():
'''
Clear any lxc variables set in __context__
'''
for var in [x for x in __context__ if x.startswith('lxc.')]:
log.trace('Clearing __context__[\'%s\']', var)
__context__.pop(var, None)
def _ip_sort(ip):
'''Ip sorting'''
idx = '001'
if ip == '127.0.0.1':
idx = '200'
if ip == '::1':
idx = '201'
elif '::' in ip:
idx = '100'
return '{0}___{1}'.format(idx, ip)
def search_lxc_bridges():
'''
Search which bridges are potentially available as LXC bridges
CLI Example:
.. code-block:: bash
salt '*' lxc.search_lxc_bridges
'''
bridges = __context__.get('lxc.bridges', None)
# either match not yet called or no bridges were found
# to handle the case where lxc was not installed on the first
# call
if not bridges:
bridges = set()
running_bridges = set()
bridges.add(DEFAULT_BR)
try:
output = __salt__['cmd.run_all']('brctl show')
for line in output['stdout'].splitlines()[1:]:
if not line.startswith(' '):
running_bridges.add(line.split()[0].strip())
except (SaltInvocationError, CommandExecutionError):
pass
for ifc, ip in six.iteritems(
__grains__.get('ip_interfaces', {})
):
if ifc in running_bridges:
bridges.add(ifc)
elif os.path.exists(
'/sys/devices/virtual/net/{0}/bridge'.format(ifc)
):
bridges.add(ifc)
bridges = list(bridges)
# if we found interfaces that have lxc in their names
# we filter them as being the potential lxc bridges
# we also try to default on br0 on other cases
def sort_bridges(a):
pref = 'z'
if 'lxc' in a:
pref = 'a'
elif 'br0' == a:
pref = 'c'
return '{0}_{1}'.format(pref, a)
bridges.sort(key=sort_bridges)
__context__['lxc.bridges'] = bridges
return bridges
def search_lxc_bridge():
'''
Search the first bridge which is potentially available as LXC bridge
CLI Example:
.. code-block:: bash
salt '*' lxc.search_lxc_bridge
'''
return search_lxc_bridges()[0]
def _get_salt_config(config, **kwargs):
if not config:
config = kwargs.get('minion', {})
if not config:
config = {}
config.setdefault('master',
kwargs.get('master',
__opts__.get('master',
__opts__['id'])))
config.setdefault(
'master_port',
kwargs.get('master_port',
__opts__.get('master_port',
__opts__.get('ret_port',
__opts__.get('4506')))))
if not config['master']:
config = {}
return config
def cloud_init_interface(name, vm_=None, **kwargs):
'''
Interface between salt.cloud.lxc driver and lxc.init
``vm_`` is a mapping of vm opts in the salt.cloud format
as documented for the lxc driver.
This can be used either:
- from the salt cloud driver
- because you find the argument to give easier here
than using directly lxc.init
.. warning::
BE REALLY CAREFUL CHANGING DEFAULTS !!!
IT'S A RETRO COMPATIBLE INTERFACE WITH
THE SALT CLOUD DRIVER (ask kiorky).
name
name of the lxc container to create
pub_key
public key to preseed the minion with.
Can be the keycontent or a filepath
priv_key
private key to preseed the minion with.
Can be the keycontent or a filepath
path
path to the container parent directory (default: /var/lib/lxc)
.. versionadded:: 2015.8.0
profile
:ref:`profile <tutorial-lxc-profiles-container>` selection
network_profile
:ref:`network profile <tutorial-lxc-profiles-network>` selection
nic_opts
per interface settings compatibles with
network profile (ipv4/ipv6/link/gateway/mac/netmask)
eg::
- {'eth0': {'mac': '00:16:3e:01:29:40',
'gateway': None, (default)
'link': 'br0', (default)
'gateway': None, (default)
'netmask': '', (default)
'ip': '22.1.4.25'}}
unconditional_install
given to lxc.bootstrap (see relative doc)
force_install
given to lxc.bootstrap (see relative doc)
config
any extra argument for the salt minion config
dnsservers
list of DNS servers to set inside the container
dns_via_dhcp
do not set the dns servers, let them be set by the dhcp.
autostart
autostart the container at boot time
password
administrative password for the container
bootstrap_delay
delay before launching bootstrap script at Container init
.. warning::
Legacy but still supported options:
from_container
which container we use as a template
when running lxc.clone
image
which template do we use when we
are using lxc.create. This is the default
mode unless you specify something in from_container
backing
which backing store to use.
Values can be: overlayfs, dir(default), lvm, zfs, brtfs
fstype
When using a blockdevice level backing store,
which filesystem to use on
size
When using a blockdevice level backing store,
which size for the filesystem to use on
snapshot
Use snapshot when cloning the container source
vgname
if using LVM: vgname
lvname
if using LVM: lvname
thinpool:
if using LVM: thinpool
ip
ip for the primary nic
mac
mac address for the primary nic
netmask
netmask for the primary nic (24)
= ``vm_.get('netmask', '24')``
bridge
bridge for the primary nic (lxcbr0)
gateway
network gateway for the container
additional_ips
additional ips which will be wired on the main bridge (br0)
which is connected to internet.
Be aware that you may use manual virtual mac addresses
providen by you provider (online, ovh, etc).
This is a list of mappings {ip: '', mac: '', netmask:''}
Set gateway to None and an interface with a gateway
to escape from another interface that eth0.
eg::
- {'mac': '00:16:3e:01:29:40',
'gateway': None, (default)
'link': 'br0', (default)
'netmask': '', (default)
'ip': '22.1.4.25'}
users
administrative users for the container
default: [root] and [root, ubuntu] on ubuntu
default_nic
name of the first interface, you should
really not override this
CLI Example:
.. code-block:: bash
salt '*' lxc.cloud_init_interface foo
'''
if vm_ is None:
vm_ = {}
vm_ = copy.deepcopy(vm_)
vm_ = salt.utils.dictupdate.update(vm_, kwargs)
profile_data = copy.deepcopy(
vm_.get('lxc_profile',
vm_.get('profile', {})))
if not isinstance(profile_data, (dict, six.string_types)):
profile_data = {}
profile = get_container_profile(profile_data)
def _cloud_get(k, default=None):
return vm_.get(k, profile.get(k, default))
if name is None:
name = vm_['name']
# if we are on ubuntu, default to ubuntu
default_template = ''
if __grains__.get('os', '') in ['Ubuntu']:
default_template = 'ubuntu'
image = _cloud_get('image')
if not image:
_cloud_get('template', default_template)
backing = _cloud_get('backing', 'dir')
if image:
profile['template'] = image
vgname = _cloud_get('vgname', None)
if vgname:
profile['vgname'] = vgname
if backing:
profile['backing'] = backing
snapshot = _cloud_get('snapshot', False)
autostart = bool(_cloud_get('autostart', True))
dnsservers = _cloud_get('dnsservers', [])
dns_via_dhcp = _cloud_get('dns_via_dhcp', True)
password = _cloud_get('password', 's3cr3t')
password_encrypted = _cloud_get('password_encrypted', False)
fstype = _cloud_get('fstype', None)
lvname = _cloud_get('lvname', None)
thinpool = _cloud_get('thinpool', None)
pub_key = _cloud_get('pub_key', None)
priv_key = _cloud_get('priv_key', None)
size = _cloud_get('size', '20G')
script = _cloud_get('script', None)
script_args = _cloud_get('script_args', None)
users = _cloud_get('users', None)
if users is None:
users = []
ssh_username = _cloud_get('ssh_username', None)
if ssh_username and (ssh_username not in users):
users.append(ssh_username)
network_profile = _cloud_get('network_profile', None)
nic_opts = kwargs.get('nic_opts', None)
netmask = _cloud_get('netmask', '24')
path = _cloud_get('path', None)
bridge = _cloud_get('bridge', None)
gateway = _cloud_get('gateway', None)
unconditional_install = _cloud_get('unconditional_install', False)
force_install = _cloud_get('force_install', True)
config = _get_salt_config(_cloud_get('config', {}), **vm_)
default_nic = _cloud_get('default_nic', DEFAULT_NIC)
# do the interface with lxc.init mainly via nic_opts
# to avoid extra and confusing extra use cases.
if not isinstance(nic_opts, dict):
nic_opts = salt.utils.odict.OrderedDict()
# have a reference to the default nic
eth0 = nic_opts.setdefault(default_nic,
salt.utils.odict.OrderedDict())
# lxc config is based of ifc order, be sure to use odicts.
if not isinstance(nic_opts, salt.utils.odict.OrderedDict):
bnic_opts = salt.utils.odict.OrderedDict()
bnic_opts.update(nic_opts)
nic_opts = bnic_opts
gw = None
# legacy salt.cloud scheme for network interfaces settings support
bridge = _cloud_get('bridge', None)
ip = _cloud_get('ip', None)
mac = _cloud_get('mac', None)
if ip:
fullip = ip
if netmask:
fullip += '/{0}'.format(netmask)
eth0['ipv4'] = fullip
if mac is not None:
eth0['mac'] = mac
for ix, iopts in enumerate(_cloud_get("additional_ips", [])):
ifh = "eth{0}".format(ix+1)
ethx = nic_opts.setdefault(ifh, {})
if gw is None:
gw = iopts.get('gateway', ethx.get('gateway', None))
if gw:
# only one and only one default gateway is allowed !
eth0.pop('gateway', None)
gateway = None
# even if the gateway if on default "eth0" nic
# and we popped it will work
# as we reinject or set it here.
ethx['gateway'] = gw
elink = iopts.get('link', ethx.get('link', None))
if elink:
ethx['link'] = elink
# allow dhcp
aip = iopts.get('ipv4', iopts.get('ip', None))
if aip:
ethx['ipv4'] = aip
nm = iopts.get('netmask', '')
if nm:
ethx['ipv4'] += '/{0}'.format(nm)
for i in ('mac', 'hwaddr'):
if i in iopts:
ethx['mac'] = iopts[i]
break
if 'mac' not in ethx:
ethx['mac'] = salt.utils.network.gen_mac()
# last round checking for unique gateway and such
gw = None
for ethx in [a for a in nic_opts]:
ndata = nic_opts[ethx]
if gw:
ndata.pop('gateway', None)
if 'gateway' in ndata:
gw = ndata['gateway']
gateway = None
# only use a default bridge / gateway if we configured them
# via the legacy salt cloud configuration style.
# On other cases, we should rely on settings provided by the new
# salt lxc network profile style configuration which can
# be also be overridden or a per interface basis via the nic_opts dict.
if bridge:
eth0['link'] = bridge
if gateway:
eth0['gateway'] = gateway
#
lxc_init_interface = {}
lxc_init_interface['name'] = name
lxc_init_interface['config'] = config
lxc_init_interface['memory'] = _cloud_get('memory', 0) # nolimit
lxc_init_interface['pub_key'] = pub_key
lxc_init_interface['priv_key'] = priv_key
lxc_init_interface['nic_opts'] = nic_opts
for clone_from in ['clone_from', 'clone', 'from_container']:
# clone_from should default to None if not available
lxc_init_interface['clone_from'] = _cloud_get(clone_from, None)
if lxc_init_interface['clone_from'] is not None:
break
lxc_init_interface['profile'] = profile
lxc_init_interface['snapshot'] = snapshot
lxc_init_interface['dnsservers'] = dnsservers
lxc_init_interface['fstype'] = fstype
lxc_init_interface['path'] = path
lxc_init_interface['vgname'] = vgname
lxc_init_interface['size'] = size
lxc_init_interface['lvname'] = lvname
lxc_init_interface['thinpool'] = thinpool
lxc_init_interface['force_install'] = force_install
lxc_init_interface['unconditional_install'] = (
unconditional_install
)
lxc_init_interface['bootstrap_url'] = script
lxc_init_interface['bootstrap_args'] = script_args
lxc_init_interface['bootstrap_shell'] = _cloud_get('bootstrap_shell', 'sh')
lxc_init_interface['bootstrap_delay'] = _cloud_get('bootstrap_delay', None)
lxc_init_interface['autostart'] = autostart
lxc_init_interface['users'] = users
lxc_init_interface['password'] = password
lxc_init_interface['password_encrypted'] = password_encrypted
# be sure not to let objects goes inside the return
# as this return will be msgpacked for use in the runner !
lxc_init_interface['network_profile'] = network_profile
for i in ['cpu', 'cpuset', 'cpushare']:
if _cloud_get(i, None):
try:
lxc_init_interface[i] = vm_[i]
except KeyError:
lxc_init_interface[i] = profile[i]
return lxc_init_interface
def _get_profile(key, name, **kwargs):
if isinstance(name, dict):
profilename = name.pop('name', None)
return _get_profile(key, profilename, **name)
if name is None:
profile_match = {}
else:
profile_match = \
__salt__['config.get'](
'lxc.{1}:{0}'.format(name, key),
default=None,
merge='recurse'
)
if profile_match is None:
# No matching profile, make the profile an empty dict so that
# overrides can be applied below.
profile_match = {}
if not isinstance(profile_match, dict):
raise CommandExecutionError('lxc.{0} must be a dictionary'.format(key))
# Overlay the kwargs to override matched profile data
overrides = salt.utils.args.clean_kwargs(**copy.deepcopy(kwargs))
profile_match = salt.utils.dictupdate.update(
copy.deepcopy(profile_match),
overrides
)
return profile_match
def get_container_profile(name=None, **kwargs):
'''
.. versionadded:: 2015.5.0
Gather a pre-configured set of container configuration parameters. If no
arguments are passed, an empty profile is returned.
Profiles can be defined in the minion or master config files, or in pillar
or grains, and are loaded using :mod:`config.get
<salt.modules.config.get>`. The key under which LXC profiles must be
configured is ``lxc.container_profile.profile_name``. An example container
profile would be as follows:
.. code-block:: yaml
lxc.container_profile:
ubuntu:
template: ubuntu
backing: lvm
vgname: lxc
size: 1G
Parameters set in a profile can be overridden by passing additional
container creation arguments (such as the ones passed to :mod:`lxc.create
<salt.modules.lxc.create>`) to this function.
A profile can be defined either as the name of the profile, or a dictionary
of variable names and values. See the :ref:`LXC Tutorial
<tutorial-lxc-profiles>` for more information on how to use LXC profiles.
CLI Example:
.. code-block:: bash
salt-call lxc.get_container_profile centos
salt-call lxc.get_container_profile ubuntu template=ubuntu backing=overlayfs
'''
profile = _get_profile('container_profile', name, **kwargs)
return profile
def get_network_profile(name=None, **kwargs):
'''
.. versionadded:: 2015.5.0
Gather a pre-configured set of network configuration parameters. If no
arguments are passed, the following default profile is returned:
.. code-block:: python
{'eth0': {'link': 'br0', 'type': 'veth', 'flags': 'up'}}
Profiles can be defined in the minion or master config files, or in pillar
or grains, and are loaded using :mod:`config.get
<salt.modules.config.get>`. The key under which LXC profiles must be
configured is ``lxc.network_profile``. An example network profile would be
as follows:
.. code-block:: yaml
lxc.network_profile.centos:
eth0:
link: br0
type: veth
flags: up
To disable networking entirely:
.. code-block:: yaml
lxc.network_profile.centos:
eth0:
disable: true
Parameters set in a profile can be overridden by passing additional
arguments to this function.
A profile can be passed either as the name of the profile, or a
dictionary of variable names and values. See the :ref:`LXC Tutorial
<tutorial-lxc-profiles>` for more information on how to use network
profiles.
.. warning::
The ``ipv4``, ``ipv6``, ``gateway``, and ``link`` (bridge) settings in
network profiles will only work if the container doesn't redefine the
network configuration (for example in
``/etc/sysconfig/network-scripts/ifcfg-<interface_name>`` on
RHEL/CentOS, or ``/etc/network/interfaces`` on Debian/Ubuntu/etc.)
CLI Example:
.. code-block:: bash
salt-call lxc.get_network_profile default
'''
profile = _get_profile('network_profile', name, **kwargs)
return profile
def _rand_cpu_str(cpu):
'''
Return a random subset of cpus for the cpuset config
'''
cpu = int(cpu)
avail = __salt__['status.nproc']()
if cpu < avail:
return '0-{0}'.format(avail)
to_set = set()
while len(to_set) < cpu:
choice = random.randint(0, avail - 1)
if choice not in to_set:
to_set.add(six.text_type(choice))
return ','.join(sorted(to_set))
def _network_conf(conf_tuples=None, **kwargs):
'''
Network configuration defaults
network_profile
as for containers, we can either call this function
either with a network_profile dict or network profile name
in the kwargs
nic_opts
overrides or extra nics in the form {nic_name: {set: tings}
'''
nic = kwargs.get('network_profile', None)
ret = []
nic_opts = kwargs.get('nic_opts', {})
if nic_opts is None:
# coming from elsewhere
nic_opts = {}
if not conf_tuples:
conf_tuples = []
old = _get_veths(conf_tuples)
if not old:
old = {}
# if we have a profile name, get the profile and load the network settings
# this will obviously by default look for a profile called "eth0"
# or by what is defined in nic_opts
# and complete each nic settings by sane defaults
if nic and isinstance(nic, (six.string_types, dict)):
nicp = get_network_profile(nic)
else:
nicp = {}
if DEFAULT_NIC not in nicp:
nicp[DEFAULT_NIC] = {}
kwargs = copy.deepcopy(kwargs)
gateway = kwargs.pop('gateway', None)
bridge = kwargs.get('bridge', None)
if nic_opts:
for dev, args in six.iteritems(nic_opts):
ethx = nicp.setdefault(dev, {})
try:
ethx = salt.utils.dictupdate.update(ethx, args)
except AttributeError:
raise SaltInvocationError('Invalid nic_opts configuration')
ifs = [a for a in nicp]
ifs += [a for a in old if a not in nicp]
ifs.sort()
gateway_set = False
for dev in ifs:
args = nicp.get(dev, {})
opts = nic_opts.get(dev, {}) if nic_opts else {}
old_if = old.get(dev, {})
disable = opts.get('disable', args.get('disable', False))
if disable:
continue
mac = opts.get('mac',
opts.get('hwaddr',
args.get('mac',
args.get('hwaddr', ''))))
type_ = opts.get('type', args.get('type', ''))
flags = opts.get('flags', args.get('flags', ''))
link = opts.get('link', args.get('link', ''))
ipv4 = opts.get('ipv4', args.get('ipv4', ''))
ipv6 = opts.get('ipv6', args.get('ipv6', ''))
infos = salt.utils.odict.OrderedDict([
('lxc.network.type', {
'test': not type_,
'value': type_,
'old': old_if.get('lxc.network.type'),
'default': 'veth'}),
('lxc.network.name', {
'test': False,
'value': dev,
'old': dev,
'default': dev}),
('lxc.network.flags', {
'test': not flags,
'value': flags,
'old': old_if.get('lxc.network.flags'),
'default': 'up'}),
('lxc.network.link', {
'test': not link,
'value': link,
'old': old_if.get('lxc.network.link'),
'default': search_lxc_bridge()}),
('lxc.network.hwaddr', {
'test': not mac,
'value': mac,
'old': old_if.get('lxc.network.hwaddr'),
'default': salt.utils.network.gen_mac()}),
('lxc.network.ipv4', {
'test': not ipv4,
'value': ipv4,
'old': old_if.get('lxc.network.ipv4', ''),
'default': None}),
('lxc.network.ipv6', {
'test': not ipv6,
'value': ipv6,
'old': old_if.get('lxc.network.ipv6', ''),
'default': None})])
# for each parameter, if not explicitly set, the
# config value present in the LXC configuration should
# take precedence over the profile configuration
for info in list(infos.keys()):
bundle = infos[info]
if bundle['test']:
if bundle['old']:
bundle['value'] = bundle['old']
elif bundle['default']:
bundle['value'] = bundle['default']
for info, data in six.iteritems(infos):
if data['value']:
ret.append({info: data['value']})
for key, val in six.iteritems(args):
if key == 'link' and bridge:
val = bridge
val = opts.get(key, val)
if key in [
'type', 'flags', 'name',
'gateway', 'mac', 'link', 'ipv4', 'ipv6'
]:
continue
ret.append({'lxc.network.{0}'.format(key): val})
# gateway (in automode) must be appended following network conf !
if not gateway:
gateway = args.get('gateway', None)
if gateway is not None and not gateway_set:
ret.append({'lxc.network.ipv4.gateway': gateway})
# only one network gateway ;)
gateway_set = True
# normally, this won't happen
# set the gateway if specified even if we did
# not managed the network underlying
if gateway is not None and not gateway_set:
ret.append({'lxc.network.ipv4.gateway': gateway})
# only one network gateway ;)
gateway_set = True
new = _get_veths(ret)
# verify that we did not loose the mac settings
for iface in [a for a in new]:
ndata = new[iface]
nmac = ndata.get('lxc.network.hwaddr', '')
ntype = ndata.get('lxc.network.type', '')
omac, otype = '', ''
if iface in old:
odata = old[iface]
omac = odata.get('lxc.network.hwaddr', '')
otype = odata.get('lxc.network.type', '')
# default for network type is setted here
# attention not to change the network type
# without a good and explicit reason to.
if otype and not ntype:
ntype = otype
if not ntype:
ntype = 'veth'
new[iface]['lxc.network.type'] = ntype
if omac and not nmac:
new[iface]['lxc.network.hwaddr'] = omac
ret = []
for val in six.itervalues(new):
for row in val:
ret.append(salt.utils.odict.OrderedDict([(row, val[row])]))
# on old versions of lxc, still support the gateway auto mode
# if we didn't explicitly say no to
# (lxc.network.ipv4.gateway: auto)
if _LooseVersion(version()) <= _LooseVersion('1.0.7') and \
True not in ['lxc.network.ipv4.gateway' in a for a in ret] and \
True in ['lxc.network.ipv4' in a for a in ret]:
ret.append({'lxc.network.ipv4.gateway': 'auto'})
return ret
def _get_lxc_default_data(**kwargs):
kwargs = copy.deepcopy(kwargs)
ret = {}
for k in ['utsname', 'rootfs']:
val = kwargs.get(k, None)
if val is not None:
ret['lxc.{0}'.format(k)] = val
autostart = kwargs.get('autostart')
# autostart can have made in kwargs, but with the None
# value which is invalid, we need an explicit boolean
# autostart = on is the default.
if autostart is None:
autostart = True
# we will set the regular lxc marker to restart container at
# machine (re)boot only if we did not explicitly ask
# not to touch to the autostart settings via
# autostart == 'keep'
if autostart != 'keep':
if autostart:
ret['lxc.start.auto'] = '1'
else:
ret['lxc.start.auto'] = '0'
memory = kwargs.get('memory')
if memory is not None:
# converting the config value from MB to bytes
ret['lxc.cgroup.memory.limit_in_bytes'] = memory * 1024 * 1024
cpuset = kwargs.get('cpuset')
if cpuset:
ret['lxc.cgroup.cpuset.cpus'] = cpuset
cpushare = kwargs.get('cpushare')
cpu = kwargs.get('cpu')
if cpushare:
ret['lxc.cgroup.cpu.shares'] = cpushare
if cpu and not cpuset:
ret['lxc.cgroup.cpuset.cpus'] = _rand_cpu_str(cpu)
return ret
def _config_list(conf_tuples=None, only_net=False, **kwargs):
'''
Return a list of dicts from the salt level configurations
conf_tuples
_LXCConfig compatible list of entries which can contain
- string line
- tuple (lxc config param,value)
- dict of one entry: {lxc config param: value)
only_net
by default we add to the tuples a reflection of both
the real config if avalaible and a certain amount of
default values like the cpu parameters, the memory
and etc.
On the other hand, we also no matter the case reflect
the network configuration computed from the actual config if
available and given values.
if no_default_loads is set, we will only
reflect the network configuration back to the conf tuples
list
'''
# explicit cast
only_net = bool(only_net)
if not conf_tuples:
conf_tuples = []
kwargs = copy.deepcopy(kwargs)
ret = []
if not only_net:
default_data = _get_lxc_default_data(**kwargs)
for k, val in six.iteritems(default_data):
ret.append({k: val})
net_datas = _network_conf(conf_tuples=conf_tuples, **kwargs)
ret.extend(net_datas)
return ret
def _get_veths(net_data):
'''
Parse the nic setup inside lxc conf tuples back to a dictionary indexed by
network interface
'''
if isinstance(net_data, dict):
net_data = list(net_data.items())
nics = salt.utils.odict.OrderedDict()
current_nic = salt.utils.odict.OrderedDict()
no_names = True
for item in net_data:
if item and isinstance(item, dict):
item = list(item.items())[0]
# skip LXC configuration comment lines, and play only with tuples conf
elif isinstance(item, six.string_types):
# deal with reflection of commented lxc configs
sitem = item.strip()
if sitem.startswith('#') or not sitem:
continue
elif '=' in item:
item = tuple([a.strip() for a in item.split('=', 1)])
if item[0] == 'lxc.network.type':
current_nic = salt.utils.odict.OrderedDict()
if item[0] == 'lxc.network.name':
no_names = False
nics[item[1].strip()] = current_nic
current_nic[item[0].strip()] = item[1].strip()
# if not ethernet card name has been collected, assuming we collected
# data for eth0
if no_names and current_nic:
nics[DEFAULT_NIC] = current_nic
return nics
class _LXCConfig(object):
'''
LXC configuration data
'''
pattern = re.compile(r'^(\S+)(\s*)(=)(\s*)(.*)')
non_interpretable_pattern = re.compile(r'^((#.*)|(\s*))$')
def __init__(self, **kwargs):
kwargs = copy.deepcopy(kwargs)
self.name = kwargs.pop('name', None)
path = get_root_path(kwargs.get('path', None))
self.data = []
if self.name:
self.path = os.path.join(path, self.name, 'config')
if os.path.isfile(self.path):
with salt.utils.files.fopen(self.path) as fhr:
for line in salt.utils.data.decode(fhr.readlines()):
match = self.pattern.findall((line.strip()))
if match:
self.data.append((match[0][0], match[0][-1]))
match = self.non_interpretable_pattern.findall(
(line.strip()))
if match:
self.data.append(('', match[0][0]))
else:
self.path = None
def _replace(key, val):
if val:
self._filter_data(key)
self.data.append((key, val))
default_data = _get_lxc_default_data(**kwargs)
for key, val in six.iteritems(default_data):
_replace(key, val)
old_net = self._filter_data('lxc.network')
net_datas = _network_conf(conf_tuples=old_net, **kwargs)
if net_datas:
for row in net_datas:
self.data.extend(list(row.items()))
# be sure to reset harmful settings
for idx in ['lxc.cgroup.memory.limit_in_bytes']:
if not default_data.get(idx):
self._filter_data(idx)
def as_string(self):
chunks = ('{0[0]}{1}{0[1]}'.format(item, (' = ' if item[0] else '')) for item in self.data)
return '\n'.join(chunks) + '\n'
def write(self):
if self.path:
content = self.as_string()
# 2 step rendering to be sure not to open/wipe the config
# before as_string succeeds.
with salt.utils.files.fopen(self.path, 'w') as fic:
fic.write(salt.utils.stringutils.to_str(content))
fic.flush()
def tempfile(self):
# this might look like the function name is shadowing the
# module, but it's not since the method belongs to the class
ntf = tempfile.NamedTemporaryFile()
ntf.write(self.as_string())
ntf.flush()
return ntf
def _filter_data(self, pattern):
'''
Removes parameters which match the pattern from the config data
'''
removed = []
filtered = []
for param in self.data:
if not param[0].startswith(pattern):
filtered.append(param)
else:
removed.append(param)
self.data = filtered
return removed
def _get_base(**kwargs):
'''
If the needed base does not exist, then create it, if it does exist
create nothing and return the name of the base lxc container so
it can be cloned.
'''
profile = get_container_profile(copy.deepcopy(kwargs.get('profile')))
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, _marker)
profile_match = profile.pop(key, default)
# let kwarg overrides be the preferred choice
if kw_overrides_match is _marker:
return profile_match
return kw_overrides_match
template = select('template')
image = select('image')
vgname = select('vgname')
path = kwargs.get('path', None)
# remove the above three variables from kwargs, if they exist, to avoid
# duplicates if create() is invoked below.
for param in ('path', 'image', 'vgname', 'template'):
kwargs.pop(param, None)
if image:
proto = _urlparse(image).scheme
img_tar = __salt__['cp.cache_file'](image)
img_name = os.path.basename(img_tar)
hash_ = salt.utils.hashutils.get_hash(
img_tar,
__salt__['config.get']('hash_type'))
name = '__base_{0}_{1}_{2}'.format(proto, img_name, hash_)
if not exists(name, path=path):
create(name, template=template, image=image,
path=path, vgname=vgname, **kwargs)
if vgname:
rootfs = os.path.join('/dev', vgname, name)
edit_conf(info(name, path=path)['config'],
out_format='commented', **{'lxc.rootfs': rootfs})
return name
elif template:
name = '__base_{0}'.format(template)
if not exists(name, path=path):
create(name, template=template, image=image, path=path,
vgname=vgname, **kwargs)
if vgname:
rootfs = os.path.join('/dev', vgname, name)
edit_conf(info(name, path=path)['config'],
out_format='commented', **{'lxc.rootfs': rootfs})
return name
return ''
def init(name,
config=None,
cpuset=None,
cpushare=None,
memory=None,
profile=None,
network_profile=None,
nic_opts=None,
cpu=None,
autostart=True,
password=None,
password_encrypted=None,
users=None,
dnsservers=None,
searchdomains=None,
bridge=None,
gateway=None,
pub_key=None,
priv_key=None,
force_install=False,
unconditional_install=False,
bootstrap_delay=None,
bootstrap_args=None,
bootstrap_shell=None,
bootstrap_url=None,
**kwargs):
'''
Initialize a new container.
This is a partial idempotent function as if it is already provisioned, we
will reset a bit the lxc configuration file but much of the hard work will
be escaped as markers will prevent re-execution of harmful tasks.
name
Name of the container
image
A tar archive to use as the rootfs for the container. Conflicts with
the ``template`` argument.
cpus
Select a random number of cpu cores and assign it to the cpuset, if the
cpuset option is set then this option will be ignored
cpuset
Explicitly define the cpus this container will be bound to
cpushare
cgroups cpu shares
autostart
autostart container on reboot
memory
cgroups memory limit, in MB
.. versionchanged:: 2015.5.0
If no value is passed, no limit is set. In earlier Salt versions,
not passing this value causes a 1024MB memory limit to be set, and
it was necessary to pass ``memory=0`` to set no limit.
gateway
the ipv4 gateway to use
the default does nothing more than lxcutils does
bridge
the bridge to use
the default does nothing more than lxcutils does
network_profile
Network profile to use for the container
.. versionadded:: 2015.5.0
nic_opts
Extra options for network interfaces, will override
``{"eth0": {"hwaddr": "aa:bb:cc:dd:ee:ff", "ipv4": "10.1.1.1", "ipv6": "2001:db8::ff00:42:8329"}}``
or
``{"eth0": {"hwaddr": "aa:bb:cc:dd:ee:ff", "ipv4": "10.1.1.1/24", "ipv6": "2001:db8::ff00:42:8329"}}``
users
Users for which the password defined in the ``password`` param should
be set. Can be passed as a comma separated list or a python list.
Defaults to just the ``root`` user.
password
Set the initial password for the users defined in the ``users``
parameter
password_encrypted : False
Set to ``True`` to denote a password hash instead of a plaintext
password
.. versionadded:: 2015.5.0
profile
A LXC profile (defined in config or pillar).
This can be either a real profile mapping or a string
to retrieve it in configuration
start
Start the newly-created container
dnsservers
list of dns servers to set in the container, default [] (no setting)
seed
Seed the container with the minion config. Default: ``True``
install
If salt-minion is not already installed, install it. Default: ``True``
config
Optional config parameters. By default, the id is set to
the name of the container.
master
salt master (default to minion's master)
master_port
salt master port (default to minion's master port)
pub_key
Explicit public key to preseed the minion with (optional).
This can be either a filepath or a string representing the key
priv_key
Explicit private key to preseed the minion with (optional).
This can be either a filepath or a string representing the key
approve_key
If explicit preseeding is not used;
Attempt to request key approval from the master. Default: ``True``
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
clone_from
Original from which to use a clone operation to create the container.
Default: ``None``
bootstrap_delay
Delay in seconds between end of container creation and bootstrapping.
Useful when waiting for container to obtain a DHCP lease.
.. versionadded:: 2015.5.0
bootstrap_url
See lxc.bootstrap
bootstrap_shell
See lxc.bootstrap
bootstrap_args
See lxc.bootstrap
force_install
Force installation even if salt-minion is detected,
this is the way to run vendor bootstrap scripts even
if a salt minion is already present in the container
unconditional_install
Run the script even if the container seems seeded
CLI Example:
.. code-block:: bash
salt 'minion' lxc.init name [cpuset=cgroups_cpuset] \\
[cpushare=cgroups_cpushare] [memory=cgroups_memory] \\
[nic=nic_profile] [profile=lxc_profile] \\
[nic_opts=nic_opts] [start=(True|False)] \\
[seed=(True|False)] [install=(True|False)] \\
[config=minion_config] [approve_key=(True|False) \\
[clone_from=original] [autostart=True] \\
[priv_key=/path_or_content] [pub_key=/path_or_content] \\
[bridge=lxcbr0] [gateway=10.0.3.1] \\
[dnsservers[dns1,dns2]] \\
[users=[foo]] [password='secret'] \\
[password_encrypted=(True|False)]
'''
ret = {'name': name,
'changes': {}}
profile = get_container_profile(copy.deepcopy(profile))
if not network_profile:
network_profile = profile.get('network_profile')
if not network_profile:
network_profile = DEFAULT_NIC
# Changes is a pointer to changes_dict['init']. This method is used so that
# we can have a list of changes as they are made, providing an ordered list
# of things that were changed.
changes_dict = {'init': []}
changes = changes_dict.get('init')
if users is None:
users = []
dusers = ['root']
for user in dusers:
if user not in users:
users.append(user)
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, _marker)
profile_match = profile.pop(key, default)
# let kwarg overrides be the preferred choice
if kw_overrides_match is _marker:
return profile_match
return kw_overrides_match
path = select('path')
bpath = get_root_path(path)
state_pre = state(name, path=path)
tvg = select('vgname')
vgname = tvg if tvg else __salt__['config.get']('lxc.vgname')
start_ = select('start', True)
autostart = select('autostart', autostart)
seed = select('seed', True)
install = select('install', True)
seed_cmd = select('seed_cmd')
salt_config = _get_salt_config(config, **kwargs)
approve_key = select('approve_key', True)
clone_from = select('clone_from')
# If using a volume group then set up to make snapshot cow clones
if vgname and not clone_from:
try:
kwargs['vgname'] = vgname
clone_from = _get_base(profile=profile, **kwargs)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = exc.strerror
if changes:
ret['changes'] = changes_dict
return ret
if not kwargs.get('snapshot') is False:
kwargs['snapshot'] = True
does_exist = exists(name, path=path)
to_reboot = False
remove_seed_marker = False
if does_exist:
pass
elif clone_from:
remove_seed_marker = True
try:
clone(name, clone_from, profile=profile, **kwargs)
changes.append({'create': 'Container cloned'})
except (SaltInvocationError, CommandExecutionError) as exc:
if 'already exists' in exc.strerror:
changes.append({'create': 'Container already exists'})
else:
ret['result'] = False
ret['comment'] = exc.strerror
if changes:
ret['changes'] = changes_dict
return ret
cfg = _LXCConfig(name=name, network_profile=network_profile,
nic_opts=nic_opts, bridge=bridge, path=path,
gateway=gateway, autostart=autostart,
cpuset=cpuset, cpushare=cpushare, memory=memory)
old_chunks = read_conf(cfg.path, out_format='commented')
cfg.write()
chunks = read_conf(cfg.path, out_format='commented')
if old_chunks != chunks:
to_reboot = True
else:
remove_seed_marker = True
cfg = _LXCConfig(network_profile=network_profile,
nic_opts=nic_opts, cpuset=cpuset, path=path,
bridge=bridge, gateway=gateway,
autostart=autostart,
cpushare=cpushare, memory=memory)
with cfg.tempfile() as cfile:
try:
create(name, config=cfile.name, profile=profile, **kwargs)
changes.append({'create': 'Container created'})
except (SaltInvocationError, CommandExecutionError) as exc:
if 'already exists' in exc.strerror:
changes.append({'create': 'Container already exists'})
else:
ret['comment'] = exc.strerror
if changes:
ret['changes'] = changes_dict
return ret
cpath = os.path.join(bpath, name, 'config')
old_chunks = []
if os.path.exists(cpath):
old_chunks = read_conf(cpath, out_format='commented')
new_cfg = _config_list(conf_tuples=old_chunks,
cpu=cpu,
network_profile=network_profile,
nic_opts=nic_opts, bridge=bridge,
cpuset=cpuset, cpushare=cpushare,
memory=memory)
if new_cfg:
edit_conf(cpath, out_format='commented', lxc_config=new_cfg)
chunks = read_conf(cpath, out_format='commented')
if old_chunks != chunks:
to_reboot = True
# last time to be sure any of our property is correctly applied
cfg = _LXCConfig(name=name, network_profile=network_profile,
nic_opts=nic_opts, bridge=bridge, path=path,
gateway=gateway, autostart=autostart,
cpuset=cpuset, cpushare=cpushare, memory=memory)
old_chunks = []
if os.path.exists(cfg.path):
old_chunks = read_conf(cfg.path, out_format='commented')
cfg.write()
chunks = read_conf(cfg.path, out_format='commented')
if old_chunks != chunks:
changes.append({'config': 'Container configuration updated'})
to_reboot = True
if to_reboot:
try:
stop(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
if changes:
ret['changes'] = changes_dict
return ret
if not does_exist or (does_exist and state(name, path=path) != 'running'):
try:
start(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
if changes:
ret['changes'] = changes_dict
return ret
if remove_seed_marker:
run(name,
'rm -f \'{0}\''.format(SEED_MARKER),
path=path,
chroot_fallback=False,
python_shell=False)
# set the default user/password, only the first time
if ret.get('result', True) and password:
gid = '/.lxc.initial_pass'
gids = [gid,
'/lxc.initial_pass',
'/.lxc.{0}.initial_pass'.format(name)]
if not any(retcode(name,
'test -e "{0}"'.format(x),
chroot_fallback=True,
path=path,
ignore_retcode=True) == 0
for x in gids):
# think to touch the default user generated by default templates
# which has a really unsecure passwords...
# root is defined as a member earlier in the code
for default_user in ['ubuntu']:
if (
default_user not in users and
retcode(name,
'id {0}'.format(default_user),
python_shell=False,
path=path,
chroot_fallback=True,
ignore_retcode=True) == 0
):
users.append(default_user)
for user in users:
try:
cret = set_password(name,
users=[user],
path=path,
password=password,
encrypted=password_encrypted)
except (SaltInvocationError, CommandExecutionError) as exc:
msg = '{0}: Failed to set password'.format(
user) + exc.strerror
# only hardfail in unrecoverable situation:
# root cannot be setted up
if user == 'root':
ret['comment'] = msg
ret['result'] = False
else:
log.debug(msg)
if ret.get('result', True):
changes.append({'password': 'Password(s) updated'})
if retcode(name,
('sh -c \'touch "{0}"; test -e "{0}"\''
.format(gid)),
path=path,
chroot_fallback=True,
ignore_retcode=True) != 0:
ret['comment'] = 'Failed to set password marker'
changes[-1]['password'] += '. ' + ret['comment'] + '.'
ret['result'] = False
# set dns servers if any, only the first time
if ret.get('result', True) and dnsservers:
# retro compatibility, test also old markers
gid = '/.lxc.initial_dns'
gids = [gid,
'/lxc.initial_dns',
'/lxc.{0}.initial_dns'.format(name)]
if not any(retcode(name,
'test -e "{0}"'.format(x),
chroot_fallback=True,
path=path,
ignore_retcode=True) == 0
for x in gids):
try:
set_dns(name,
path=path,
dnsservers=dnsservers,
searchdomains=searchdomains)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Failed to set DNS: ' + exc.strerror
ret['result'] = False
else:
changes.append({'dns': 'DNS updated'})
if retcode(name,
('sh -c \'touch "{0}"; test -e "{0}"\''
.format(gid)),
chroot_fallback=True,
path=path,
ignore_retcode=True) != 0:
ret['comment'] = 'Failed to set DNS marker'
changes[-1]['dns'] += '. ' + ret['comment'] + '.'
ret['result'] = False
# retro compatibility, test also old markers
if remove_seed_marker:
run(name,
'rm -f \'{0}\''.format(SEED_MARKER),
path=path,
python_shell=False)
gid = '/.lxc.initial_seed'
gids = [gid, '/lxc.initial_seed']
if (
any(retcode(name,
'test -e {0}'.format(x),
path=path,
chroot_fallback=True,
ignore_retcode=True) == 0
for x in gids) or not ret.get('result', True)
):
pass
elif seed or seed_cmd:
if seed:
try:
result = bootstrap(
name, config=salt_config, path=path,
approve_key=approve_key,
pub_key=pub_key, priv_key=priv_key,
install=install,
force_install=force_install,
unconditional_install=unconditional_install,
bootstrap_delay=bootstrap_delay,
bootstrap_url=bootstrap_url,
bootstrap_shell=bootstrap_shell,
bootstrap_args=bootstrap_args)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Bootstrap failed: ' + exc.strerror
ret['result'] = False
else:
if not result:
ret['comment'] = ('Bootstrap failed, see minion log for '
'more information')
ret['result'] = False
else:
changes.append(
{'bootstrap': 'Container successfully bootstrapped'}
)
elif seed_cmd:
try:
result = __salt__[seed_cmd](info(name, path=path)['rootfs'],
name,
salt_config)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = ('Bootstrap via seed_cmd \'{0}\' failed: {1}'
.format(seed_cmd, exc.strerror))
ret['result'] = False
else:
if not result:
ret['comment'] = ('Bootstrap via seed_cmd \'{0}\' failed, '
'see minion log for more information '
.format(seed_cmd))
ret['result'] = False
else:
changes.append(
{'bootstrap': 'Container successfully bootstrapped '
'using seed_cmd \'{0}\''
.format(seed_cmd)}
)
if ret.get('result', True) and not start_:
try:
stop(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
ret['result'] = False
state_post = state(name, path=path)
if state_pre != state_post:
changes.append({'state': {'old': state_pre, 'new': state_post}})
if ret.get('result', True):
ret['comment'] = ('Container \'{0}\' successfully initialized'
.format(name))
ret['result'] = True
if changes:
ret['changes'] = changes_dict
return ret
def cloud_init(name, vm_=None, **kwargs):
'''
Thin wrapper to lxc.init to be used from the saltcloud lxc driver
name
Name of the container
may be None and then guessed from saltcloud mapping
`vm_`
saltcloud mapping defaults for the vm
CLI Example:
.. code-block:: bash
salt '*' lxc.cloud_init foo
'''
init_interface = cloud_init_interface(name, vm_, **kwargs)
name = init_interface.pop('name', name)
return init(name, **init_interface)
def images(dist=None):
'''
.. versionadded:: 2015.5.0
List the available images for LXC's ``download`` template.
dist : None
Filter results to a single Linux distribution
CLI Examples:
.. code-block:: bash
salt myminion lxc.images
salt myminion lxc.images dist=centos
'''
out = __salt__['cmd.run_stdout'](
'lxc-create -n __imgcheck -t download -- --list',
ignore_retcode=True
)
if 'DIST' not in out:
raise CommandExecutionError(
'Unable to run the \'download\' template script. Is it installed?'
)
ret = {}
passed_header = False
for line in out.splitlines():
try:
distro, release, arch, variant, build_time = line.split()
except ValueError:
continue
if not passed_header:
if distro == 'DIST':
passed_header = True
continue
dist_list = ret.setdefault(distro, [])
dist_list.append({
'release': release,
'arch': arch,
'variant': variant,
'build_time': build_time,
})
if dist is not None:
return dict([(dist, ret.get(dist, []))])
return ret
def templates():
'''
.. versionadded:: 2015.5.0
List the available LXC template scripts installed on the minion
CLI Examples:
.. code-block:: bash
salt myminion lxc.templates
'''
try:
template_scripts = os.listdir('/usr/share/lxc/templates')
except OSError:
return []
else:
return [x[4:] for x in template_scripts if x.startswith('lxc-')]
def _after_ignition_network_profile(cmd,
ret,
name,
network_profile,
path,
nic_opts):
_clear_context()
if ret['retcode'] == 0 and exists(name, path=path):
if network_profile:
network_changes = apply_network_profile(name,
network_profile,
path=path,
nic_opts=nic_opts)
if network_changes:
log.info(
'Network changes from applying network profile \'%s\' '
'to newly-created container \'%s\':\n%s',
network_profile, name, network_changes
)
c_state = state(name, path=path)
return {'result': True,
'state': {'old': None, 'new': c_state}}
else:
if exists(name, path=path):
# destroy the container if it was partially created
cmd = 'lxc-destroy'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0}'.format(name)
__salt__['cmd.retcode'](cmd, python_shell=False)
raise CommandExecutionError(
'Container could not be created with cmd \'{0}\': {1}'
.format(cmd, ret['stderr'])
)
def create(name,
config=None,
profile=None,
network_profile=None,
nic_opts=None,
**kwargs):
'''
Create a new container.
name
Name of the container
config
The config file to use for the container. Defaults to system-wide
config (usually in /etc/lxc/lxc.conf).
profile
Profile to use in container creation (see
:mod:`lxc.get_container_profile
<salt.modules.lxc.get_container_profile>`). Values in a profile will be
overridden by the **Container Creation Arguments** listed below.
network_profile
Network profile to use for container
.. versionadded:: 2015.5.0
**Container Creation Arguments**
template
The template to use. For example, ``ubuntu`` or ``fedora``.
For a full list of available templates, check out
the :mod:`lxc.templates <salt.modules.lxc.templates>` function.
Conflicts with the ``image`` argument.
.. note::
The ``download`` template requires the following three parameters
to be defined in ``options``:
* **dist** - The name of the distribution
* **release** - Release name/version
* **arch** - Architecture of the container
The available images can be listed using the :mod:`lxc.images
<salt.modules.lxc.images>` function.
options
Template-specific options to pass to the lxc-create command. These
correspond to the long options (ones beginning with two dashes) that
the template script accepts. For example:
.. code-block:: bash
options='{"dist": "centos", "release": "6", "arch": "amd64"}'
For available template options, refer to the lxc template scripts
which are ususally located under ``/usr/share/lxc/templates``,
or run ``lxc-create -t <template> -h``.
image
A tar archive to use as the rootfs for the container. Conflicts with
the ``template`` argument.
backing
The type of storage to use. Set to ``lvm`` to use an LVM group.
Defaults to filesystem within /var/lib/lxc.
fstype
Filesystem type to use on LVM logical volume
size : 1G
Size of the volume to create. Only applicable if ``backing=lvm``.
vgname : lxc
Name of the LVM volume group in which to create the volume for this
container. Only applicable if ``backing=lvm``.
lvname
Name of the LVM logical volume in which to create the volume for this
container. Only applicable if ``backing=lvm``.
thinpool
Name of a pool volume that will be used for thin-provisioning this
container. Only applicable if ``backing=lvm``.
nic_opts
give extra opts overriding network profile values
path
parent path for the container creation (default: /var/lib/lxc)
zfsroot
Name of the ZFS root in which to create the volume for this container.
Only applicable if ``backing=zfs``. (default: tank/lxc)
.. versionadded:: 2015.8.0
'''
# Required params for 'download' template
download_template_deps = ('dist', 'release', 'arch')
cmd = 'lxc-create -n {0}'.format(name)
profile = get_container_profile(copy.deepcopy(profile))
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, None)
profile_match = profile.pop(key, default)
# Return the profile match if the the kwarg match was None, as the
# lxc.present state will pass these kwargs set to None by default.
if kw_overrides_match is None:
return profile_match
return kw_overrides_match
path = select('path')
if exists(name, path=path):
raise CommandExecutionError(
'Container \'{0}\' already exists'.format(name)
)
tvg = select('vgname')
vgname = tvg if tvg else __salt__['config.get']('lxc.vgname')
# The 'template' and 'image' params conflict
template = select('template')
image = select('image')
if template and image:
raise SaltInvocationError(
'Only one of \'template\' and \'image\' is permitted'
)
elif not any((template, image, profile)):
raise SaltInvocationError(
'At least one of \'template\', \'image\', and \'profile\' is '
'required'
)
options = select('options') or {}
backing = select('backing')
if vgname and not backing:
backing = 'lvm'
lvname = select('lvname')
thinpool = select('thinpool')
fstype = select('fstype')
size = select('size', '1G')
zfsroot = select('zfsroot')
if backing in ('dir', 'overlayfs', 'btrfs', 'zfs'):
fstype = None
size = None
# some backends won't support some parameters
if backing in ('aufs', 'dir', 'overlayfs', 'btrfs'):
lvname = vgname = thinpool = None
if image:
img_tar = __salt__['cp.cache_file'](image)
template = os.path.join(
os.path.dirname(salt.__file__),
'templates',
'lxc',
'salt_tarball')
options['imgtar'] = img_tar
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
if not os.path.exists(path):
os.makedirs(path)
if config:
cmd += ' -f {0}'.format(config)
if template:
cmd += ' -t {0}'.format(template)
if backing:
backing = backing.lower()
cmd += ' -B {0}'.format(backing)
if backing in ('zfs',):
if zfsroot:
cmd += ' --zfsroot {0}'.format(zfsroot)
if backing in ('lvm',):
if lvname:
cmd += ' --lvname {0}'.format(lvname)
if vgname:
cmd += ' --vgname {0}'.format(vgname)
if thinpool:
cmd += ' --thinpool {0}'.format(thinpool)
if backing not in ('dir', 'overlayfs'):
if fstype:
cmd += ' --fstype {0}'.format(fstype)
if size:
cmd += ' --fssize {0}'.format(size)
if options:
if template == 'download':
missing_deps = [x for x in download_template_deps
if x not in options]
if missing_deps:
raise SaltInvocationError(
'Missing params in \'options\' dict: {0}'
.format(', '.join(missing_deps))
)
cmd += ' --'
for key, val in six.iteritems(options):
cmd += ' --{0} {1}'.format(key, val)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
# please do not merge extra conflicting stuff
# inside those two line (ret =, return)
return _after_ignition_network_profile(cmd,
ret,
name,
network_profile,
path,
nic_opts)
def clone(name,
orig,
profile=None,
network_profile=None,
nic_opts=None,
**kwargs):
'''
Create a new container as a clone of another container
name
Name of the container
orig
Name of the original container to be cloned
profile
Profile to use in container cloning (see
:mod:`lxc.get_container_profile
<salt.modules.lxc.get_container_profile>`). Values in a profile will be
overridden by the **Container Cloning Arguments** listed below.
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
**Container Cloning Arguments**
snapshot
Use Copy On Write snapshots (LVM)
size : 1G
Size of the volume to create. Only applicable if ``backing=lvm``.
backing
The type of storage to use. Set to ``lvm`` to use an LVM group.
Defaults to filesystem within /var/lib/lxc.
network_profile
Network profile to use for container
.. versionadded:: 2015.8.0
nic_opts
give extra opts overriding network profile values
.. versionadded:: 2015.8.0
CLI Examples:
.. code-block:: bash
salt '*' lxc.clone myclone orig=orig_container
salt '*' lxc.clone myclone orig=orig_container snapshot=True
'''
profile = get_container_profile(copy.deepcopy(profile))
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, None)
profile_match = profile.pop(key, default)
# let kwarg overrides be the preferred choice
if kw_overrides_match is None:
return profile_match
return kw_overrides_match
path = select('path')
if exists(name, path=path):
raise CommandExecutionError(
'Container \'{0}\' already exists'.format(name)
)
_ensure_exists(orig, path=path)
if state(orig, path=path) != 'stopped':
raise CommandExecutionError(
'Container \'{0}\' must be stopped to be cloned'.format(orig)
)
backing = select('backing')
snapshot = select('snapshot')
if backing in ('dir',):
snapshot = False
if not snapshot:
snapshot = ''
else:
snapshot = '-s'
size = select('size', '1G')
if backing in ('dir', 'overlayfs', 'btrfs'):
size = None
# LXC commands and options changed in 2.0 - CF issue #34086 for details
if _LooseVersion(version()) >= _LooseVersion('2.0'):
# https://linuxcontainers.org/lxc/manpages//man1/lxc-copy.1.html
cmd = 'lxc-copy'
cmd += ' {0} -n {1} -N {2}'.format(snapshot, orig, name)
else:
# https://linuxcontainers.org/lxc/manpages//man1/lxc-clone.1.html
cmd = 'lxc-clone'
cmd += ' {0} -o {1} -n {2}'.format(snapshot, orig, name)
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
if not os.path.exists(path):
os.makedirs(path)
if backing:
backing = backing.lower()
cmd += ' -B {0}'.format(backing)
if backing not in ('dir', 'overlayfs'):
if size:
cmd += ' -L {0}'.format(size)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
# please do not merge extra conflicting stuff
# inside those two line (ret =, return)
return _after_ignition_network_profile(cmd,
ret,
name,
network_profile,
path,
nic_opts)
def ls_(active=None, cache=True, path=None):
'''
Return a list of the containers available on the minion
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
active
If ``True``, return only active (i.e. running) containers
.. versionadded:: 2015.5.0
CLI Example:
.. code-block:: bash
salt '*' lxc.ls
salt '*' lxc.ls active=True
'''
contextvar = 'lxc.ls{0}'.format(path)
if active:
contextvar += '.active'
if cache and (contextvar in __context__):
return __context__[contextvar]
else:
ret = []
cmd = 'lxc-ls'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
if active:
cmd += ' --active'
output = __salt__['cmd.run_stdout'](cmd, python_shell=False)
for line in output.splitlines():
ret.extend(line.split())
__context__[contextvar] = ret
return ret
def list_(extra=False, limit=None, path=None):
'''
List containers classified by state
extra
Also get per-container specific info. This will change the return data.
Instead of returning a list of containers, a dictionary of containers
and each container's output from :mod:`lxc.info
<salt.modules.lxc.info>`.
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
limit
Return output matching a specific state (**frozen**, **running**, or
**stopped**).
.. versionadded:: 2015.5.0
CLI Examples:
.. code-block:: bash
salt '*' lxc.list
salt '*' lxc.list extra=True
salt '*' lxc.list limit=running
'''
ctnrs = ls_(path=path)
if extra:
stopped = {}
frozen = {}
running = {}
else:
stopped = []
frozen = []
running = []
ret = {'running': running,
'stopped': stopped,
'frozen': frozen}
for container in ctnrs:
cmd = 'lxc-info'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0}'.format(container)
c_info = __salt__['cmd.run'](
cmd,
python_shell=False,
output_loglevel='debug'
)
c_state = None
for line in c_info.splitlines():
stat = line.split(':')
if stat[0] in ('State', 'state'):
c_state = stat[1].strip()
break
if not c_state or (limit is not None and c_state.lower() != limit):
continue
if extra:
infos = info(container, path=path)
method = 'update'
value = {container: infos}
else:
method = 'append'
value = container
if c_state == 'STOPPED':
getattr(stopped, method)(value)
continue
if c_state == 'FROZEN':
getattr(frozen, method)(value)
continue
if c_state == 'RUNNING':
getattr(running, method)(value)
continue
if limit is not None:
return ret.get(limit, {} if extra else [])
return ret
def _change_state(cmd,
name,
expected,
stdin=_marker,
stdout=_marker,
stderr=_marker,
with_communicate=_marker,
use_vt=_marker,
path=None):
pre = state(name, path=path)
if pre == expected:
return {'result': True,
'state': {'old': expected, 'new': expected},
'comment': 'Container \'{0}\' already {1}'
.format(name, expected)}
if cmd == 'lxc-destroy':
# Kill the container first
scmd = 'lxc-stop'
if path:
scmd += ' -P {0}'.format(pipes.quote(path))
scmd += ' -k -n {0}'.format(name)
__salt__['cmd.run'](scmd,
python_shell=False)
if path and ' -P ' not in cmd:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0}'.format(name)
# certain lxc commands need to be taken with care (lxc-start)
# as te command itself mess with double forks; we must not
# communicate with it, but just wait for the exit status
pkwargs = {'python_shell': False,
'redirect_stderr': True,
'with_communicate': with_communicate,
'use_vt': use_vt,
'stdin': stdin,
'stdout': stdout}
for i in [a for a in pkwargs]:
val = pkwargs[i]
if val is _marker:
pkwargs.pop(i, None)
_cmdout = __salt__['cmd.run_all'](cmd, **pkwargs)
if _cmdout['retcode'] != 0:
raise CommandExecutionError(
'Error changing state for container \'{0}\' using command '
'\'{1}\': {2}'.format(name, cmd, _cmdout['stdout'])
)
if expected is not None:
# some commands do not wait, so we will
rcmd = 'lxc-wait'
if path:
rcmd += ' -P {0}'.format(pipes.quote(path))
rcmd += ' -n {0} -s {1}'.format(name, expected.upper())
__salt__['cmd.run'](rcmd, python_shell=False, timeout=30)
_clear_context()
post = state(name, path=path)
ret = {'result': post == expected,
'state': {'old': pre, 'new': post}}
return ret
def _ensure_exists(name, path=None):
'''
Raise an exception if the container does not exist
'''
if not exists(name, path=path):
raise CommandExecutionError(
'Container \'{0}\' does not exist'.format(name)
)
def _ensure_running(name, no_start=False, path=None):
'''
If the container is not currently running, start it. This function returns
the state that the container was in before changing
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
'''
_ensure_exists(name, path=path)
pre = state(name, path=path)
if pre == 'running':
# This will be a no-op but running the function will give us a pretty
# return dict.
return start(name, path=path)
elif pre == 'stopped':
if no_start:
raise CommandExecutionError(
'Container \'{0}\' is not running'.format(name)
)
return start(name, path=path)
elif pre == 'frozen':
if no_start:
raise CommandExecutionError(
'Container \'{0}\' is not running'.format(name)
)
return unfreeze(name, path=path)
def start(name, **kwargs):
'''
Start the named container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
lxc_config
path to a lxc config file
config file will be guessed from container name otherwise
.. versionadded:: 2015.8.0
use_vt
run the command through VT
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.start name
'''
path = kwargs.get('path', None)
cpath = get_root_path(path)
lxc_config = kwargs.get('lxc_config', None)
cmd = 'lxc-start'
if not lxc_config:
lxc_config = os.path.join(cpath, name, 'config')
# we try to start, even without config, if global opts are there
if os.path.exists(lxc_config):
cmd += ' -f {0}'.format(pipes.quote(lxc_config))
cmd += ' -d'
_ensure_exists(name, path=path)
if state(name, path=path) == 'frozen':
raise CommandExecutionError(
'Container \'{0}\' is frozen, use lxc.unfreeze'.format(name)
)
# lxc-start daemonize itself violently, we must not communicate with it
use_vt = kwargs.get('use_vt', None)
with_communicate = kwargs.get('with_communicate', False)
return _change_state(cmd, name, 'running',
stdout=None,
stderr=None,
stdin=None,
with_communicate=with_communicate,
path=path,
use_vt=use_vt)
def stop(name, kill=False, path=None, use_vt=None):
'''
Stop the named container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
kill: False
Do not wait for the container to stop, kill all tasks in the container.
Older LXC versions will stop containers like this irrespective of this
argument.
.. versionchanged:: 2015.5.0
Default value changed to ``False``
use_vt
run the command through VT
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.stop name
'''
_ensure_exists(name, path=path)
orig_state = state(name, path=path)
if orig_state == 'frozen' and not kill:
# Gracefully stopping a frozen container is slower than unfreezing and
# then stopping it (at least in my testing), so if we're not
# force-stopping the container, unfreeze it first.
unfreeze(name, path=path)
cmd = 'lxc-stop'
if kill:
cmd += ' -k'
ret = _change_state(cmd, name, 'stopped', use_vt=use_vt, path=path)
ret['state']['old'] = orig_state
return ret
def freeze(name, **kwargs):
'''
Freeze the named container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
start : False
If ``True`` and the container is stopped, the container will be started
before attempting to freeze.
.. versionadded:: 2015.5.0
use_vt
run the command through VT
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.freeze name
'''
use_vt = kwargs.get('use_vt', None)
path = kwargs.get('path', None)
_ensure_exists(name, path=path)
orig_state = state(name, path=path)
start_ = kwargs.get('start', False)
if orig_state == 'stopped':
if not start_:
raise CommandExecutionError(
'Container \'{0}\' is stopped'.format(name)
)
start(name, path=path)
cmd = 'lxc-freeze'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
ret = _change_state(cmd, name, 'frozen', use_vt=use_vt, path=path)
if orig_state == 'stopped' and start_:
ret['state']['old'] = orig_state
ret['started'] = True
ret['state']['new'] = state(name, path=path)
return ret
def unfreeze(name, path=None, use_vt=None):
'''
Unfreeze the named container.
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
use_vt
run the command through VT
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.unfreeze name
'''
_ensure_exists(name, path=path)
if state(name, path=path) == 'stopped':
raise CommandExecutionError(
'Container \'{0}\' is stopped'.format(name)
)
cmd = 'lxc-unfreeze'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
return _change_state(cmd, name, 'running', path=path, use_vt=use_vt)
def destroy(name, stop=False, path=None):
'''
Destroy the named container.
.. warning::
Destroys all data associated with the container.
path
path to the container parent directory (default: /var/lib/lxc)
.. versionadded:: 2015.8.0
stop : False
If ``True``, the container will be destroyed even if it is
running/frozen.
.. versionchanged:: 2015.5.0
Default value changed to ``False``. This more closely matches the
behavior of ``lxc-destroy(1)``, and also makes it less likely that
an accidental command will destroy a running container that was
being used for important things.
CLI Examples:
.. code-block:: bash
salt '*' lxc.destroy foo
salt '*' lxc.destroy foo stop=True
'''
_ensure_exists(name, path=path)
if not stop and state(name, path=path) != 'stopped':
raise CommandExecutionError(
'Container \'{0}\' is not stopped'.format(name)
)
return _change_state('lxc-destroy', name, None, path=path)
# Compatibility between LXC and nspawn
remove = salt.utils.functools.alias_function(destroy, 'remove')
def exists(name, path=None):
'''
Returns whether the named container exists.
path
path to the container parent directory (default: /var/lib/lxc)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.exists name
'''
_exists = name in ls_(path=path)
# container may be just created but we did cached earlier the
# lxc-ls results
if not _exists:
_exists = name in ls_(cache=False, path=path)
return _exists
def state(name, path=None):
'''
Returns the state of a container.
path
path to the container parent directory (default: /var/lib/lxc)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.state name
'''
# Don't use _ensure_exists() here, it will mess with _change_state()
cachekey = 'lxc.state.{0}{1}'.format(name, path)
try:
return __context__[cachekey]
except KeyError:
if not exists(name, path=path):
__context__[cachekey] = None
else:
cmd = 'lxc-info'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0}'.format(name)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
if ret['retcode'] != 0:
_clear_context()
raise CommandExecutionError(
'Unable to get state of container \'{0}\''.format(name)
)
c_infos = ret['stdout'].splitlines()
c_state = None
for c_info in c_infos:
stat = c_info.split(':')
if stat[0].lower() == 'state':
c_state = stat[1].strip().lower()
break
__context__[cachekey] = c_state
return __context__[cachekey]
def get_parameter(name, parameter, path=None):
'''
Returns the value of a cgroup parameter for a container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.get_parameter container_name memory.limit_in_bytes
'''
_ensure_exists(name, path=path)
cmd = 'lxc-cgroup'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0} {1}'.format(name, parameter)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
if ret['retcode'] != 0:
raise CommandExecutionError(
'Unable to retrieve value for \'{0}\''.format(parameter)
)
return ret['stdout'].strip()
def set_parameter(name, parameter, value, path=None):
'''
Set the value of a cgroup parameter for a container.
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.set_parameter name parameter value
'''
if not exists(name, path=path):
return None
cmd = 'lxc-cgroup'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0} {1} {2}'.format(name, parameter, value)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
if ret['retcode'] != 0:
return False
else:
return True
def info(name, path=None):
'''
Returns information about a container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.info name
'''
cachekey = 'lxc.info.{0}{1}'.format(name, path)
try:
return __context__[cachekey]
except KeyError:
_ensure_exists(name, path=path)
cpath = get_root_path(path)
try:
conf_file = os.path.join(cpath, name, 'config')
except AttributeError:
conf_file = os.path.join(cpath, six.text_type(name), 'config')
if not os.path.isfile(conf_file):
raise CommandExecutionError(
'LXC config file {0} does not exist'.format(conf_file)
)
ret = {}
config = []
with salt.utils.files.fopen(conf_file) as fp_:
for line in fp_:
line = salt.utils.stringutils.to_unicode(line)
comps = [x.strip() for x in
line.split('#', 1)[0].strip().split('=', 1)]
if len(comps) == 2:
config.append(tuple(comps))
ifaces = []
current = None
for key, val in config:
if key == 'lxc.network.type':
current = {'type': val}
ifaces.append(current)
elif not current:
continue
elif key.startswith('lxc.network.'):
current[key.replace('lxc.network.', '', 1)] = val
if ifaces:
ret['nics'] = ifaces
ret['rootfs'] = next(
(x[1] for x in config if x[0] == 'lxc.rootfs'),
None
)
ret['state'] = state(name, path=path)
ret['ips'] = []
ret['public_ips'] = []
ret['private_ips'] = []
ret['public_ipv4_ips'] = []
ret['public_ipv6_ips'] = []
ret['private_ipv4_ips'] = []
ret['private_ipv6_ips'] = []
ret['ipv4_ips'] = []
ret['ipv6_ips'] = []
ret['size'] = None
ret['config'] = conf_file
if ret['state'] == 'running':
try:
limit = int(get_parameter(name, 'memory.limit_in_bytes'))
except (CommandExecutionError, TypeError, ValueError):
limit = 0
try:
usage = int(get_parameter(name, 'memory.usage_in_bytes'))
except (CommandExecutionError, TypeError, ValueError):
usage = 0
free = limit - usage
ret['memory_limit'] = limit
ret['memory_free'] = free
size = run_stdout(name, 'df /', path=path, python_shell=False)
# The size is the 2nd column of the last line
ret['size'] = size.splitlines()[-1].split()[1]
# First try iproute2
ip_cmd = run_all(
name, 'ip link show', path=path, python_shell=False)
if ip_cmd['retcode'] == 0:
ip_data = ip_cmd['stdout']
ip_cmd = run_all(
name, 'ip addr show', path=path, python_shell=False)
ip_data += '\n' + ip_cmd['stdout']
ip_data = salt.utils.network._interfaces_ip(ip_data)
else:
# That didn't work, try ifconfig
ip_cmd = run_all(
name, 'ifconfig', path=path, python_shell=False)
if ip_cmd['retcode'] == 0:
ip_data = \
salt.utils.network._interfaces_ifconfig(
ip_cmd['stdout'])
else:
# Neither was successful, give up
log.warning(
'Unable to run ip or ifconfig in container \'%s\'', name
)
ip_data = {}
ret['ipv4_ips'] = salt.utils.network.ip_addrs(
include_loopback=True,
interface_data=ip_data
)
ret['ipv6_ips'] = salt.utils.network.ip_addrs6(
include_loopback=True,
interface_data=ip_data
)
ret['ips'] = ret['ipv4_ips'] + ret['ipv6_ips']
for address in ret['ipv4_ips']:
if address == '127.0.0.1':
ret['private_ips'].append(address)
ret['private_ipv4_ips'].append(address)
elif salt.utils.cloud.is_public_ip(address):
ret['public_ips'].append(address)
ret['public_ipv4_ips'].append(address)
else:
ret['private_ips'].append(address)
ret['private_ipv4_ips'].append(address)
for address in ret['ipv6_ips']:
if address == '::1' or address.startswith('fe80'):
ret['private_ips'].append(address)
ret['private_ipv6_ips'].append(address)
else:
ret['public_ips'].append(address)
ret['public_ipv6_ips'].append(address)
for key in [x for x in ret if x == 'ips' or x.endswith('ips')]:
ret[key].sort(key=_ip_sort)
__context__[cachekey] = ret
return __context__[cachekey]
def set_password(name, users, password, encrypted=True, path=None):
'''
.. versionchanged:: 2015.5.0
Function renamed from ``set_pass`` to ``set_password``. Additionally,
this function now supports (and defaults to using) a password hash
instead of a plaintext password.
Set the password of one or more system users inside containers
users
Comma-separated list (or python list) of users to change password
password
Password to set for the specified user(s)
encrypted : True
If true, ``password`` must be a password hash. Set to ``False`` to set
a plaintext password (not recommended).
.. versionadded:: 2015.5.0
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.set_pass container-name root '$6$uJ2uAyLU$KoI67t8As/0fXtJOPcHKGXmUpcoYUcVR2K6x93walnShTCQvjRwq25yIkiCBOqgbfdKQSFnAo28/ek6716vEV1'
salt '*' lxc.set_pass container-name root foo encrypted=False
'''
def _bad_user_input():
raise SaltInvocationError('Invalid input for \'users\' parameter')
if not isinstance(users, list):
try:
users = users.split(',')
except AttributeError:
_bad_user_input()
if not users:
_bad_user_input()
failed_users = []
for user in users:
result = retcode(name,
'chpasswd{0}'.format(' -e' if encrypted else ''),
stdin=':'.join((user, password)),
python_shell=False,
path=path,
chroot_fallback=True,
output_loglevel='quiet')
if result != 0:
failed_users.append(user)
if failed_users:
raise CommandExecutionError(
'Password change failed for the following user(s): {0}'
.format(', '.join(failed_users))
)
return True
set_pass = salt.utils.functools.alias_function(set_password, 'set_pass')
def update_lxc_conf(name, lxc_conf, lxc_conf_unset, path=None):
'''
Edit LXC configuration options
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.update_lxc_conf ubuntu \\
lxc_conf="[{'network.ipv4.ip':'10.0.3.5'}]" \\
lxc_conf_unset="['lxc.utsname']"
'''
_ensure_exists(name, path=path)
cpath = get_root_path(path)
lxc_conf_p = os.path.join(cpath, name, 'config')
if not os.path.exists(lxc_conf_p):
raise SaltInvocationError(
'Configuration file {0} does not exist'.format(lxc_conf_p)
)
changes = {'edited': [], 'added': [], 'removed': []}
ret = {'changes': changes, 'result': True, 'comment': ''}
# do not use salt.utils.files.fopen !
with salt.utils.files.fopen(lxc_conf_p, 'r') as fic:
filtered_lxc_conf = []
for row in lxc_conf:
if not row:
continue
for conf in row:
filtered_lxc_conf.append((conf.strip(),
row[conf].strip()))
ret['comment'] = 'lxc.conf is up to date'
lines = []
orig_config = salt.utils.stringutils.to_unicode(fic.read())
for line in orig_config.splitlines():
if line.startswith('#') or not line.strip():
lines.append([line, ''])
else:
line = line.split('=')
index = line.pop(0)
val = (index.strip(), '='.join(line).strip())
if val not in lines:
lines.append(val)
for key, item in filtered_lxc_conf:
matched = False
for idx, line in enumerate(lines[:]):
if line[0] == key:
matched = True
lines[idx] = (key, item)
if '='.join(line[1:]).strip() != item.strip():
changes['edited'].append(
({line[0]: line[1:]}, {key: item}))
break
if not matched:
if (key, item) not in lines:
lines.append((key, item))
changes['added'].append({key: item})
dest_lxc_conf = []
# filter unset
if lxc_conf_unset:
for line in lines:
for opt in lxc_conf_unset:
if (
not line[0].startswith(opt) and
line not in dest_lxc_conf
):
dest_lxc_conf.append(line)
else:
changes['removed'].append(opt)
else:
dest_lxc_conf = lines
conf = ''
for key, val in dest_lxc_conf:
if not val:
conf += '{0}\n'.format(key)
else:
conf += '{0} = {1}\n'.format(key.strip(), val.strip())
conf_changed = conf != orig_config
chrono = datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S')
if conf_changed:
# DO NOT USE salt.utils.files.fopen here, i got (kiorky)
# problems with lxc configs which were wiped !
with salt.utils.files.fopen('{0}.{1}'.format(lxc_conf_p, chrono), 'w') as wfic:
wfic.write(salt.utils.stringutils.to_str(conf))
with salt.utils.files.fopen(lxc_conf_p, 'w') as wfic:
wfic.write(salt.utils.stringutils.to_str(conf))
ret['comment'] = 'Updated'
ret['result'] = True
if not any(changes[x] for x in changes):
# Ensure an empty changes dict if nothing was modified
ret['changes'] = {}
return ret
def set_dns(name, dnsservers=None, searchdomains=None, path=None):
'''
.. versionchanged:: 2015.5.0
The ``dnsservers`` and ``searchdomains`` parameters can now be passed
as a comma-separated list.
Update /etc/resolv.confo
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.set_dns ubuntu "['8.8.8.8', '4.4.4.4']"
'''
if dnsservers is None:
dnsservers = ['8.8.8.8', '4.4.4.4']
elif not isinstance(dnsservers, list):
try:
dnsservers = dnsservers.split(',')
except AttributeError:
raise SaltInvocationError(
'Invalid input for \'dnsservers\' parameter'
)
if searchdomains is None:
searchdomains = []
elif not isinstance(searchdomains, list):
try:
searchdomains = searchdomains.split(',')
except AttributeError:
raise SaltInvocationError(
'Invalid input for \'searchdomains\' parameter'
)
dns = ['nameserver {0}'.format(x) for x in dnsservers]
dns.extend(['search {0}'.format(x) for x in searchdomains])
dns = '\n'.join(dns) + '\n'
# we may be using resolvconf in the container
# We need to handle that case with care:
# - we create the resolv.conf runtime directory (the
# linked directory) as anyway it will be shadowed when the real
# runned tmpfs mountpoint will be mounted.
# ( /etc/resolv.conf -> ../run/resolvconf/resolv.conf)
# Indeed, it can save us in any other case (running, eg, in a
# bare chroot when repairing or preparing the container for
# operation.
# - We also teach resolvconf to use the aforementioned dns.
# - We finally also set /etc/resolv.conf in all cases
rstr = __salt__['test.random_hash']()
# no tmp here, apparmor won't let us execute !
script = '/sbin/{0}_dns.sh'.format(rstr)
DNS_SCRIPT = "\n".join([
# 'set -x',
'#!/usr/bin/env bash',
'if [ -h /etc/resolv.conf ];then',
' if [ "x$(readlink /etc/resolv.conf)"'
' = "x../run/resolvconf/resolv.conf" ];then',
' if [ ! -d /run/resolvconf/ ];then',
' mkdir -p /run/resolvconf',
' fi',
' cat > /etc/resolvconf/resolv.conf.d/head <<EOF',
dns,
'EOF',
'',
' fi',
'fi',
'cat > /etc/resolv.conf <<EOF',
dns,
'EOF',
''])
result = run_all(
name, 'tee {0}'.format(script), path=path,
stdin=DNS_SCRIPT, python_shell=True)
if result['retcode'] == 0:
result = run_all(
name, 'sh -c "chmod +x {0};{0}"'.format(script),
path=path, python_shell=True)
# blindly delete the setter file
run_all(name,
'sh -c \'if [ -f "{0}" ];then rm -f "{0}";fi\''.format(script),
path=path, python_shell=True)
if result['retcode'] != 0:
error = ('Unable to write to /etc/resolv.conf in container \'{0}\''
.format(name))
if result['stderr']:
error += ': {0}'.format(result['stderr'])
raise CommandExecutionError(error)
return True
def running_systemd(name, cache=True, path=None):
'''
Determine if systemD is running
path
path to the container parent
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.running_systemd ubuntu
'''
k = 'lxc.systemd.test.{0}{1}'.format(name, path)
ret = __context__.get(k, None)
if ret is None or not cache:
rstr = __salt__['test.random_hash']()
# no tmp here, apparmor won't let us execute !
script = '/sbin/{0}_testsystemd.sh'.format(rstr)
# ubuntu already had since trusty some bits of systemd but was
# still using upstart ...
# we need to be a bit more careful that just testing that systemd
# is present
_script = textwrap.dedent(
'''\
#!/usr/bin/env bash
set -x
if ! command -v systemctl 1>/dev/null 2>/dev/null;then exit 2;fi
for i in \\
/run/systemd/journal/dev-log\\
/run/systemd/journal/flushed\\
/run/systemd/journal/kernel-seqnum\\
/run/systemd/journal/socket\\
/run/systemd/journal/stdout\\
/var/run/systemd/journal/dev-log\\
/var/run/systemd/journal/flushed\\
/var/run/systemd/journal/kernel-seqnum\\
/var/run/systemd/journal/socket\\
/var/run/systemd/journal/stdout\\
;do\\
if test -e ${i};then exit 0;fi
done
if test -d /var/systemd/system;then exit 0;fi
exit 2
''')
result = run_all(
name, 'tee {0}'.format(script), path=path,
stdin=_script, python_shell=True)
if result['retcode'] == 0:
result = run_all(name,
'sh -c "chmod +x {0};{0}"'''.format(script),
path=path,
python_shell=True)
else:
raise CommandExecutionError(
'lxc {0} failed to copy initd tester'.format(name))
run_all(name,
'sh -c \'if [ -f "{0}" ];then rm -f "{0}";fi\''
''.format(script),
path=path,
ignore_retcode=True,
python_shell=True)
if result['retcode'] != 0:
error = ('Unable to determine if the container \'{0}\''
' was running systemd, assmuming it is not.'
''.format(name))
if result['stderr']:
error += ': {0}'.format(result['stderr'])
# only cache result if we got a known exit code
if result['retcode'] in (0, 2):
__context__[k] = ret = not result['retcode']
return ret
def systemd_running_state(name, path=None):
'''
Get the operational state of a systemd based container
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.systemd_running_state ubuntu
'''
try:
ret = run_all(name,
'systemctl is-system-running',
path=path,
ignore_retcode=True)['stdout']
except CommandExecutionError:
ret = ''
return ret
def test_sd_started_state(name, path=None):
'''
Test if a systemd container is fully started
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.test_sd_started_state ubuntu
'''
qstate = systemd_running_state(name, path=path)
if qstate in ('initializing', 'starting'):
return False
elif qstate == '':
return None
else:
return True
def test_bare_started_state(name, path=None):
'''
Test if a non systemd container is fully started
For now, it consists only to test if the container is attachable
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.test_bare_started_state ubuntu
'''
try:
ret = run_all(
name, 'ls', path=path, ignore_retcode=True
)['retcode'] == 0
except (CommandExecutionError,):
ret = None
return ret
def wait_started(name, path=None, timeout=300):
'''
Check that the system has fully inited
This is actually very important for systemD based containers
see https://github.com/saltstack/salt/issues/23847
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.wait_started ubuntu
'''
if not exists(name, path=path):
raise CommandExecutionError(
'Container {0} does does exists'.format(name))
if not state(name, path=path) == 'running':
raise CommandExecutionError(
'Container {0} is not running'.format(name))
ret = False
if running_systemd(name, path=path):
test_started = test_sd_started_state
logger = log.error
else:
test_started = test_bare_started_state
logger = log.debug
now = time.time()
expire = now + timeout
now = time.time()
started = test_started(name, path=path)
while time.time() < expire and not started:
time.sleep(0.3)
started = test_started(name, path=path)
if started is None:
logger(
'Assuming %s is started, although we failed to detect that'
' is fully started correctly', name)
ret = True
else:
ret = started
return ret
def _needs_install(name, path=None):
ret = 0
has_minion = retcode(name,
'which salt-minion',
path=path,
ignore_retcode=True)
# we assume that installing is when no minion is running
# but testing the executable presence is not enougth for custom
# installs where the bootstrap can do much more than installing
# the bare salt binaries.
if has_minion:
processes = run_stdout(name, "ps aux", path=path)
if 'salt-minion' not in processes:
ret = 1
else:
retcode(name, 'salt-call --local service.stop salt-minion')
else:
ret = 1
return ret
def bootstrap(name,
config=None,
approve_key=True,
install=True,
pub_key=None,
priv_key=None,
bootstrap_url=None,
force_install=False,
unconditional_install=False,
path=None,
bootstrap_delay=None,
bootstrap_args=None,
bootstrap_shell=None):
'''
Install and configure salt in a container.
config
Minion configuration options. By default, the ``master`` option is set
to the target host's master.
approve_key
Request a pre-approval of the generated minion key. Requires
that the salt-master be configured to either auto-accept all keys or
expect a signing request from the target host. Default: ``True``
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
pub_key
Explicit public key to pressed the minion with (optional).
This can be either a filepath or a string representing the key
priv_key
Explicit private key to pressed the minion with (optional).
This can be either a filepath or a string representing the key
bootstrap_delay
Delay in seconds between end of container creation and bootstrapping.
Useful when waiting for container to obtain a DHCP lease.
.. versionadded:: 2015.5.0
bootstrap_url
url, content or filepath to the salt bootstrap script
bootstrap_args
salt bootstrap script arguments
bootstrap_shell
shell to execute the script into
install
Whether to attempt a full installation of salt-minion if needed.
force_install
Force installation even if salt-minion is detected,
this is the way to run vendor bootstrap scripts even
if a salt minion is already present in the container
unconditional_install
Run the script even if the container seems seeded
CLI Examples:
.. code-block:: bash
salt 'minion' lxc.bootstrap container_name [config=config_data] \\
[approve_key=(True|False)] [install=(True|False)]
'''
wait_started(name, path=path)
if bootstrap_delay is not None:
try:
log.info('LXC %s: bootstrap_delay: %s', name, bootstrap_delay)
time.sleep(bootstrap_delay)
except TypeError:
# Bad input, but assume since a value was passed that
# a delay was desired, and sleep for 5 seconds
time.sleep(5)
c_info = info(name, path=path)
if not c_info:
return None
# default set here as we cannot set them
# in def as it can come from a chain of procedures.
if bootstrap_args:
# custom bootstrap args can be totally customized, and user could
# have inserted the placeholder for the config directory.
# For example, some salt bootstrap script do not use at all -c
if '{0}' not in bootstrap_args:
bootstrap_args += ' -c {0}'
else:
bootstrap_args = '-c {0}'
if not bootstrap_shell:
bootstrap_shell = 'sh'
orig_state = _ensure_running(name, path=path)
if not orig_state:
return orig_state
if not force_install:
needs_install = _needs_install(name, path=path)
else:
needs_install = True
seeded = retcode(name,
'test -e \'{0}\''.format(SEED_MARKER),
path=path,
chroot_fallback=True,
ignore_retcode=True) == 0
tmp = tempfile.mkdtemp()
if seeded and not unconditional_install:
ret = True
else:
ret = False
cfg_files = __salt__['seed.mkconfig'](
config, tmp=tmp, id_=name, approve_key=approve_key,
pub_key=pub_key, priv_key=priv_key)
if needs_install or force_install or unconditional_install:
if install:
rstr = __salt__['test.random_hash']()
configdir = '/var/tmp/.c_{0}'.format(rstr)
cmd = 'install -m 0700 -d {0}'.format(configdir)
if run_all(
name, cmd, path=path, python_shell=False
)['retcode'] != 0:
log.error('tmpdir %s creation failed %s', configdir, cmd)
return False
bs_ = __salt__['config.gather_bootstrap_script'](
bootstrap=bootstrap_url)
script = '/sbin/{0}_bootstrap.sh'.format(rstr)
copy_to(name, bs_, script, path=path)
result = run_all(name,
'sh -c "chmod +x {0}"'.format(script),
path=path,
python_shell=True)
copy_to(name, cfg_files['config'],
os.path.join(configdir, 'minion'),
path=path)
copy_to(name, cfg_files['privkey'],
os.path.join(configdir, 'minion.pem'),
path=path)
copy_to(name, cfg_files['pubkey'],
os.path.join(configdir, 'minion.pub'),
path=path)
bootstrap_args = bootstrap_args.format(configdir)
cmd = ('{0} {2} {1}'
.format(bootstrap_shell,
bootstrap_args.replace("'", "''"),
script))
# log ASAP the forged bootstrap command which can be wrapped
# out of the output in case of unexpected problem
log.info('Running %s in LXC container \'%s\'', cmd, name)
ret = retcode(name, cmd, output_loglevel='info',
path=path, use_vt=True) == 0
run_all(name,
'sh -c \'if [ -f "{0}" ];then rm -f "{0}";fi\''
''.format(script),
path=path,
ignore_retcode=True,
python_shell=True)
else:
ret = False
else:
minion_config = salt.config.minion_config(cfg_files['config'])
pki_dir = minion_config['pki_dir']
copy_to(name,
cfg_files['config'],
'/etc/salt/minion',
path=path)
copy_to(name,
cfg_files['privkey'],
os.path.join(pki_dir, 'minion.pem'),
path=path)
copy_to(name,
cfg_files['pubkey'],
os.path.join(pki_dir, 'minion.pub'),
path=path)
run(name,
'salt-call --local service.enable salt-minion',
path=path,
python_shell=False)
ret = True
shutil.rmtree(tmp)
if orig_state == 'stopped':
stop(name, path=path)
elif orig_state == 'frozen':
freeze(name, path=path)
# mark seeded upon successful install
if ret:
run(name,
'touch \'{0}\''.format(SEED_MARKER),
path=path,
python_shell=False)
return ret
def attachable(name, path=None):
'''
Return True if the named container can be attached to via the lxc-attach
command
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt 'minion' lxc.attachable ubuntu
'''
cachekey = 'lxc.attachable{0}{1}'.format(name, path)
try:
return __context__[cachekey]
except KeyError:
_ensure_exists(name, path=path)
# Can't use run() here because it uses attachable() and would
# endlessly recurse, resulting in a traceback
log.debug('Checking if LXC container %s is attachable', name)
cmd = 'lxc-attach'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' --clear-env -n {0} -- /usr/bin/env'.format(name)
result = __salt__['cmd.retcode'](cmd,
python_shell=False,
output_loglevel='quiet',
ignore_retcode=True) == 0
__context__[cachekey] = result
return __context__[cachekey]
def _run(name,
cmd,
output=None,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=None,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
Common logic for lxc.run functions
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
'''
orig_state = state(name, path=path)
try:
if attachable(name, path=path):
ret = __salt__['container_resource.run'](
name,
cmd,
path=path,
container_type=__virtualname__,
exec_driver=EXEC_DRIVER,
output=output,
no_start=no_start,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
ignore_retcode=ignore_retcode,
use_vt=use_vt,
keep_env=keep_env)
else:
if not chroot_fallback:
raise CommandExecutionError(
'{0} is not attachable.'.format(name))
rootfs = info(name, path=path).get('rootfs')
# Set context var to make cmd.run_chroot run cmd.run instead of
# cmd.run_all.
__context__['cmd.run_chroot.func'] = __salt__['cmd.run']
ret = __salt__['cmd.run_chroot'](rootfs,
cmd,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
ignore_retcode=ignore_retcode)
except Exception:
raise
finally:
# Make sure we honor preserve_state, even if there was an exception
new_state = state(name, path=path)
if preserve_state:
if orig_state == 'stopped' and new_state != 'stopped':
stop(name, path=path)
elif orig_state == 'frozen' and new_state != 'frozen':
freeze(name, start=True, path=path)
if output in (None, 'all'):
return ret
else:
return ret[output]
def run(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.8.0
Run :mod:`cmd.run <salt.modules.cmdmod.run>` within a container
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed in stderr if the command being run
does not exist. If no output is returned using this function, try using
:mod:`lxc.run_stderr <salt.modules.lxc.run_stderr>` or
:mod:`lxc.run_all <salt.modules.lxc.run_all>`.
name
Name of the container in which to run the command
cmd
Command to run
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console. Assumes
``output=all``.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
CLI Example:
.. code-block:: bash
salt myminion lxc.run mycontainer 'ifconfig -a'
'''
return _run(name,
cmd,
path=path,
output=None,
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def run_stdout(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.5.0
Run :mod:`cmd.run_stdout <salt.modules.cmdmod.run_stdout>` within a container
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed in stderr if the command being run
does not exist. If no output is returned using this function, try using
:mod:`lxc.run_stderr <salt.modules.lxc.run_stderr>` or
:mod:`lxc.run_all <salt.modules.lxc.run_all>`.
name
Name of the container in which to run the command
cmd
Command to run
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console
``output=all``.
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
CLI Example:
.. code-block:: bash
salt myminion lxc.run_stdout mycontainer 'ifconfig -a'
'''
return _run(name,
cmd,
path=path,
output='stdout',
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def run_stderr(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.5.0
Run :mod:`cmd.run_stderr <salt.modules.cmdmod.run_stderr>` within a container
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed if the command being run does not
exist.
name
Name of the container in which to run the command
cmd
Command to run
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console
``output=all``.
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
CLI Example:
.. code-block:: bash
salt myminion lxc.run_stderr mycontainer 'ip addr show'
'''
return _run(name,
cmd,
path=path,
output='stderr',
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def retcode(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.5.0
Run :mod:`cmd.retcode <salt.modules.cmdmod.retcode>` within a container
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed in stderr if the command being run
does not exist. If the retcode is nonzero and not what was expected,
try using :mod:`lxc.run_stderr <salt.modules.lxc.run_stderr>`
or :mod:`lxc.run_all <salt.modules.lxc.run_all>`.
name
Name of the container in which to run the command
cmd
Command to run
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console
``output=all``.
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
CLI Example:
.. code-block:: bash
salt myminion lxc.retcode mycontainer 'ip addr show'
'''
return _run(name,
cmd,
output='retcode',
path=path,
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def run_all(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.5.0
Run :mod:`cmd.run_all <salt.modules.cmdmod.run_all>` within a container
.. note::
While the command is run within the container, it is initiated from the
host. Therefore, the PID in the return dict is from the host, not from
the container.
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed in stderr if the command being run
does not exist.
name
Name of the container in which to run the command
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
cmd
Command to run
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console
``output=all``.
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
CLI Example:
.. code-block:: bash
salt myminion lxc.run_all mycontainer 'ip addr show'
'''
return _run(name,
cmd,
output='all',
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
path=path,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def _get_md5(name, path):
'''
Get the MD5 checksum of a file from a container
'''
output = run_stdout(name, 'md5sum "{0}"'.format(path),
chroot_fallback=True,
ignore_retcode=True)
try:
return output.split()[0]
except IndexError:
# Destination file does not exist or could not be accessed
return None
def copy_to(name, source, dest, overwrite=False, makedirs=False, path=None):
'''
.. versionchanged:: 2015.8.0
Function renamed from ``lxc.cp`` to ``lxc.copy_to`` for consistency
with other container types. ``lxc.cp`` will continue to work, however.
For versions 2015.2.x and earlier, use ``lxc.cp``.
Copy a file or directory from the host into a container
name
Container name
source
File to be copied to the container
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
dest
Destination on the container. Must be an absolute path.
.. versionchanged:: 2015.5.0
If the destination is a directory, the file will be copied into
that directory.
overwrite : False
Unless this option is set to ``True``, then if a file exists at the
location specified by the ``dest`` argument, an error will be raised.
.. versionadded:: 2015.8.0
makedirs : False
Create the parent directory on the container if it does not already
exist.
.. versionadded:: 2015.5.0
CLI Example:
.. code-block:: bash
salt 'minion' lxc.copy_to /tmp/foo /root/foo
salt 'minion' lxc.cp /tmp/foo /root/foo
'''
_ensure_running(name, no_start=True, path=path)
return __salt__['container_resource.copy_to'](
name,
source,
dest,
container_type=__virtualname__,
path=path,
exec_driver=EXEC_DRIVER,
overwrite=overwrite,
makedirs=makedirs)
cp = salt.utils.functools.alias_function(copy_to, 'cp')
def read_conf(conf_file, out_format='simple'):
'''
Read in an LXC configuration file. By default returns a simple, unsorted
dict, but can also return a more detailed structure including blank lines
and comments.
out_format:
set to 'simple' if you need the old and unsupported behavior.
This won't support the multiple lxc values (eg: multiple network nics)
CLI Examples:
.. code-block:: bash
salt 'minion' lxc.read_conf /etc/lxc/mycontainer.conf
salt 'minion' lxc.read_conf /etc/lxc/mycontainer.conf out_format=commented
'''
ret_commented = []
ret_simple = {}
with salt.utils.files.fopen(conf_file, 'r') as fp_:
for line in salt.utils.data.decode(fp_.readlines()):
if '=' not in line:
ret_commented.append(line)
continue
comps = line.split('=')
value = '='.join(comps[1:]).strip()
comment = None
if value.strip().startswith('#'):
vcomps = value.strip().split('#')
value = vcomps[1].strip()
comment = '#'.join(vcomps[1:]).strip()
ret_commented.append({comps[0].strip(): {
'value': value,
'comment': comment,
}})
else:
ret_commented.append({comps[0].strip(): value})
ret_simple[comps[0].strip()] = value
if out_format == 'simple':
return ret_simple
return ret_commented
def write_conf(conf_file, conf):
'''
Write out an LXC configuration file
This is normally only used internally. The format of the data structure
must match that which is returned from ``lxc.read_conf()``, with
``out_format`` set to ``commented``.
An example might look like:
.. code-block:: python
[
{'lxc.utsname': '$CONTAINER_NAME'},
'# This is a commented line\\n',
'\\n',
{'lxc.mount': '$CONTAINER_FSTAB'},
{'lxc.rootfs': {'comment': 'This is another test',
'value': 'This is another test'}},
'\\n',
{'lxc.network.type': 'veth'},
{'lxc.network.flags': 'up'},
{'lxc.network.link': 'br0'},
{'lxc.network.mac': '$CONTAINER_MACADDR'},
{'lxc.network.ipv4': '$CONTAINER_IPADDR'},
{'lxc.network.name': '$CONTAINER_DEVICENAME'},
]
CLI Example:
.. code-block:: bash
salt 'minion' lxc.write_conf /etc/lxc/mycontainer.conf \\
out_format=commented
'''
if not isinstance(conf, list):
raise SaltInvocationError('Configuration must be passed as a list')
# construct the content prior to write to the file
# to avoid half written configs
content = ''
for line in conf:
if isinstance(line, (six.text_type, six.string_types)):
content += line
elif isinstance(line, dict):
for key in list(line.keys()):
out_line = None
if isinstance(
line[key],
(six.text_type, six.string_types, six.integer_types, float)
):
out_line = ' = '.join((key, "{0}".format(line[key])))
elif isinstance(line[key], dict):
out_line = ' = '.join((key, line[key]['value']))
if 'comment' in line[key]:
out_line = ' # '.join((out_line, line[key]['comment']))
if out_line:
content += out_line
content += '\n'
with salt.utils.files.fopen(conf_file, 'w') as fp_:
fp_.write(salt.utils.stringutils.to_str(content))
return {}
def edit_conf(conf_file,
out_format='simple',
read_only=False,
lxc_config=None,
**kwargs):
'''
Edit an LXC configuration file. If a setting is already present inside the
file, its value will be replaced. If it does not exist, it will be appended
to the end of the file. Comments and blank lines will be kept in-tact if
they already exist in the file.
out_format:
Set to simple if you need backward compatibility (multiple items for a
simple key is not supported)
read_only:
return only the edited configuration without applying it
to the underlying lxc configuration file
lxc_config:
List of dict containning lxc configuration items
For network configuration, you also need to add the device it belongs
to, otherwise it will default to eth0.
Also, any change to a network parameter will result in the whole
network reconfiguration to avoid mismatchs, be aware of that !
After the file is edited, its contents will be returned. By default, it
will be returned in ``simple`` format, meaning an unordered dict (which
may not represent the actual file order). Passing in an ``out_format`` of
``commented`` will return a data structure which accurately represents the
order and content of the file.
CLI Example:
.. code-block:: bash
salt 'minion' lxc.edit_conf /etc/lxc/mycontainer.conf \\
out_format=commented lxc.network.type=veth
salt 'minion' lxc.edit_conf /etc/lxc/mycontainer.conf \\
out_format=commented \\
lxc_config="[{'lxc.network.name': 'eth0', \\
'lxc.network.ipv4': '1.2.3.4'},
{'lxc.network.name': 'eth2', \\
'lxc.network.ipv4': '1.2.3.5',\\
'lxc.network.gateway': '1.2.3.1'}]"
'''
data = []
try:
conf = read_conf(conf_file, out_format=out_format)
except Exception:
conf = []
if not lxc_config:
lxc_config = []
lxc_config = copy.deepcopy(lxc_config)
# search if we want to access net config
# in that case, we will replace all the net configuration
net_config = []
for lxc_kws in lxc_config + [kwargs]:
net_params = {}
for kwarg in [a for a in lxc_kws]:
if kwarg.startswith('__'):
continue
if kwarg.startswith('lxc.network.'):
net_params[kwarg] = lxc_kws[kwarg]
lxc_kws.pop(kwarg, None)
if net_params:
net_config.append(net_params)
nic_opts = salt.utils.odict.OrderedDict()
for params in net_config:
dev = params.get('lxc.network.name', DEFAULT_NIC)
dev_opts = nic_opts.setdefault(dev, salt.utils.odict.OrderedDict())
for param in params:
opt = param.replace('lxc.network.', '')
opt = {'hwaddr': 'mac'}.get(opt, opt)
dev_opts[opt] = params[param]
net_changes = []
if nic_opts:
net_changes = _config_list(conf, only_net=True,
**{'network_profile': DEFAULT_NIC,
'nic_opts': nic_opts})
if net_changes:
lxc_config.extend(net_changes)
for line in conf:
if not isinstance(line, dict):
data.append(line)
continue
else:
for key in list(line.keys()):
val = line[key]
if net_changes and key.startswith('lxc.network.'):
continue
found = False
for ix in range(len(lxc_config)):
kw = lxc_config[ix]
if key in kw:
found = True
data.append({key: kw[key]})
del kw[key]
if not found:
data.append({key: val})
for lxc_kws in lxc_config:
for kwarg in lxc_kws:
data.append({kwarg: lxc_kws[kwarg]})
if read_only:
return data
write_conf(conf_file, data)
return read_conf(conf_file, out_format)
def reboot(name, path=None):
'''
Reboot a container.
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Examples:
.. code-block:: bash
salt 'minion' lxc.reboot myvm
'''
ret = {'result': True,
'changes': {},
'comment': '{0} rebooted'.format(name)}
does_exist = exists(name, path=path)
if does_exist and (state(name, path=path) == 'running'):
try:
stop(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
ret['result'] = False
return ret
if does_exist and (state(name, path=path) != 'running'):
try:
start(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
ret['result'] = False
return ret
ret['changes'][name] = 'rebooted'
return ret
def reconfigure(name,
cpu=None,
cpuset=None,
cpushare=None,
memory=None,
profile=None,
network_profile=None,
nic_opts=None,
bridge=None,
gateway=None,
autostart=None,
utsname=None,
rootfs=None,
path=None,
**kwargs):
'''
Reconfigure a container.
This only applies to a few property
name
Name of the container.
utsname
utsname of the container.
.. versionadded:: 2016.3.0
rootfs
rootfs of the container.
.. versionadded:: 2016.3.0
cpu
Select a random number of cpu cores and assign it to the cpuset, if the
cpuset option is set then this option will be ignored
cpuset
Explicitly define the cpus this container will be bound to
cpushare
cgroups cpu shares.
autostart
autostart container on reboot
memory
cgroups memory limit, in MB.
(0 for nolimit, None for old default 1024MB)
gateway
the ipv4 gateway to use
the default does nothing more than lxcutils does
bridge
the bridge to use
the default does nothing more than lxcutils does
nic
Network interfaces profile (defined in config or pillar).
nic_opts
Extra options for network interfaces, will override
``{"eth0": {"mac": "aa:bb:cc:dd:ee:ff", "ipv4": "10.1.1.1", "ipv6": "2001:db8::ff00:42:8329"}}``
or
``{"eth0": {"mac": "aa:bb:cc:dd:ee:ff", "ipv4": "10.1.1.1/24", "ipv6": "2001:db8::ff00:42:8329"}}``
path
path to the container parent
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt-call -lall mc_lxc_fork.reconfigure foobar nic_opts="{'eth1': {'mac': '00:16:3e:dd:ee:44'}}" memory=4
'''
changes = {}
cpath = get_root_path(path)
path = os.path.join(cpath, name, 'config')
ret = {'name': name,
'comment': 'config for {0} up to date'.format(name),
'result': True,
'changes': changes}
profile = get_container_profile(copy.deepcopy(profile))
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, _marker)
profile_match = profile.pop(key, default)
# let kwarg overrides be the preferred choice
if kw_overrides_match is _marker:
return profile_match
return kw_overrides_match
if nic_opts is not None and not network_profile:
network_profile = DEFAULT_NIC
if autostart is not None:
autostart = select('autostart', autostart)
else:
autostart = 'keep'
if not utsname:
utsname = select('utsname', utsname)
if os.path.exists(path):
old_chunks = read_conf(path, out_format='commented')
make_kw = salt.utils.odict.OrderedDict([
('utsname', utsname),
('rootfs', rootfs),
('autostart', autostart),
('cpu', cpu),
('gateway', gateway),
('cpuset', cpuset),
('cpushare', cpushare),
('network_profile', network_profile),
('nic_opts', nic_opts),
('bridge', bridge)])
# match 0 and none as memory = 0 in lxc config is harmful
if memory:
make_kw['memory'] = memory
kw = salt.utils.odict.OrderedDict()
for key, val in six.iteritems(make_kw):
if val is not None:
kw[key] = val
new_cfg = _config_list(conf_tuples=old_chunks, **kw)
if new_cfg:
edit_conf(path, out_format='commented', lxc_config=new_cfg)
chunks = read_conf(path, out_format='commented')
if old_chunks != chunks:
ret['comment'] = '{0} lxc config updated'.format(name)
if state(name, path=path) == 'running':
cret = reboot(name, path=path)
ret['result'] = cret['result']
return ret
def apply_network_profile(name, network_profile, nic_opts=None, path=None):
'''
.. versionadded:: 2015.5.0
Apply a network profile to a container
network_profile
profile name or default values (dict)
nic_opts
values to override in defaults (dict)
indexed by nic card names
path
path to the container parent
.. versionadded:: 2015.8.0
CLI Examples:
.. code-block:: bash
salt 'minion' lxc.apply_network_profile web1 centos
salt 'minion' lxc.apply_network_profile web1 centos \\
nic_opts="{'eth0': {'mac': 'xx:xx:xx:xx:xx:xx'}}"
salt 'minion' lxc.apply_network_profile web1 \\
"{'eth0': {'mac': 'xx:xx:xx:xx:xx:yy'}}"
nic_opts="{'eth0': {'mac': 'xx:xx:xx:xx:xx:xx'}}"
The special case to disable use of ethernet nics:
.. code-block:: bash
salt 'minion' lxc.apply_network_profile web1 centos \\
"{eth0: {disable: true}}"
'''
cpath = get_root_path(path)
cfgpath = os.path.join(cpath, name, 'config')
before = []
with salt.utils.files.fopen(cfgpath, 'r') as fp_:
for line in fp_:
before.append(line)
lxcconfig = _LXCConfig(name=name, path=path)
old_net = lxcconfig._filter_data('lxc.network')
network_params = {}
for param in _network_conf(
conf_tuples=old_net,
network_profile=network_profile, nic_opts=nic_opts
):
network_params.update(param)
if network_params:
edit_conf(cfgpath, out_format='commented', **network_params)
after = []
with salt.utils.files.fopen(cfgpath, 'r') as fp_:
for line in fp_:
after.append(line)
diff = ''
for line in difflib.unified_diff(before,
after,
fromfile='before',
tofile='after'):
diff += line
return diff
def get_pid(name, path=None):
'''
Returns a container pid.
Throw an exception if the container isn't running.
CLI Example:
.. code-block:: bash
salt '*' lxc.get_pid name
'''
if name not in list_(limit='running', path=path):
raise CommandExecutionError('Container {0} is not running, can\'t determine PID'.format(name))
info = __salt__['cmd.run']('lxc-info -n {0}'.format(name)).split("\n")
pid = [line.split(':')[1].strip() for line in info if re.match(r'\s*PID', line)][0]
return pid
def add_veth(name, interface_name, bridge=None, path=None):
'''
Add a veth to a container.
Note : this function doesn't update the container config, just add the interface at runtime
name
Name of the container
interface_name
Name of the interface in the container
bridge
Name of the bridge to attach the interface to (facultative)
CLI Examples:
.. code-block:: bash
salt '*' lxc.add_veth container_name eth1 br1
salt '*' lxc.add_veth container_name eth1
'''
# Get container init PID
pid = get_pid(name, path=path)
# Generate a ramdom string for veth and ensure that is isn't present on the system
while True:
random_veth = 'veth'+''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(6))
if random_veth not in __salt__['network.interfaces']().keys():
break
# Check prerequisites
if not __salt__['file.directory_exists']('/var/run/'):
raise CommandExecutionError('Directory /var/run required for lxc.add_veth doesn\'t exists')
if not __salt__['file.file_exists']('/proc/{0}/ns/net'.format(pid)):
raise CommandExecutionError('Proc file for container {0} network namespace doesn\'t exists'.format(name))
if not __salt__['file.directory_exists']('/var/run/netns'):
__salt__['file.mkdir']('/var/run/netns')
# Ensure that the symlink is up to date (change on container restart)
if __salt__['file.is_link']('/var/run/netns/{0}'.format(name)):
__salt__['file.remove']('/var/run/netns/{0}'.format(name))
__salt__['file.symlink']('/proc/{0}/ns/net'.format(pid), '/var/run/netns/{0}'.format(name))
# Ensure that interface doesn't exists
interface_exists = 0 == __salt__['cmd.retcode']('ip netns exec {netns} ip address list {interface}'.format(
netns=name,
interface=interface_name
))
if interface_exists:
raise CommandExecutionError('Interface {interface} already exists in {container}'.format(
interface=interface_name,
container=name
))
# Create veth and bring it up
if __salt__['cmd.retcode']('ip link add name {veth} type veth peer name {veth}_c'.format(veth=random_veth)) != 0:
raise CommandExecutionError('Error while creating the veth pair {0}'.format(random_veth))
if __salt__['cmd.retcode']('ip link set dev {0} up'.format(random_veth)) != 0:
raise CommandExecutionError('Error while bringing up host-side veth {0}'.format(random_veth))
# Attach it to the container
attached = 0 == __salt__['cmd.retcode']('ip link set dev {veth}_c netns {container} name {interface_name}'.format(
veth=random_veth,
container=name,
interface_name=interface_name
))
if not attached:
raise CommandExecutionError('Error while attaching the veth {veth} to container {container}'.format(
veth=random_veth,
container=name
))
__salt__['file.remove']('/var/run/netns/{0}'.format(name))
if bridge is not None:
__salt__['bridge.addif'](bridge, random_veth)
|
saltstack/salt
|
salt/modules/lxc.py
|
start
|
python
|
def start(name, **kwargs):
'''
Start the named container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
lxc_config
path to a lxc config file
config file will be guessed from container name otherwise
.. versionadded:: 2015.8.0
use_vt
run the command through VT
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.start name
'''
path = kwargs.get('path', None)
cpath = get_root_path(path)
lxc_config = kwargs.get('lxc_config', None)
cmd = 'lxc-start'
if not lxc_config:
lxc_config = os.path.join(cpath, name, 'config')
# we try to start, even without config, if global opts are there
if os.path.exists(lxc_config):
cmd += ' -f {0}'.format(pipes.quote(lxc_config))
cmd += ' -d'
_ensure_exists(name, path=path)
if state(name, path=path) == 'frozen':
raise CommandExecutionError(
'Container \'{0}\' is frozen, use lxc.unfreeze'.format(name)
)
# lxc-start daemonize itself violently, we must not communicate with it
use_vt = kwargs.get('use_vt', None)
with_communicate = kwargs.get('with_communicate', False)
return _change_state(cmd, name, 'running',
stdout=None,
stderr=None,
stdin=None,
with_communicate=with_communicate,
path=path,
use_vt=use_vt)
|
Start the named container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
lxc_config
path to a lxc config file
config file will be guessed from container name otherwise
.. versionadded:: 2015.8.0
use_vt
run the command through VT
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.start name
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/lxc.py#L2386-L2437
|
[
"def state(name, path=None):\n '''\n Returns the state of a container.\n\n path\n path to the container parent directory (default: /var/lib/lxc)\n\n .. versionadded:: 2015.8.0\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' lxc.state name\n '''\n # Don't use _ensure_exists() here, it will mess with _change_state()\n\n cachekey = 'lxc.state.{0}{1}'.format(name, path)\n try:\n return __context__[cachekey]\n except KeyError:\n if not exists(name, path=path):\n __context__[cachekey] = None\n else:\n cmd = 'lxc-info'\n if path:\n cmd += ' -P {0}'.format(pipes.quote(path))\n cmd += ' -n {0}'.format(name)\n ret = __salt__['cmd.run_all'](cmd, python_shell=False)\n if ret['retcode'] != 0:\n _clear_context()\n raise CommandExecutionError(\n 'Unable to get state of container \\'{0}\\''.format(name)\n )\n c_infos = ret['stdout'].splitlines()\n c_state = None\n for c_info in c_infos:\n stat = c_info.split(':')\n if stat[0].lower() == 'state':\n c_state = stat[1].strip().lower()\n break\n __context__[cachekey] = c_state\n return __context__[cachekey]\n",
"def _change_state(cmd,\n name,\n expected,\n stdin=_marker,\n stdout=_marker,\n stderr=_marker,\n with_communicate=_marker,\n use_vt=_marker,\n path=None):\n pre = state(name, path=path)\n if pre == expected:\n return {'result': True,\n 'state': {'old': expected, 'new': expected},\n 'comment': 'Container \\'{0}\\' already {1}'\n .format(name, expected)}\n\n if cmd == 'lxc-destroy':\n # Kill the container first\n scmd = 'lxc-stop'\n if path:\n scmd += ' -P {0}'.format(pipes.quote(path))\n scmd += ' -k -n {0}'.format(name)\n __salt__['cmd.run'](scmd,\n python_shell=False)\n\n if path and ' -P ' not in cmd:\n cmd += ' -P {0}'.format(pipes.quote(path))\n cmd += ' -n {0}'.format(name)\n\n # certain lxc commands need to be taken with care (lxc-start)\n # as te command itself mess with double forks; we must not\n # communicate with it, but just wait for the exit status\n pkwargs = {'python_shell': False,\n 'redirect_stderr': True,\n 'with_communicate': with_communicate,\n 'use_vt': use_vt,\n 'stdin': stdin,\n 'stdout': stdout}\n for i in [a for a in pkwargs]:\n val = pkwargs[i]\n if val is _marker:\n pkwargs.pop(i, None)\n\n _cmdout = __salt__['cmd.run_all'](cmd, **pkwargs)\n\n if _cmdout['retcode'] != 0:\n raise CommandExecutionError(\n 'Error changing state for container \\'{0}\\' using command '\n '\\'{1}\\': {2}'.format(name, cmd, _cmdout['stdout'])\n )\n if expected is not None:\n # some commands do not wait, so we will\n rcmd = 'lxc-wait'\n if path:\n rcmd += ' -P {0}'.format(pipes.quote(path))\n rcmd += ' -n {0} -s {1}'.format(name, expected.upper())\n __salt__['cmd.run'](rcmd, python_shell=False, timeout=30)\n _clear_context()\n post = state(name, path=path)\n ret = {'result': post == expected,\n 'state': {'old': pre, 'new': post}}\n return ret\n",
"def get_root_path(path):\n '''\n Get the configured lxc root for containers\n\n .. versionadded:: 2015.8.0\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' lxc.get_root_path\n\n '''\n if not path:\n path = __opts__.get('lxc.root_path', DEFAULT_PATH)\n return path\n",
"def _ensure_exists(name, path=None):\n '''\n Raise an exception if the container does not exist\n '''\n if not exists(name, path=path):\n raise CommandExecutionError(\n 'Container \\'{0}\\' does not exist'.format(name)\n )\n"
] |
# -*- coding: utf-8 -*-
'''
Control Linux Containers via Salt
:depends: lxc package for distribution
lxc >= 1.0 (even beta alpha) is required
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import datetime
import copy
import string
import textwrap
import difflib
import logging
import tempfile
import os
import pipes
import time
import shutil
import re
import random
# Import salt libs
import salt.utils.args
import salt.utils.cloud
import salt.utils.data
import salt.utils.dictupdate
import salt.utils.files
import salt.utils.functools
import salt.utils.hashutils
import salt.utils.network
import salt.utils.odict
import salt.utils.path
import salt.utils.stringutils
from salt.exceptions import CommandExecutionError, SaltInvocationError
import salt.config
from salt.utils.versions import LooseVersion as _LooseVersion
# Import 3rd-party libs
from salt.ext import six
# pylint: disable=import-error,no-name-in-module
from salt.ext.six.moves import range # pylint: disable=redefined-builtin
from salt.ext.six.moves.urllib.parse import urlparse as _urlparse
# pylint: enable=import-error,no-name-in-module
# Set up logging
log = logging.getLogger(__name__)
# Don't shadow built-in's.
__func_alias__ = {
'list_': 'list',
'ls_': 'ls'
}
__virtualname__ = 'lxc'
DEFAULT_NIC = 'eth0'
DEFAULT_BR = 'br0'
SEED_MARKER = '/lxc.initial_seed'
EXEC_DRIVER = 'lxc-attach'
DEFAULT_PATH = '/var/lib/lxc'
_marker = object()
def __virtual__():
if salt.utils.path.which('lxc-start'):
return __virtualname__
# To speed up the whole thing, we decided to not use the
# subshell way and assume things are in place for lxc
# Discussion made by @kiorky and @thatch45
# lxc-version presence is not sufficient, in lxc1.0 alpha
# (precise backports), we have it and it is sufficient
# for the module to execute.
# elif salt.utils.path.which('lxc-version'):
# passed = False
# try:
# passed = subprocess.check_output(
# 'lxc-version').split(':')[1].strip() >= '1.0'
# except Exception:
# pass
# if not passed:
# log.warning('Support for lxc < 1.0 may be incomplete.')
# return 'lxc'
# return False
#
return (False, 'The lxc execution module cannot be loaded: the lxc-start binary is not in the path.')
def get_root_path(path):
'''
Get the configured lxc root for containers
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.get_root_path
'''
if not path:
path = __opts__.get('lxc.root_path', DEFAULT_PATH)
return path
def version():
'''
Return the actual lxc client version
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.version
'''
k = 'lxc.version'
if not __context__.get(k, None):
cversion = __salt__['cmd.run_all']('lxc-info --version')
if not cversion['retcode']:
ver = _LooseVersion(cversion['stdout'])
if ver < _LooseVersion('1.0'):
raise CommandExecutionError('LXC should be at least 1.0')
__context__[k] = "{0}".format(ver)
return __context__.get(k, None)
def _clear_context():
'''
Clear any lxc variables set in __context__
'''
for var in [x for x in __context__ if x.startswith('lxc.')]:
log.trace('Clearing __context__[\'%s\']', var)
__context__.pop(var, None)
def _ip_sort(ip):
'''Ip sorting'''
idx = '001'
if ip == '127.0.0.1':
idx = '200'
if ip == '::1':
idx = '201'
elif '::' in ip:
idx = '100'
return '{0}___{1}'.format(idx, ip)
def search_lxc_bridges():
'''
Search which bridges are potentially available as LXC bridges
CLI Example:
.. code-block:: bash
salt '*' lxc.search_lxc_bridges
'''
bridges = __context__.get('lxc.bridges', None)
# either match not yet called or no bridges were found
# to handle the case where lxc was not installed on the first
# call
if not bridges:
bridges = set()
running_bridges = set()
bridges.add(DEFAULT_BR)
try:
output = __salt__['cmd.run_all']('brctl show')
for line in output['stdout'].splitlines()[1:]:
if not line.startswith(' '):
running_bridges.add(line.split()[0].strip())
except (SaltInvocationError, CommandExecutionError):
pass
for ifc, ip in six.iteritems(
__grains__.get('ip_interfaces', {})
):
if ifc in running_bridges:
bridges.add(ifc)
elif os.path.exists(
'/sys/devices/virtual/net/{0}/bridge'.format(ifc)
):
bridges.add(ifc)
bridges = list(bridges)
# if we found interfaces that have lxc in their names
# we filter them as being the potential lxc bridges
# we also try to default on br0 on other cases
def sort_bridges(a):
pref = 'z'
if 'lxc' in a:
pref = 'a'
elif 'br0' == a:
pref = 'c'
return '{0}_{1}'.format(pref, a)
bridges.sort(key=sort_bridges)
__context__['lxc.bridges'] = bridges
return bridges
def search_lxc_bridge():
'''
Search the first bridge which is potentially available as LXC bridge
CLI Example:
.. code-block:: bash
salt '*' lxc.search_lxc_bridge
'''
return search_lxc_bridges()[0]
def _get_salt_config(config, **kwargs):
if not config:
config = kwargs.get('minion', {})
if not config:
config = {}
config.setdefault('master',
kwargs.get('master',
__opts__.get('master',
__opts__['id'])))
config.setdefault(
'master_port',
kwargs.get('master_port',
__opts__.get('master_port',
__opts__.get('ret_port',
__opts__.get('4506')))))
if not config['master']:
config = {}
return config
def cloud_init_interface(name, vm_=None, **kwargs):
'''
Interface between salt.cloud.lxc driver and lxc.init
``vm_`` is a mapping of vm opts in the salt.cloud format
as documented for the lxc driver.
This can be used either:
- from the salt cloud driver
- because you find the argument to give easier here
than using directly lxc.init
.. warning::
BE REALLY CAREFUL CHANGING DEFAULTS !!!
IT'S A RETRO COMPATIBLE INTERFACE WITH
THE SALT CLOUD DRIVER (ask kiorky).
name
name of the lxc container to create
pub_key
public key to preseed the minion with.
Can be the keycontent or a filepath
priv_key
private key to preseed the minion with.
Can be the keycontent or a filepath
path
path to the container parent directory (default: /var/lib/lxc)
.. versionadded:: 2015.8.0
profile
:ref:`profile <tutorial-lxc-profiles-container>` selection
network_profile
:ref:`network profile <tutorial-lxc-profiles-network>` selection
nic_opts
per interface settings compatibles with
network profile (ipv4/ipv6/link/gateway/mac/netmask)
eg::
- {'eth0': {'mac': '00:16:3e:01:29:40',
'gateway': None, (default)
'link': 'br0', (default)
'gateway': None, (default)
'netmask': '', (default)
'ip': '22.1.4.25'}}
unconditional_install
given to lxc.bootstrap (see relative doc)
force_install
given to lxc.bootstrap (see relative doc)
config
any extra argument for the salt minion config
dnsservers
list of DNS servers to set inside the container
dns_via_dhcp
do not set the dns servers, let them be set by the dhcp.
autostart
autostart the container at boot time
password
administrative password for the container
bootstrap_delay
delay before launching bootstrap script at Container init
.. warning::
Legacy but still supported options:
from_container
which container we use as a template
when running lxc.clone
image
which template do we use when we
are using lxc.create. This is the default
mode unless you specify something in from_container
backing
which backing store to use.
Values can be: overlayfs, dir(default), lvm, zfs, brtfs
fstype
When using a blockdevice level backing store,
which filesystem to use on
size
When using a blockdevice level backing store,
which size for the filesystem to use on
snapshot
Use snapshot when cloning the container source
vgname
if using LVM: vgname
lvname
if using LVM: lvname
thinpool:
if using LVM: thinpool
ip
ip for the primary nic
mac
mac address for the primary nic
netmask
netmask for the primary nic (24)
= ``vm_.get('netmask', '24')``
bridge
bridge for the primary nic (lxcbr0)
gateway
network gateway for the container
additional_ips
additional ips which will be wired on the main bridge (br0)
which is connected to internet.
Be aware that you may use manual virtual mac addresses
providen by you provider (online, ovh, etc).
This is a list of mappings {ip: '', mac: '', netmask:''}
Set gateway to None and an interface with a gateway
to escape from another interface that eth0.
eg::
- {'mac': '00:16:3e:01:29:40',
'gateway': None, (default)
'link': 'br0', (default)
'netmask': '', (default)
'ip': '22.1.4.25'}
users
administrative users for the container
default: [root] and [root, ubuntu] on ubuntu
default_nic
name of the first interface, you should
really not override this
CLI Example:
.. code-block:: bash
salt '*' lxc.cloud_init_interface foo
'''
if vm_ is None:
vm_ = {}
vm_ = copy.deepcopy(vm_)
vm_ = salt.utils.dictupdate.update(vm_, kwargs)
profile_data = copy.deepcopy(
vm_.get('lxc_profile',
vm_.get('profile', {})))
if not isinstance(profile_data, (dict, six.string_types)):
profile_data = {}
profile = get_container_profile(profile_data)
def _cloud_get(k, default=None):
return vm_.get(k, profile.get(k, default))
if name is None:
name = vm_['name']
# if we are on ubuntu, default to ubuntu
default_template = ''
if __grains__.get('os', '') in ['Ubuntu']:
default_template = 'ubuntu'
image = _cloud_get('image')
if not image:
_cloud_get('template', default_template)
backing = _cloud_get('backing', 'dir')
if image:
profile['template'] = image
vgname = _cloud_get('vgname', None)
if vgname:
profile['vgname'] = vgname
if backing:
profile['backing'] = backing
snapshot = _cloud_get('snapshot', False)
autostart = bool(_cloud_get('autostart', True))
dnsservers = _cloud_get('dnsservers', [])
dns_via_dhcp = _cloud_get('dns_via_dhcp', True)
password = _cloud_get('password', 's3cr3t')
password_encrypted = _cloud_get('password_encrypted', False)
fstype = _cloud_get('fstype', None)
lvname = _cloud_get('lvname', None)
thinpool = _cloud_get('thinpool', None)
pub_key = _cloud_get('pub_key', None)
priv_key = _cloud_get('priv_key', None)
size = _cloud_get('size', '20G')
script = _cloud_get('script', None)
script_args = _cloud_get('script_args', None)
users = _cloud_get('users', None)
if users is None:
users = []
ssh_username = _cloud_get('ssh_username', None)
if ssh_username and (ssh_username not in users):
users.append(ssh_username)
network_profile = _cloud_get('network_profile', None)
nic_opts = kwargs.get('nic_opts', None)
netmask = _cloud_get('netmask', '24')
path = _cloud_get('path', None)
bridge = _cloud_get('bridge', None)
gateway = _cloud_get('gateway', None)
unconditional_install = _cloud_get('unconditional_install', False)
force_install = _cloud_get('force_install', True)
config = _get_salt_config(_cloud_get('config', {}), **vm_)
default_nic = _cloud_get('default_nic', DEFAULT_NIC)
# do the interface with lxc.init mainly via nic_opts
# to avoid extra and confusing extra use cases.
if not isinstance(nic_opts, dict):
nic_opts = salt.utils.odict.OrderedDict()
# have a reference to the default nic
eth0 = nic_opts.setdefault(default_nic,
salt.utils.odict.OrderedDict())
# lxc config is based of ifc order, be sure to use odicts.
if not isinstance(nic_opts, salt.utils.odict.OrderedDict):
bnic_opts = salt.utils.odict.OrderedDict()
bnic_opts.update(nic_opts)
nic_opts = bnic_opts
gw = None
# legacy salt.cloud scheme for network interfaces settings support
bridge = _cloud_get('bridge', None)
ip = _cloud_get('ip', None)
mac = _cloud_get('mac', None)
if ip:
fullip = ip
if netmask:
fullip += '/{0}'.format(netmask)
eth0['ipv4'] = fullip
if mac is not None:
eth0['mac'] = mac
for ix, iopts in enumerate(_cloud_get("additional_ips", [])):
ifh = "eth{0}".format(ix+1)
ethx = nic_opts.setdefault(ifh, {})
if gw is None:
gw = iopts.get('gateway', ethx.get('gateway', None))
if gw:
# only one and only one default gateway is allowed !
eth0.pop('gateway', None)
gateway = None
# even if the gateway if on default "eth0" nic
# and we popped it will work
# as we reinject or set it here.
ethx['gateway'] = gw
elink = iopts.get('link', ethx.get('link', None))
if elink:
ethx['link'] = elink
# allow dhcp
aip = iopts.get('ipv4', iopts.get('ip', None))
if aip:
ethx['ipv4'] = aip
nm = iopts.get('netmask', '')
if nm:
ethx['ipv4'] += '/{0}'.format(nm)
for i in ('mac', 'hwaddr'):
if i in iopts:
ethx['mac'] = iopts[i]
break
if 'mac' not in ethx:
ethx['mac'] = salt.utils.network.gen_mac()
# last round checking for unique gateway and such
gw = None
for ethx in [a for a in nic_opts]:
ndata = nic_opts[ethx]
if gw:
ndata.pop('gateway', None)
if 'gateway' in ndata:
gw = ndata['gateway']
gateway = None
# only use a default bridge / gateway if we configured them
# via the legacy salt cloud configuration style.
# On other cases, we should rely on settings provided by the new
# salt lxc network profile style configuration which can
# be also be overridden or a per interface basis via the nic_opts dict.
if bridge:
eth0['link'] = bridge
if gateway:
eth0['gateway'] = gateway
#
lxc_init_interface = {}
lxc_init_interface['name'] = name
lxc_init_interface['config'] = config
lxc_init_interface['memory'] = _cloud_get('memory', 0) # nolimit
lxc_init_interface['pub_key'] = pub_key
lxc_init_interface['priv_key'] = priv_key
lxc_init_interface['nic_opts'] = nic_opts
for clone_from in ['clone_from', 'clone', 'from_container']:
# clone_from should default to None if not available
lxc_init_interface['clone_from'] = _cloud_get(clone_from, None)
if lxc_init_interface['clone_from'] is not None:
break
lxc_init_interface['profile'] = profile
lxc_init_interface['snapshot'] = snapshot
lxc_init_interface['dnsservers'] = dnsservers
lxc_init_interface['fstype'] = fstype
lxc_init_interface['path'] = path
lxc_init_interface['vgname'] = vgname
lxc_init_interface['size'] = size
lxc_init_interface['lvname'] = lvname
lxc_init_interface['thinpool'] = thinpool
lxc_init_interface['force_install'] = force_install
lxc_init_interface['unconditional_install'] = (
unconditional_install
)
lxc_init_interface['bootstrap_url'] = script
lxc_init_interface['bootstrap_args'] = script_args
lxc_init_interface['bootstrap_shell'] = _cloud_get('bootstrap_shell', 'sh')
lxc_init_interface['bootstrap_delay'] = _cloud_get('bootstrap_delay', None)
lxc_init_interface['autostart'] = autostart
lxc_init_interface['users'] = users
lxc_init_interface['password'] = password
lxc_init_interface['password_encrypted'] = password_encrypted
# be sure not to let objects goes inside the return
# as this return will be msgpacked for use in the runner !
lxc_init_interface['network_profile'] = network_profile
for i in ['cpu', 'cpuset', 'cpushare']:
if _cloud_get(i, None):
try:
lxc_init_interface[i] = vm_[i]
except KeyError:
lxc_init_interface[i] = profile[i]
return lxc_init_interface
def _get_profile(key, name, **kwargs):
if isinstance(name, dict):
profilename = name.pop('name', None)
return _get_profile(key, profilename, **name)
if name is None:
profile_match = {}
else:
profile_match = \
__salt__['config.get'](
'lxc.{1}:{0}'.format(name, key),
default=None,
merge='recurse'
)
if profile_match is None:
# No matching profile, make the profile an empty dict so that
# overrides can be applied below.
profile_match = {}
if not isinstance(profile_match, dict):
raise CommandExecutionError('lxc.{0} must be a dictionary'.format(key))
# Overlay the kwargs to override matched profile data
overrides = salt.utils.args.clean_kwargs(**copy.deepcopy(kwargs))
profile_match = salt.utils.dictupdate.update(
copy.deepcopy(profile_match),
overrides
)
return profile_match
def get_container_profile(name=None, **kwargs):
'''
.. versionadded:: 2015.5.0
Gather a pre-configured set of container configuration parameters. If no
arguments are passed, an empty profile is returned.
Profiles can be defined in the minion or master config files, or in pillar
or grains, and are loaded using :mod:`config.get
<salt.modules.config.get>`. The key under which LXC profiles must be
configured is ``lxc.container_profile.profile_name``. An example container
profile would be as follows:
.. code-block:: yaml
lxc.container_profile:
ubuntu:
template: ubuntu
backing: lvm
vgname: lxc
size: 1G
Parameters set in a profile can be overridden by passing additional
container creation arguments (such as the ones passed to :mod:`lxc.create
<salt.modules.lxc.create>`) to this function.
A profile can be defined either as the name of the profile, or a dictionary
of variable names and values. See the :ref:`LXC Tutorial
<tutorial-lxc-profiles>` for more information on how to use LXC profiles.
CLI Example:
.. code-block:: bash
salt-call lxc.get_container_profile centos
salt-call lxc.get_container_profile ubuntu template=ubuntu backing=overlayfs
'''
profile = _get_profile('container_profile', name, **kwargs)
return profile
def get_network_profile(name=None, **kwargs):
'''
.. versionadded:: 2015.5.0
Gather a pre-configured set of network configuration parameters. If no
arguments are passed, the following default profile is returned:
.. code-block:: python
{'eth0': {'link': 'br0', 'type': 'veth', 'flags': 'up'}}
Profiles can be defined in the minion or master config files, or in pillar
or grains, and are loaded using :mod:`config.get
<salt.modules.config.get>`. The key under which LXC profiles must be
configured is ``lxc.network_profile``. An example network profile would be
as follows:
.. code-block:: yaml
lxc.network_profile.centos:
eth0:
link: br0
type: veth
flags: up
To disable networking entirely:
.. code-block:: yaml
lxc.network_profile.centos:
eth0:
disable: true
Parameters set in a profile can be overridden by passing additional
arguments to this function.
A profile can be passed either as the name of the profile, or a
dictionary of variable names and values. See the :ref:`LXC Tutorial
<tutorial-lxc-profiles>` for more information on how to use network
profiles.
.. warning::
The ``ipv4``, ``ipv6``, ``gateway``, and ``link`` (bridge) settings in
network profiles will only work if the container doesn't redefine the
network configuration (for example in
``/etc/sysconfig/network-scripts/ifcfg-<interface_name>`` on
RHEL/CentOS, or ``/etc/network/interfaces`` on Debian/Ubuntu/etc.)
CLI Example:
.. code-block:: bash
salt-call lxc.get_network_profile default
'''
profile = _get_profile('network_profile', name, **kwargs)
return profile
def _rand_cpu_str(cpu):
'''
Return a random subset of cpus for the cpuset config
'''
cpu = int(cpu)
avail = __salt__['status.nproc']()
if cpu < avail:
return '0-{0}'.format(avail)
to_set = set()
while len(to_set) < cpu:
choice = random.randint(0, avail - 1)
if choice not in to_set:
to_set.add(six.text_type(choice))
return ','.join(sorted(to_set))
def _network_conf(conf_tuples=None, **kwargs):
'''
Network configuration defaults
network_profile
as for containers, we can either call this function
either with a network_profile dict or network profile name
in the kwargs
nic_opts
overrides or extra nics in the form {nic_name: {set: tings}
'''
nic = kwargs.get('network_profile', None)
ret = []
nic_opts = kwargs.get('nic_opts', {})
if nic_opts is None:
# coming from elsewhere
nic_opts = {}
if not conf_tuples:
conf_tuples = []
old = _get_veths(conf_tuples)
if not old:
old = {}
# if we have a profile name, get the profile and load the network settings
# this will obviously by default look for a profile called "eth0"
# or by what is defined in nic_opts
# and complete each nic settings by sane defaults
if nic and isinstance(nic, (six.string_types, dict)):
nicp = get_network_profile(nic)
else:
nicp = {}
if DEFAULT_NIC not in nicp:
nicp[DEFAULT_NIC] = {}
kwargs = copy.deepcopy(kwargs)
gateway = kwargs.pop('gateway', None)
bridge = kwargs.get('bridge', None)
if nic_opts:
for dev, args in six.iteritems(nic_opts):
ethx = nicp.setdefault(dev, {})
try:
ethx = salt.utils.dictupdate.update(ethx, args)
except AttributeError:
raise SaltInvocationError('Invalid nic_opts configuration')
ifs = [a for a in nicp]
ifs += [a for a in old if a not in nicp]
ifs.sort()
gateway_set = False
for dev in ifs:
args = nicp.get(dev, {})
opts = nic_opts.get(dev, {}) if nic_opts else {}
old_if = old.get(dev, {})
disable = opts.get('disable', args.get('disable', False))
if disable:
continue
mac = opts.get('mac',
opts.get('hwaddr',
args.get('mac',
args.get('hwaddr', ''))))
type_ = opts.get('type', args.get('type', ''))
flags = opts.get('flags', args.get('flags', ''))
link = opts.get('link', args.get('link', ''))
ipv4 = opts.get('ipv4', args.get('ipv4', ''))
ipv6 = opts.get('ipv6', args.get('ipv6', ''))
infos = salt.utils.odict.OrderedDict([
('lxc.network.type', {
'test': not type_,
'value': type_,
'old': old_if.get('lxc.network.type'),
'default': 'veth'}),
('lxc.network.name', {
'test': False,
'value': dev,
'old': dev,
'default': dev}),
('lxc.network.flags', {
'test': not flags,
'value': flags,
'old': old_if.get('lxc.network.flags'),
'default': 'up'}),
('lxc.network.link', {
'test': not link,
'value': link,
'old': old_if.get('lxc.network.link'),
'default': search_lxc_bridge()}),
('lxc.network.hwaddr', {
'test': not mac,
'value': mac,
'old': old_if.get('lxc.network.hwaddr'),
'default': salt.utils.network.gen_mac()}),
('lxc.network.ipv4', {
'test': not ipv4,
'value': ipv4,
'old': old_if.get('lxc.network.ipv4', ''),
'default': None}),
('lxc.network.ipv6', {
'test': not ipv6,
'value': ipv6,
'old': old_if.get('lxc.network.ipv6', ''),
'default': None})])
# for each parameter, if not explicitly set, the
# config value present in the LXC configuration should
# take precedence over the profile configuration
for info in list(infos.keys()):
bundle = infos[info]
if bundle['test']:
if bundle['old']:
bundle['value'] = bundle['old']
elif bundle['default']:
bundle['value'] = bundle['default']
for info, data in six.iteritems(infos):
if data['value']:
ret.append({info: data['value']})
for key, val in six.iteritems(args):
if key == 'link' and bridge:
val = bridge
val = opts.get(key, val)
if key in [
'type', 'flags', 'name',
'gateway', 'mac', 'link', 'ipv4', 'ipv6'
]:
continue
ret.append({'lxc.network.{0}'.format(key): val})
# gateway (in automode) must be appended following network conf !
if not gateway:
gateway = args.get('gateway', None)
if gateway is not None and not gateway_set:
ret.append({'lxc.network.ipv4.gateway': gateway})
# only one network gateway ;)
gateway_set = True
# normally, this won't happen
# set the gateway if specified even if we did
# not managed the network underlying
if gateway is not None and not gateway_set:
ret.append({'lxc.network.ipv4.gateway': gateway})
# only one network gateway ;)
gateway_set = True
new = _get_veths(ret)
# verify that we did not loose the mac settings
for iface in [a for a in new]:
ndata = new[iface]
nmac = ndata.get('lxc.network.hwaddr', '')
ntype = ndata.get('lxc.network.type', '')
omac, otype = '', ''
if iface in old:
odata = old[iface]
omac = odata.get('lxc.network.hwaddr', '')
otype = odata.get('lxc.network.type', '')
# default for network type is setted here
# attention not to change the network type
# without a good and explicit reason to.
if otype and not ntype:
ntype = otype
if not ntype:
ntype = 'veth'
new[iface]['lxc.network.type'] = ntype
if omac and not nmac:
new[iface]['lxc.network.hwaddr'] = omac
ret = []
for val in six.itervalues(new):
for row in val:
ret.append(salt.utils.odict.OrderedDict([(row, val[row])]))
# on old versions of lxc, still support the gateway auto mode
# if we didn't explicitly say no to
# (lxc.network.ipv4.gateway: auto)
if _LooseVersion(version()) <= _LooseVersion('1.0.7') and \
True not in ['lxc.network.ipv4.gateway' in a for a in ret] and \
True in ['lxc.network.ipv4' in a for a in ret]:
ret.append({'lxc.network.ipv4.gateway': 'auto'})
return ret
def _get_lxc_default_data(**kwargs):
kwargs = copy.deepcopy(kwargs)
ret = {}
for k in ['utsname', 'rootfs']:
val = kwargs.get(k, None)
if val is not None:
ret['lxc.{0}'.format(k)] = val
autostart = kwargs.get('autostart')
# autostart can have made in kwargs, but with the None
# value which is invalid, we need an explicit boolean
# autostart = on is the default.
if autostart is None:
autostart = True
# we will set the regular lxc marker to restart container at
# machine (re)boot only if we did not explicitly ask
# not to touch to the autostart settings via
# autostart == 'keep'
if autostart != 'keep':
if autostart:
ret['lxc.start.auto'] = '1'
else:
ret['lxc.start.auto'] = '0'
memory = kwargs.get('memory')
if memory is not None:
# converting the config value from MB to bytes
ret['lxc.cgroup.memory.limit_in_bytes'] = memory * 1024 * 1024
cpuset = kwargs.get('cpuset')
if cpuset:
ret['lxc.cgroup.cpuset.cpus'] = cpuset
cpushare = kwargs.get('cpushare')
cpu = kwargs.get('cpu')
if cpushare:
ret['lxc.cgroup.cpu.shares'] = cpushare
if cpu and not cpuset:
ret['lxc.cgroup.cpuset.cpus'] = _rand_cpu_str(cpu)
return ret
def _config_list(conf_tuples=None, only_net=False, **kwargs):
'''
Return a list of dicts from the salt level configurations
conf_tuples
_LXCConfig compatible list of entries which can contain
- string line
- tuple (lxc config param,value)
- dict of one entry: {lxc config param: value)
only_net
by default we add to the tuples a reflection of both
the real config if avalaible and a certain amount of
default values like the cpu parameters, the memory
and etc.
On the other hand, we also no matter the case reflect
the network configuration computed from the actual config if
available and given values.
if no_default_loads is set, we will only
reflect the network configuration back to the conf tuples
list
'''
# explicit cast
only_net = bool(only_net)
if not conf_tuples:
conf_tuples = []
kwargs = copy.deepcopy(kwargs)
ret = []
if not only_net:
default_data = _get_lxc_default_data(**kwargs)
for k, val in six.iteritems(default_data):
ret.append({k: val})
net_datas = _network_conf(conf_tuples=conf_tuples, **kwargs)
ret.extend(net_datas)
return ret
def _get_veths(net_data):
'''
Parse the nic setup inside lxc conf tuples back to a dictionary indexed by
network interface
'''
if isinstance(net_data, dict):
net_data = list(net_data.items())
nics = salt.utils.odict.OrderedDict()
current_nic = salt.utils.odict.OrderedDict()
no_names = True
for item in net_data:
if item and isinstance(item, dict):
item = list(item.items())[0]
# skip LXC configuration comment lines, and play only with tuples conf
elif isinstance(item, six.string_types):
# deal with reflection of commented lxc configs
sitem = item.strip()
if sitem.startswith('#') or not sitem:
continue
elif '=' in item:
item = tuple([a.strip() for a in item.split('=', 1)])
if item[0] == 'lxc.network.type':
current_nic = salt.utils.odict.OrderedDict()
if item[0] == 'lxc.network.name':
no_names = False
nics[item[1].strip()] = current_nic
current_nic[item[0].strip()] = item[1].strip()
# if not ethernet card name has been collected, assuming we collected
# data for eth0
if no_names and current_nic:
nics[DEFAULT_NIC] = current_nic
return nics
class _LXCConfig(object):
'''
LXC configuration data
'''
pattern = re.compile(r'^(\S+)(\s*)(=)(\s*)(.*)')
non_interpretable_pattern = re.compile(r'^((#.*)|(\s*))$')
def __init__(self, **kwargs):
kwargs = copy.deepcopy(kwargs)
self.name = kwargs.pop('name', None)
path = get_root_path(kwargs.get('path', None))
self.data = []
if self.name:
self.path = os.path.join(path, self.name, 'config')
if os.path.isfile(self.path):
with salt.utils.files.fopen(self.path) as fhr:
for line in salt.utils.data.decode(fhr.readlines()):
match = self.pattern.findall((line.strip()))
if match:
self.data.append((match[0][0], match[0][-1]))
match = self.non_interpretable_pattern.findall(
(line.strip()))
if match:
self.data.append(('', match[0][0]))
else:
self.path = None
def _replace(key, val):
if val:
self._filter_data(key)
self.data.append((key, val))
default_data = _get_lxc_default_data(**kwargs)
for key, val in six.iteritems(default_data):
_replace(key, val)
old_net = self._filter_data('lxc.network')
net_datas = _network_conf(conf_tuples=old_net, **kwargs)
if net_datas:
for row in net_datas:
self.data.extend(list(row.items()))
# be sure to reset harmful settings
for idx in ['lxc.cgroup.memory.limit_in_bytes']:
if not default_data.get(idx):
self._filter_data(idx)
def as_string(self):
chunks = ('{0[0]}{1}{0[1]}'.format(item, (' = ' if item[0] else '')) for item in self.data)
return '\n'.join(chunks) + '\n'
def write(self):
if self.path:
content = self.as_string()
# 2 step rendering to be sure not to open/wipe the config
# before as_string succeeds.
with salt.utils.files.fopen(self.path, 'w') as fic:
fic.write(salt.utils.stringutils.to_str(content))
fic.flush()
def tempfile(self):
# this might look like the function name is shadowing the
# module, but it's not since the method belongs to the class
ntf = tempfile.NamedTemporaryFile()
ntf.write(self.as_string())
ntf.flush()
return ntf
def _filter_data(self, pattern):
'''
Removes parameters which match the pattern from the config data
'''
removed = []
filtered = []
for param in self.data:
if not param[0].startswith(pattern):
filtered.append(param)
else:
removed.append(param)
self.data = filtered
return removed
def _get_base(**kwargs):
'''
If the needed base does not exist, then create it, if it does exist
create nothing and return the name of the base lxc container so
it can be cloned.
'''
profile = get_container_profile(copy.deepcopy(kwargs.get('profile')))
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, _marker)
profile_match = profile.pop(key, default)
# let kwarg overrides be the preferred choice
if kw_overrides_match is _marker:
return profile_match
return kw_overrides_match
template = select('template')
image = select('image')
vgname = select('vgname')
path = kwargs.get('path', None)
# remove the above three variables from kwargs, if they exist, to avoid
# duplicates if create() is invoked below.
for param in ('path', 'image', 'vgname', 'template'):
kwargs.pop(param, None)
if image:
proto = _urlparse(image).scheme
img_tar = __salt__['cp.cache_file'](image)
img_name = os.path.basename(img_tar)
hash_ = salt.utils.hashutils.get_hash(
img_tar,
__salt__['config.get']('hash_type'))
name = '__base_{0}_{1}_{2}'.format(proto, img_name, hash_)
if not exists(name, path=path):
create(name, template=template, image=image,
path=path, vgname=vgname, **kwargs)
if vgname:
rootfs = os.path.join('/dev', vgname, name)
edit_conf(info(name, path=path)['config'],
out_format='commented', **{'lxc.rootfs': rootfs})
return name
elif template:
name = '__base_{0}'.format(template)
if not exists(name, path=path):
create(name, template=template, image=image, path=path,
vgname=vgname, **kwargs)
if vgname:
rootfs = os.path.join('/dev', vgname, name)
edit_conf(info(name, path=path)['config'],
out_format='commented', **{'lxc.rootfs': rootfs})
return name
return ''
def init(name,
config=None,
cpuset=None,
cpushare=None,
memory=None,
profile=None,
network_profile=None,
nic_opts=None,
cpu=None,
autostart=True,
password=None,
password_encrypted=None,
users=None,
dnsservers=None,
searchdomains=None,
bridge=None,
gateway=None,
pub_key=None,
priv_key=None,
force_install=False,
unconditional_install=False,
bootstrap_delay=None,
bootstrap_args=None,
bootstrap_shell=None,
bootstrap_url=None,
**kwargs):
'''
Initialize a new container.
This is a partial idempotent function as if it is already provisioned, we
will reset a bit the lxc configuration file but much of the hard work will
be escaped as markers will prevent re-execution of harmful tasks.
name
Name of the container
image
A tar archive to use as the rootfs for the container. Conflicts with
the ``template`` argument.
cpus
Select a random number of cpu cores and assign it to the cpuset, if the
cpuset option is set then this option will be ignored
cpuset
Explicitly define the cpus this container will be bound to
cpushare
cgroups cpu shares
autostart
autostart container on reboot
memory
cgroups memory limit, in MB
.. versionchanged:: 2015.5.0
If no value is passed, no limit is set. In earlier Salt versions,
not passing this value causes a 1024MB memory limit to be set, and
it was necessary to pass ``memory=0`` to set no limit.
gateway
the ipv4 gateway to use
the default does nothing more than lxcutils does
bridge
the bridge to use
the default does nothing more than lxcutils does
network_profile
Network profile to use for the container
.. versionadded:: 2015.5.0
nic_opts
Extra options for network interfaces, will override
``{"eth0": {"hwaddr": "aa:bb:cc:dd:ee:ff", "ipv4": "10.1.1.1", "ipv6": "2001:db8::ff00:42:8329"}}``
or
``{"eth0": {"hwaddr": "aa:bb:cc:dd:ee:ff", "ipv4": "10.1.1.1/24", "ipv6": "2001:db8::ff00:42:8329"}}``
users
Users for which the password defined in the ``password`` param should
be set. Can be passed as a comma separated list or a python list.
Defaults to just the ``root`` user.
password
Set the initial password for the users defined in the ``users``
parameter
password_encrypted : False
Set to ``True`` to denote a password hash instead of a plaintext
password
.. versionadded:: 2015.5.0
profile
A LXC profile (defined in config or pillar).
This can be either a real profile mapping or a string
to retrieve it in configuration
start
Start the newly-created container
dnsservers
list of dns servers to set in the container, default [] (no setting)
seed
Seed the container with the minion config. Default: ``True``
install
If salt-minion is not already installed, install it. Default: ``True``
config
Optional config parameters. By default, the id is set to
the name of the container.
master
salt master (default to minion's master)
master_port
salt master port (default to minion's master port)
pub_key
Explicit public key to preseed the minion with (optional).
This can be either a filepath or a string representing the key
priv_key
Explicit private key to preseed the minion with (optional).
This can be either a filepath or a string representing the key
approve_key
If explicit preseeding is not used;
Attempt to request key approval from the master. Default: ``True``
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
clone_from
Original from which to use a clone operation to create the container.
Default: ``None``
bootstrap_delay
Delay in seconds between end of container creation and bootstrapping.
Useful when waiting for container to obtain a DHCP lease.
.. versionadded:: 2015.5.0
bootstrap_url
See lxc.bootstrap
bootstrap_shell
See lxc.bootstrap
bootstrap_args
See lxc.bootstrap
force_install
Force installation even if salt-minion is detected,
this is the way to run vendor bootstrap scripts even
if a salt minion is already present in the container
unconditional_install
Run the script even if the container seems seeded
CLI Example:
.. code-block:: bash
salt 'minion' lxc.init name [cpuset=cgroups_cpuset] \\
[cpushare=cgroups_cpushare] [memory=cgroups_memory] \\
[nic=nic_profile] [profile=lxc_profile] \\
[nic_opts=nic_opts] [start=(True|False)] \\
[seed=(True|False)] [install=(True|False)] \\
[config=minion_config] [approve_key=(True|False) \\
[clone_from=original] [autostart=True] \\
[priv_key=/path_or_content] [pub_key=/path_or_content] \\
[bridge=lxcbr0] [gateway=10.0.3.1] \\
[dnsservers[dns1,dns2]] \\
[users=[foo]] [password='secret'] \\
[password_encrypted=(True|False)]
'''
ret = {'name': name,
'changes': {}}
profile = get_container_profile(copy.deepcopy(profile))
if not network_profile:
network_profile = profile.get('network_profile')
if not network_profile:
network_profile = DEFAULT_NIC
# Changes is a pointer to changes_dict['init']. This method is used so that
# we can have a list of changes as they are made, providing an ordered list
# of things that were changed.
changes_dict = {'init': []}
changes = changes_dict.get('init')
if users is None:
users = []
dusers = ['root']
for user in dusers:
if user not in users:
users.append(user)
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, _marker)
profile_match = profile.pop(key, default)
# let kwarg overrides be the preferred choice
if kw_overrides_match is _marker:
return profile_match
return kw_overrides_match
path = select('path')
bpath = get_root_path(path)
state_pre = state(name, path=path)
tvg = select('vgname')
vgname = tvg if tvg else __salt__['config.get']('lxc.vgname')
start_ = select('start', True)
autostart = select('autostart', autostart)
seed = select('seed', True)
install = select('install', True)
seed_cmd = select('seed_cmd')
salt_config = _get_salt_config(config, **kwargs)
approve_key = select('approve_key', True)
clone_from = select('clone_from')
# If using a volume group then set up to make snapshot cow clones
if vgname and not clone_from:
try:
kwargs['vgname'] = vgname
clone_from = _get_base(profile=profile, **kwargs)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = exc.strerror
if changes:
ret['changes'] = changes_dict
return ret
if not kwargs.get('snapshot') is False:
kwargs['snapshot'] = True
does_exist = exists(name, path=path)
to_reboot = False
remove_seed_marker = False
if does_exist:
pass
elif clone_from:
remove_seed_marker = True
try:
clone(name, clone_from, profile=profile, **kwargs)
changes.append({'create': 'Container cloned'})
except (SaltInvocationError, CommandExecutionError) as exc:
if 'already exists' in exc.strerror:
changes.append({'create': 'Container already exists'})
else:
ret['result'] = False
ret['comment'] = exc.strerror
if changes:
ret['changes'] = changes_dict
return ret
cfg = _LXCConfig(name=name, network_profile=network_profile,
nic_opts=nic_opts, bridge=bridge, path=path,
gateway=gateway, autostart=autostart,
cpuset=cpuset, cpushare=cpushare, memory=memory)
old_chunks = read_conf(cfg.path, out_format='commented')
cfg.write()
chunks = read_conf(cfg.path, out_format='commented')
if old_chunks != chunks:
to_reboot = True
else:
remove_seed_marker = True
cfg = _LXCConfig(network_profile=network_profile,
nic_opts=nic_opts, cpuset=cpuset, path=path,
bridge=bridge, gateway=gateway,
autostart=autostart,
cpushare=cpushare, memory=memory)
with cfg.tempfile() as cfile:
try:
create(name, config=cfile.name, profile=profile, **kwargs)
changes.append({'create': 'Container created'})
except (SaltInvocationError, CommandExecutionError) as exc:
if 'already exists' in exc.strerror:
changes.append({'create': 'Container already exists'})
else:
ret['comment'] = exc.strerror
if changes:
ret['changes'] = changes_dict
return ret
cpath = os.path.join(bpath, name, 'config')
old_chunks = []
if os.path.exists(cpath):
old_chunks = read_conf(cpath, out_format='commented')
new_cfg = _config_list(conf_tuples=old_chunks,
cpu=cpu,
network_profile=network_profile,
nic_opts=nic_opts, bridge=bridge,
cpuset=cpuset, cpushare=cpushare,
memory=memory)
if new_cfg:
edit_conf(cpath, out_format='commented', lxc_config=new_cfg)
chunks = read_conf(cpath, out_format='commented')
if old_chunks != chunks:
to_reboot = True
# last time to be sure any of our property is correctly applied
cfg = _LXCConfig(name=name, network_profile=network_profile,
nic_opts=nic_opts, bridge=bridge, path=path,
gateway=gateway, autostart=autostart,
cpuset=cpuset, cpushare=cpushare, memory=memory)
old_chunks = []
if os.path.exists(cfg.path):
old_chunks = read_conf(cfg.path, out_format='commented')
cfg.write()
chunks = read_conf(cfg.path, out_format='commented')
if old_chunks != chunks:
changes.append({'config': 'Container configuration updated'})
to_reboot = True
if to_reboot:
try:
stop(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
if changes:
ret['changes'] = changes_dict
return ret
if not does_exist or (does_exist and state(name, path=path) != 'running'):
try:
start(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
if changes:
ret['changes'] = changes_dict
return ret
if remove_seed_marker:
run(name,
'rm -f \'{0}\''.format(SEED_MARKER),
path=path,
chroot_fallback=False,
python_shell=False)
# set the default user/password, only the first time
if ret.get('result', True) and password:
gid = '/.lxc.initial_pass'
gids = [gid,
'/lxc.initial_pass',
'/.lxc.{0}.initial_pass'.format(name)]
if not any(retcode(name,
'test -e "{0}"'.format(x),
chroot_fallback=True,
path=path,
ignore_retcode=True) == 0
for x in gids):
# think to touch the default user generated by default templates
# which has a really unsecure passwords...
# root is defined as a member earlier in the code
for default_user in ['ubuntu']:
if (
default_user not in users and
retcode(name,
'id {0}'.format(default_user),
python_shell=False,
path=path,
chroot_fallback=True,
ignore_retcode=True) == 0
):
users.append(default_user)
for user in users:
try:
cret = set_password(name,
users=[user],
path=path,
password=password,
encrypted=password_encrypted)
except (SaltInvocationError, CommandExecutionError) as exc:
msg = '{0}: Failed to set password'.format(
user) + exc.strerror
# only hardfail in unrecoverable situation:
# root cannot be setted up
if user == 'root':
ret['comment'] = msg
ret['result'] = False
else:
log.debug(msg)
if ret.get('result', True):
changes.append({'password': 'Password(s) updated'})
if retcode(name,
('sh -c \'touch "{0}"; test -e "{0}"\''
.format(gid)),
path=path,
chroot_fallback=True,
ignore_retcode=True) != 0:
ret['comment'] = 'Failed to set password marker'
changes[-1]['password'] += '. ' + ret['comment'] + '.'
ret['result'] = False
# set dns servers if any, only the first time
if ret.get('result', True) and dnsservers:
# retro compatibility, test also old markers
gid = '/.lxc.initial_dns'
gids = [gid,
'/lxc.initial_dns',
'/lxc.{0}.initial_dns'.format(name)]
if not any(retcode(name,
'test -e "{0}"'.format(x),
chroot_fallback=True,
path=path,
ignore_retcode=True) == 0
for x in gids):
try:
set_dns(name,
path=path,
dnsservers=dnsservers,
searchdomains=searchdomains)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Failed to set DNS: ' + exc.strerror
ret['result'] = False
else:
changes.append({'dns': 'DNS updated'})
if retcode(name,
('sh -c \'touch "{0}"; test -e "{0}"\''
.format(gid)),
chroot_fallback=True,
path=path,
ignore_retcode=True) != 0:
ret['comment'] = 'Failed to set DNS marker'
changes[-1]['dns'] += '. ' + ret['comment'] + '.'
ret['result'] = False
# retro compatibility, test also old markers
if remove_seed_marker:
run(name,
'rm -f \'{0}\''.format(SEED_MARKER),
path=path,
python_shell=False)
gid = '/.lxc.initial_seed'
gids = [gid, '/lxc.initial_seed']
if (
any(retcode(name,
'test -e {0}'.format(x),
path=path,
chroot_fallback=True,
ignore_retcode=True) == 0
for x in gids) or not ret.get('result', True)
):
pass
elif seed or seed_cmd:
if seed:
try:
result = bootstrap(
name, config=salt_config, path=path,
approve_key=approve_key,
pub_key=pub_key, priv_key=priv_key,
install=install,
force_install=force_install,
unconditional_install=unconditional_install,
bootstrap_delay=bootstrap_delay,
bootstrap_url=bootstrap_url,
bootstrap_shell=bootstrap_shell,
bootstrap_args=bootstrap_args)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Bootstrap failed: ' + exc.strerror
ret['result'] = False
else:
if not result:
ret['comment'] = ('Bootstrap failed, see minion log for '
'more information')
ret['result'] = False
else:
changes.append(
{'bootstrap': 'Container successfully bootstrapped'}
)
elif seed_cmd:
try:
result = __salt__[seed_cmd](info(name, path=path)['rootfs'],
name,
salt_config)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = ('Bootstrap via seed_cmd \'{0}\' failed: {1}'
.format(seed_cmd, exc.strerror))
ret['result'] = False
else:
if not result:
ret['comment'] = ('Bootstrap via seed_cmd \'{0}\' failed, '
'see minion log for more information '
.format(seed_cmd))
ret['result'] = False
else:
changes.append(
{'bootstrap': 'Container successfully bootstrapped '
'using seed_cmd \'{0}\''
.format(seed_cmd)}
)
if ret.get('result', True) and not start_:
try:
stop(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
ret['result'] = False
state_post = state(name, path=path)
if state_pre != state_post:
changes.append({'state': {'old': state_pre, 'new': state_post}})
if ret.get('result', True):
ret['comment'] = ('Container \'{0}\' successfully initialized'
.format(name))
ret['result'] = True
if changes:
ret['changes'] = changes_dict
return ret
def cloud_init(name, vm_=None, **kwargs):
'''
Thin wrapper to lxc.init to be used from the saltcloud lxc driver
name
Name of the container
may be None and then guessed from saltcloud mapping
`vm_`
saltcloud mapping defaults for the vm
CLI Example:
.. code-block:: bash
salt '*' lxc.cloud_init foo
'''
init_interface = cloud_init_interface(name, vm_, **kwargs)
name = init_interface.pop('name', name)
return init(name, **init_interface)
def images(dist=None):
'''
.. versionadded:: 2015.5.0
List the available images for LXC's ``download`` template.
dist : None
Filter results to a single Linux distribution
CLI Examples:
.. code-block:: bash
salt myminion lxc.images
salt myminion lxc.images dist=centos
'''
out = __salt__['cmd.run_stdout'](
'lxc-create -n __imgcheck -t download -- --list',
ignore_retcode=True
)
if 'DIST' not in out:
raise CommandExecutionError(
'Unable to run the \'download\' template script. Is it installed?'
)
ret = {}
passed_header = False
for line in out.splitlines():
try:
distro, release, arch, variant, build_time = line.split()
except ValueError:
continue
if not passed_header:
if distro == 'DIST':
passed_header = True
continue
dist_list = ret.setdefault(distro, [])
dist_list.append({
'release': release,
'arch': arch,
'variant': variant,
'build_time': build_time,
})
if dist is not None:
return dict([(dist, ret.get(dist, []))])
return ret
def templates():
'''
.. versionadded:: 2015.5.0
List the available LXC template scripts installed on the minion
CLI Examples:
.. code-block:: bash
salt myminion lxc.templates
'''
try:
template_scripts = os.listdir('/usr/share/lxc/templates')
except OSError:
return []
else:
return [x[4:] for x in template_scripts if x.startswith('lxc-')]
def _after_ignition_network_profile(cmd,
ret,
name,
network_profile,
path,
nic_opts):
_clear_context()
if ret['retcode'] == 0 and exists(name, path=path):
if network_profile:
network_changes = apply_network_profile(name,
network_profile,
path=path,
nic_opts=nic_opts)
if network_changes:
log.info(
'Network changes from applying network profile \'%s\' '
'to newly-created container \'%s\':\n%s',
network_profile, name, network_changes
)
c_state = state(name, path=path)
return {'result': True,
'state': {'old': None, 'new': c_state}}
else:
if exists(name, path=path):
# destroy the container if it was partially created
cmd = 'lxc-destroy'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0}'.format(name)
__salt__['cmd.retcode'](cmd, python_shell=False)
raise CommandExecutionError(
'Container could not be created with cmd \'{0}\': {1}'
.format(cmd, ret['stderr'])
)
def create(name,
config=None,
profile=None,
network_profile=None,
nic_opts=None,
**kwargs):
'''
Create a new container.
name
Name of the container
config
The config file to use for the container. Defaults to system-wide
config (usually in /etc/lxc/lxc.conf).
profile
Profile to use in container creation (see
:mod:`lxc.get_container_profile
<salt.modules.lxc.get_container_profile>`). Values in a profile will be
overridden by the **Container Creation Arguments** listed below.
network_profile
Network profile to use for container
.. versionadded:: 2015.5.0
**Container Creation Arguments**
template
The template to use. For example, ``ubuntu`` or ``fedora``.
For a full list of available templates, check out
the :mod:`lxc.templates <salt.modules.lxc.templates>` function.
Conflicts with the ``image`` argument.
.. note::
The ``download`` template requires the following three parameters
to be defined in ``options``:
* **dist** - The name of the distribution
* **release** - Release name/version
* **arch** - Architecture of the container
The available images can be listed using the :mod:`lxc.images
<salt.modules.lxc.images>` function.
options
Template-specific options to pass to the lxc-create command. These
correspond to the long options (ones beginning with two dashes) that
the template script accepts. For example:
.. code-block:: bash
options='{"dist": "centos", "release": "6", "arch": "amd64"}'
For available template options, refer to the lxc template scripts
which are ususally located under ``/usr/share/lxc/templates``,
or run ``lxc-create -t <template> -h``.
image
A tar archive to use as the rootfs for the container. Conflicts with
the ``template`` argument.
backing
The type of storage to use. Set to ``lvm`` to use an LVM group.
Defaults to filesystem within /var/lib/lxc.
fstype
Filesystem type to use on LVM logical volume
size : 1G
Size of the volume to create. Only applicable if ``backing=lvm``.
vgname : lxc
Name of the LVM volume group in which to create the volume for this
container. Only applicable if ``backing=lvm``.
lvname
Name of the LVM logical volume in which to create the volume for this
container. Only applicable if ``backing=lvm``.
thinpool
Name of a pool volume that will be used for thin-provisioning this
container. Only applicable if ``backing=lvm``.
nic_opts
give extra opts overriding network profile values
path
parent path for the container creation (default: /var/lib/lxc)
zfsroot
Name of the ZFS root in which to create the volume for this container.
Only applicable if ``backing=zfs``. (default: tank/lxc)
.. versionadded:: 2015.8.0
'''
# Required params for 'download' template
download_template_deps = ('dist', 'release', 'arch')
cmd = 'lxc-create -n {0}'.format(name)
profile = get_container_profile(copy.deepcopy(profile))
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, None)
profile_match = profile.pop(key, default)
# Return the profile match if the the kwarg match was None, as the
# lxc.present state will pass these kwargs set to None by default.
if kw_overrides_match is None:
return profile_match
return kw_overrides_match
path = select('path')
if exists(name, path=path):
raise CommandExecutionError(
'Container \'{0}\' already exists'.format(name)
)
tvg = select('vgname')
vgname = tvg if tvg else __salt__['config.get']('lxc.vgname')
# The 'template' and 'image' params conflict
template = select('template')
image = select('image')
if template and image:
raise SaltInvocationError(
'Only one of \'template\' and \'image\' is permitted'
)
elif not any((template, image, profile)):
raise SaltInvocationError(
'At least one of \'template\', \'image\', and \'profile\' is '
'required'
)
options = select('options') or {}
backing = select('backing')
if vgname and not backing:
backing = 'lvm'
lvname = select('lvname')
thinpool = select('thinpool')
fstype = select('fstype')
size = select('size', '1G')
zfsroot = select('zfsroot')
if backing in ('dir', 'overlayfs', 'btrfs', 'zfs'):
fstype = None
size = None
# some backends won't support some parameters
if backing in ('aufs', 'dir', 'overlayfs', 'btrfs'):
lvname = vgname = thinpool = None
if image:
img_tar = __salt__['cp.cache_file'](image)
template = os.path.join(
os.path.dirname(salt.__file__),
'templates',
'lxc',
'salt_tarball')
options['imgtar'] = img_tar
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
if not os.path.exists(path):
os.makedirs(path)
if config:
cmd += ' -f {0}'.format(config)
if template:
cmd += ' -t {0}'.format(template)
if backing:
backing = backing.lower()
cmd += ' -B {0}'.format(backing)
if backing in ('zfs',):
if zfsroot:
cmd += ' --zfsroot {0}'.format(zfsroot)
if backing in ('lvm',):
if lvname:
cmd += ' --lvname {0}'.format(lvname)
if vgname:
cmd += ' --vgname {0}'.format(vgname)
if thinpool:
cmd += ' --thinpool {0}'.format(thinpool)
if backing not in ('dir', 'overlayfs'):
if fstype:
cmd += ' --fstype {0}'.format(fstype)
if size:
cmd += ' --fssize {0}'.format(size)
if options:
if template == 'download':
missing_deps = [x for x in download_template_deps
if x not in options]
if missing_deps:
raise SaltInvocationError(
'Missing params in \'options\' dict: {0}'
.format(', '.join(missing_deps))
)
cmd += ' --'
for key, val in six.iteritems(options):
cmd += ' --{0} {1}'.format(key, val)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
# please do not merge extra conflicting stuff
# inside those two line (ret =, return)
return _after_ignition_network_profile(cmd,
ret,
name,
network_profile,
path,
nic_opts)
def clone(name,
orig,
profile=None,
network_profile=None,
nic_opts=None,
**kwargs):
'''
Create a new container as a clone of another container
name
Name of the container
orig
Name of the original container to be cloned
profile
Profile to use in container cloning (see
:mod:`lxc.get_container_profile
<salt.modules.lxc.get_container_profile>`). Values in a profile will be
overridden by the **Container Cloning Arguments** listed below.
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
**Container Cloning Arguments**
snapshot
Use Copy On Write snapshots (LVM)
size : 1G
Size of the volume to create. Only applicable if ``backing=lvm``.
backing
The type of storage to use. Set to ``lvm`` to use an LVM group.
Defaults to filesystem within /var/lib/lxc.
network_profile
Network profile to use for container
.. versionadded:: 2015.8.0
nic_opts
give extra opts overriding network profile values
.. versionadded:: 2015.8.0
CLI Examples:
.. code-block:: bash
salt '*' lxc.clone myclone orig=orig_container
salt '*' lxc.clone myclone orig=orig_container snapshot=True
'''
profile = get_container_profile(copy.deepcopy(profile))
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, None)
profile_match = profile.pop(key, default)
# let kwarg overrides be the preferred choice
if kw_overrides_match is None:
return profile_match
return kw_overrides_match
path = select('path')
if exists(name, path=path):
raise CommandExecutionError(
'Container \'{0}\' already exists'.format(name)
)
_ensure_exists(orig, path=path)
if state(orig, path=path) != 'stopped':
raise CommandExecutionError(
'Container \'{0}\' must be stopped to be cloned'.format(orig)
)
backing = select('backing')
snapshot = select('snapshot')
if backing in ('dir',):
snapshot = False
if not snapshot:
snapshot = ''
else:
snapshot = '-s'
size = select('size', '1G')
if backing in ('dir', 'overlayfs', 'btrfs'):
size = None
# LXC commands and options changed in 2.0 - CF issue #34086 for details
if _LooseVersion(version()) >= _LooseVersion('2.0'):
# https://linuxcontainers.org/lxc/manpages//man1/lxc-copy.1.html
cmd = 'lxc-copy'
cmd += ' {0} -n {1} -N {2}'.format(snapshot, orig, name)
else:
# https://linuxcontainers.org/lxc/manpages//man1/lxc-clone.1.html
cmd = 'lxc-clone'
cmd += ' {0} -o {1} -n {2}'.format(snapshot, orig, name)
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
if not os.path.exists(path):
os.makedirs(path)
if backing:
backing = backing.lower()
cmd += ' -B {0}'.format(backing)
if backing not in ('dir', 'overlayfs'):
if size:
cmd += ' -L {0}'.format(size)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
# please do not merge extra conflicting stuff
# inside those two line (ret =, return)
return _after_ignition_network_profile(cmd,
ret,
name,
network_profile,
path,
nic_opts)
def ls_(active=None, cache=True, path=None):
'''
Return a list of the containers available on the minion
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
active
If ``True``, return only active (i.e. running) containers
.. versionadded:: 2015.5.0
CLI Example:
.. code-block:: bash
salt '*' lxc.ls
salt '*' lxc.ls active=True
'''
contextvar = 'lxc.ls{0}'.format(path)
if active:
contextvar += '.active'
if cache and (contextvar in __context__):
return __context__[contextvar]
else:
ret = []
cmd = 'lxc-ls'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
if active:
cmd += ' --active'
output = __salt__['cmd.run_stdout'](cmd, python_shell=False)
for line in output.splitlines():
ret.extend(line.split())
__context__[contextvar] = ret
return ret
def list_(extra=False, limit=None, path=None):
'''
List containers classified by state
extra
Also get per-container specific info. This will change the return data.
Instead of returning a list of containers, a dictionary of containers
and each container's output from :mod:`lxc.info
<salt.modules.lxc.info>`.
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
limit
Return output matching a specific state (**frozen**, **running**, or
**stopped**).
.. versionadded:: 2015.5.0
CLI Examples:
.. code-block:: bash
salt '*' lxc.list
salt '*' lxc.list extra=True
salt '*' lxc.list limit=running
'''
ctnrs = ls_(path=path)
if extra:
stopped = {}
frozen = {}
running = {}
else:
stopped = []
frozen = []
running = []
ret = {'running': running,
'stopped': stopped,
'frozen': frozen}
for container in ctnrs:
cmd = 'lxc-info'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0}'.format(container)
c_info = __salt__['cmd.run'](
cmd,
python_shell=False,
output_loglevel='debug'
)
c_state = None
for line in c_info.splitlines():
stat = line.split(':')
if stat[0] in ('State', 'state'):
c_state = stat[1].strip()
break
if not c_state or (limit is not None and c_state.lower() != limit):
continue
if extra:
infos = info(container, path=path)
method = 'update'
value = {container: infos}
else:
method = 'append'
value = container
if c_state == 'STOPPED':
getattr(stopped, method)(value)
continue
if c_state == 'FROZEN':
getattr(frozen, method)(value)
continue
if c_state == 'RUNNING':
getattr(running, method)(value)
continue
if limit is not None:
return ret.get(limit, {} if extra else [])
return ret
def _change_state(cmd,
name,
expected,
stdin=_marker,
stdout=_marker,
stderr=_marker,
with_communicate=_marker,
use_vt=_marker,
path=None):
pre = state(name, path=path)
if pre == expected:
return {'result': True,
'state': {'old': expected, 'new': expected},
'comment': 'Container \'{0}\' already {1}'
.format(name, expected)}
if cmd == 'lxc-destroy':
# Kill the container first
scmd = 'lxc-stop'
if path:
scmd += ' -P {0}'.format(pipes.quote(path))
scmd += ' -k -n {0}'.format(name)
__salt__['cmd.run'](scmd,
python_shell=False)
if path and ' -P ' not in cmd:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0}'.format(name)
# certain lxc commands need to be taken with care (lxc-start)
# as te command itself mess with double forks; we must not
# communicate with it, but just wait for the exit status
pkwargs = {'python_shell': False,
'redirect_stderr': True,
'with_communicate': with_communicate,
'use_vt': use_vt,
'stdin': stdin,
'stdout': stdout}
for i in [a for a in pkwargs]:
val = pkwargs[i]
if val is _marker:
pkwargs.pop(i, None)
_cmdout = __salt__['cmd.run_all'](cmd, **pkwargs)
if _cmdout['retcode'] != 0:
raise CommandExecutionError(
'Error changing state for container \'{0}\' using command '
'\'{1}\': {2}'.format(name, cmd, _cmdout['stdout'])
)
if expected is not None:
# some commands do not wait, so we will
rcmd = 'lxc-wait'
if path:
rcmd += ' -P {0}'.format(pipes.quote(path))
rcmd += ' -n {0} -s {1}'.format(name, expected.upper())
__salt__['cmd.run'](rcmd, python_shell=False, timeout=30)
_clear_context()
post = state(name, path=path)
ret = {'result': post == expected,
'state': {'old': pre, 'new': post}}
return ret
def _ensure_exists(name, path=None):
'''
Raise an exception if the container does not exist
'''
if not exists(name, path=path):
raise CommandExecutionError(
'Container \'{0}\' does not exist'.format(name)
)
def _ensure_running(name, no_start=False, path=None):
'''
If the container is not currently running, start it. This function returns
the state that the container was in before changing
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
'''
_ensure_exists(name, path=path)
pre = state(name, path=path)
if pre == 'running':
# This will be a no-op but running the function will give us a pretty
# return dict.
return start(name, path=path)
elif pre == 'stopped':
if no_start:
raise CommandExecutionError(
'Container \'{0}\' is not running'.format(name)
)
return start(name, path=path)
elif pre == 'frozen':
if no_start:
raise CommandExecutionError(
'Container \'{0}\' is not running'.format(name)
)
return unfreeze(name, path=path)
def restart(name, path=None, lxc_config=None, force=False):
'''
.. versionadded:: 2015.5.0
Restart the named container. If the container was not running, the
container will merely be started.
name
The name of the container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
lxc_config
path to a lxc config file
config file will be guessed from container name otherwise
.. versionadded:: 2015.8.0
force : False
If ``True``, the container will be force-stopped instead of gracefully
shut down
CLI Example:
.. code-block:: bash
salt myminion lxc.restart name
'''
_ensure_exists(name, path=path)
orig_state = state(name, path=path)
if orig_state != 'stopped':
stop(name, kill=force, path=path)
ret = start(name, path=path, lxc_config=lxc_config)
ret['state']['old'] = orig_state
if orig_state != 'stopped':
ret['restarted'] = True
return ret
def stop(name, kill=False, path=None, use_vt=None):
'''
Stop the named container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
kill: False
Do not wait for the container to stop, kill all tasks in the container.
Older LXC versions will stop containers like this irrespective of this
argument.
.. versionchanged:: 2015.5.0
Default value changed to ``False``
use_vt
run the command through VT
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.stop name
'''
_ensure_exists(name, path=path)
orig_state = state(name, path=path)
if orig_state == 'frozen' and not kill:
# Gracefully stopping a frozen container is slower than unfreezing and
# then stopping it (at least in my testing), so if we're not
# force-stopping the container, unfreeze it first.
unfreeze(name, path=path)
cmd = 'lxc-stop'
if kill:
cmd += ' -k'
ret = _change_state(cmd, name, 'stopped', use_vt=use_vt, path=path)
ret['state']['old'] = orig_state
return ret
def freeze(name, **kwargs):
'''
Freeze the named container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
start : False
If ``True`` and the container is stopped, the container will be started
before attempting to freeze.
.. versionadded:: 2015.5.0
use_vt
run the command through VT
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.freeze name
'''
use_vt = kwargs.get('use_vt', None)
path = kwargs.get('path', None)
_ensure_exists(name, path=path)
orig_state = state(name, path=path)
start_ = kwargs.get('start', False)
if orig_state == 'stopped':
if not start_:
raise CommandExecutionError(
'Container \'{0}\' is stopped'.format(name)
)
start(name, path=path)
cmd = 'lxc-freeze'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
ret = _change_state(cmd, name, 'frozen', use_vt=use_vt, path=path)
if orig_state == 'stopped' and start_:
ret['state']['old'] = orig_state
ret['started'] = True
ret['state']['new'] = state(name, path=path)
return ret
def unfreeze(name, path=None, use_vt=None):
'''
Unfreeze the named container.
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
use_vt
run the command through VT
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.unfreeze name
'''
_ensure_exists(name, path=path)
if state(name, path=path) == 'stopped':
raise CommandExecutionError(
'Container \'{0}\' is stopped'.format(name)
)
cmd = 'lxc-unfreeze'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
return _change_state(cmd, name, 'running', path=path, use_vt=use_vt)
def destroy(name, stop=False, path=None):
'''
Destroy the named container.
.. warning::
Destroys all data associated with the container.
path
path to the container parent directory (default: /var/lib/lxc)
.. versionadded:: 2015.8.0
stop : False
If ``True``, the container will be destroyed even if it is
running/frozen.
.. versionchanged:: 2015.5.0
Default value changed to ``False``. This more closely matches the
behavior of ``lxc-destroy(1)``, and also makes it less likely that
an accidental command will destroy a running container that was
being used for important things.
CLI Examples:
.. code-block:: bash
salt '*' lxc.destroy foo
salt '*' lxc.destroy foo stop=True
'''
_ensure_exists(name, path=path)
if not stop and state(name, path=path) != 'stopped':
raise CommandExecutionError(
'Container \'{0}\' is not stopped'.format(name)
)
return _change_state('lxc-destroy', name, None, path=path)
# Compatibility between LXC and nspawn
remove = salt.utils.functools.alias_function(destroy, 'remove')
def exists(name, path=None):
'''
Returns whether the named container exists.
path
path to the container parent directory (default: /var/lib/lxc)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.exists name
'''
_exists = name in ls_(path=path)
# container may be just created but we did cached earlier the
# lxc-ls results
if not _exists:
_exists = name in ls_(cache=False, path=path)
return _exists
def state(name, path=None):
'''
Returns the state of a container.
path
path to the container parent directory (default: /var/lib/lxc)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.state name
'''
# Don't use _ensure_exists() here, it will mess with _change_state()
cachekey = 'lxc.state.{0}{1}'.format(name, path)
try:
return __context__[cachekey]
except KeyError:
if not exists(name, path=path):
__context__[cachekey] = None
else:
cmd = 'lxc-info'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0}'.format(name)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
if ret['retcode'] != 0:
_clear_context()
raise CommandExecutionError(
'Unable to get state of container \'{0}\''.format(name)
)
c_infos = ret['stdout'].splitlines()
c_state = None
for c_info in c_infos:
stat = c_info.split(':')
if stat[0].lower() == 'state':
c_state = stat[1].strip().lower()
break
__context__[cachekey] = c_state
return __context__[cachekey]
def get_parameter(name, parameter, path=None):
'''
Returns the value of a cgroup parameter for a container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.get_parameter container_name memory.limit_in_bytes
'''
_ensure_exists(name, path=path)
cmd = 'lxc-cgroup'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0} {1}'.format(name, parameter)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
if ret['retcode'] != 0:
raise CommandExecutionError(
'Unable to retrieve value for \'{0}\''.format(parameter)
)
return ret['stdout'].strip()
def set_parameter(name, parameter, value, path=None):
'''
Set the value of a cgroup parameter for a container.
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.set_parameter name parameter value
'''
if not exists(name, path=path):
return None
cmd = 'lxc-cgroup'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0} {1} {2}'.format(name, parameter, value)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
if ret['retcode'] != 0:
return False
else:
return True
def info(name, path=None):
'''
Returns information about a container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.info name
'''
cachekey = 'lxc.info.{0}{1}'.format(name, path)
try:
return __context__[cachekey]
except KeyError:
_ensure_exists(name, path=path)
cpath = get_root_path(path)
try:
conf_file = os.path.join(cpath, name, 'config')
except AttributeError:
conf_file = os.path.join(cpath, six.text_type(name), 'config')
if not os.path.isfile(conf_file):
raise CommandExecutionError(
'LXC config file {0} does not exist'.format(conf_file)
)
ret = {}
config = []
with salt.utils.files.fopen(conf_file) as fp_:
for line in fp_:
line = salt.utils.stringutils.to_unicode(line)
comps = [x.strip() for x in
line.split('#', 1)[0].strip().split('=', 1)]
if len(comps) == 2:
config.append(tuple(comps))
ifaces = []
current = None
for key, val in config:
if key == 'lxc.network.type':
current = {'type': val}
ifaces.append(current)
elif not current:
continue
elif key.startswith('lxc.network.'):
current[key.replace('lxc.network.', '', 1)] = val
if ifaces:
ret['nics'] = ifaces
ret['rootfs'] = next(
(x[1] for x in config if x[0] == 'lxc.rootfs'),
None
)
ret['state'] = state(name, path=path)
ret['ips'] = []
ret['public_ips'] = []
ret['private_ips'] = []
ret['public_ipv4_ips'] = []
ret['public_ipv6_ips'] = []
ret['private_ipv4_ips'] = []
ret['private_ipv6_ips'] = []
ret['ipv4_ips'] = []
ret['ipv6_ips'] = []
ret['size'] = None
ret['config'] = conf_file
if ret['state'] == 'running':
try:
limit = int(get_parameter(name, 'memory.limit_in_bytes'))
except (CommandExecutionError, TypeError, ValueError):
limit = 0
try:
usage = int(get_parameter(name, 'memory.usage_in_bytes'))
except (CommandExecutionError, TypeError, ValueError):
usage = 0
free = limit - usage
ret['memory_limit'] = limit
ret['memory_free'] = free
size = run_stdout(name, 'df /', path=path, python_shell=False)
# The size is the 2nd column of the last line
ret['size'] = size.splitlines()[-1].split()[1]
# First try iproute2
ip_cmd = run_all(
name, 'ip link show', path=path, python_shell=False)
if ip_cmd['retcode'] == 0:
ip_data = ip_cmd['stdout']
ip_cmd = run_all(
name, 'ip addr show', path=path, python_shell=False)
ip_data += '\n' + ip_cmd['stdout']
ip_data = salt.utils.network._interfaces_ip(ip_data)
else:
# That didn't work, try ifconfig
ip_cmd = run_all(
name, 'ifconfig', path=path, python_shell=False)
if ip_cmd['retcode'] == 0:
ip_data = \
salt.utils.network._interfaces_ifconfig(
ip_cmd['stdout'])
else:
# Neither was successful, give up
log.warning(
'Unable to run ip or ifconfig in container \'%s\'', name
)
ip_data = {}
ret['ipv4_ips'] = salt.utils.network.ip_addrs(
include_loopback=True,
interface_data=ip_data
)
ret['ipv6_ips'] = salt.utils.network.ip_addrs6(
include_loopback=True,
interface_data=ip_data
)
ret['ips'] = ret['ipv4_ips'] + ret['ipv6_ips']
for address in ret['ipv4_ips']:
if address == '127.0.0.1':
ret['private_ips'].append(address)
ret['private_ipv4_ips'].append(address)
elif salt.utils.cloud.is_public_ip(address):
ret['public_ips'].append(address)
ret['public_ipv4_ips'].append(address)
else:
ret['private_ips'].append(address)
ret['private_ipv4_ips'].append(address)
for address in ret['ipv6_ips']:
if address == '::1' or address.startswith('fe80'):
ret['private_ips'].append(address)
ret['private_ipv6_ips'].append(address)
else:
ret['public_ips'].append(address)
ret['public_ipv6_ips'].append(address)
for key in [x for x in ret if x == 'ips' or x.endswith('ips')]:
ret[key].sort(key=_ip_sort)
__context__[cachekey] = ret
return __context__[cachekey]
def set_password(name, users, password, encrypted=True, path=None):
'''
.. versionchanged:: 2015.5.0
Function renamed from ``set_pass`` to ``set_password``. Additionally,
this function now supports (and defaults to using) a password hash
instead of a plaintext password.
Set the password of one or more system users inside containers
users
Comma-separated list (or python list) of users to change password
password
Password to set for the specified user(s)
encrypted : True
If true, ``password`` must be a password hash. Set to ``False`` to set
a plaintext password (not recommended).
.. versionadded:: 2015.5.0
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.set_pass container-name root '$6$uJ2uAyLU$KoI67t8As/0fXtJOPcHKGXmUpcoYUcVR2K6x93walnShTCQvjRwq25yIkiCBOqgbfdKQSFnAo28/ek6716vEV1'
salt '*' lxc.set_pass container-name root foo encrypted=False
'''
def _bad_user_input():
raise SaltInvocationError('Invalid input for \'users\' parameter')
if not isinstance(users, list):
try:
users = users.split(',')
except AttributeError:
_bad_user_input()
if not users:
_bad_user_input()
failed_users = []
for user in users:
result = retcode(name,
'chpasswd{0}'.format(' -e' if encrypted else ''),
stdin=':'.join((user, password)),
python_shell=False,
path=path,
chroot_fallback=True,
output_loglevel='quiet')
if result != 0:
failed_users.append(user)
if failed_users:
raise CommandExecutionError(
'Password change failed for the following user(s): {0}'
.format(', '.join(failed_users))
)
return True
set_pass = salt.utils.functools.alias_function(set_password, 'set_pass')
def update_lxc_conf(name, lxc_conf, lxc_conf_unset, path=None):
'''
Edit LXC configuration options
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.update_lxc_conf ubuntu \\
lxc_conf="[{'network.ipv4.ip':'10.0.3.5'}]" \\
lxc_conf_unset="['lxc.utsname']"
'''
_ensure_exists(name, path=path)
cpath = get_root_path(path)
lxc_conf_p = os.path.join(cpath, name, 'config')
if not os.path.exists(lxc_conf_p):
raise SaltInvocationError(
'Configuration file {0} does not exist'.format(lxc_conf_p)
)
changes = {'edited': [], 'added': [], 'removed': []}
ret = {'changes': changes, 'result': True, 'comment': ''}
# do not use salt.utils.files.fopen !
with salt.utils.files.fopen(lxc_conf_p, 'r') as fic:
filtered_lxc_conf = []
for row in lxc_conf:
if not row:
continue
for conf in row:
filtered_lxc_conf.append((conf.strip(),
row[conf].strip()))
ret['comment'] = 'lxc.conf is up to date'
lines = []
orig_config = salt.utils.stringutils.to_unicode(fic.read())
for line in orig_config.splitlines():
if line.startswith('#') or not line.strip():
lines.append([line, ''])
else:
line = line.split('=')
index = line.pop(0)
val = (index.strip(), '='.join(line).strip())
if val not in lines:
lines.append(val)
for key, item in filtered_lxc_conf:
matched = False
for idx, line in enumerate(lines[:]):
if line[0] == key:
matched = True
lines[idx] = (key, item)
if '='.join(line[1:]).strip() != item.strip():
changes['edited'].append(
({line[0]: line[1:]}, {key: item}))
break
if not matched:
if (key, item) not in lines:
lines.append((key, item))
changes['added'].append({key: item})
dest_lxc_conf = []
# filter unset
if lxc_conf_unset:
for line in lines:
for opt in lxc_conf_unset:
if (
not line[0].startswith(opt) and
line not in dest_lxc_conf
):
dest_lxc_conf.append(line)
else:
changes['removed'].append(opt)
else:
dest_lxc_conf = lines
conf = ''
for key, val in dest_lxc_conf:
if not val:
conf += '{0}\n'.format(key)
else:
conf += '{0} = {1}\n'.format(key.strip(), val.strip())
conf_changed = conf != orig_config
chrono = datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S')
if conf_changed:
# DO NOT USE salt.utils.files.fopen here, i got (kiorky)
# problems with lxc configs which were wiped !
with salt.utils.files.fopen('{0}.{1}'.format(lxc_conf_p, chrono), 'w') as wfic:
wfic.write(salt.utils.stringutils.to_str(conf))
with salt.utils.files.fopen(lxc_conf_p, 'w') as wfic:
wfic.write(salt.utils.stringutils.to_str(conf))
ret['comment'] = 'Updated'
ret['result'] = True
if not any(changes[x] for x in changes):
# Ensure an empty changes dict if nothing was modified
ret['changes'] = {}
return ret
def set_dns(name, dnsservers=None, searchdomains=None, path=None):
'''
.. versionchanged:: 2015.5.0
The ``dnsservers`` and ``searchdomains`` parameters can now be passed
as a comma-separated list.
Update /etc/resolv.confo
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.set_dns ubuntu "['8.8.8.8', '4.4.4.4']"
'''
if dnsservers is None:
dnsservers = ['8.8.8.8', '4.4.4.4']
elif not isinstance(dnsservers, list):
try:
dnsservers = dnsservers.split(',')
except AttributeError:
raise SaltInvocationError(
'Invalid input for \'dnsservers\' parameter'
)
if searchdomains is None:
searchdomains = []
elif not isinstance(searchdomains, list):
try:
searchdomains = searchdomains.split(',')
except AttributeError:
raise SaltInvocationError(
'Invalid input for \'searchdomains\' parameter'
)
dns = ['nameserver {0}'.format(x) for x in dnsservers]
dns.extend(['search {0}'.format(x) for x in searchdomains])
dns = '\n'.join(dns) + '\n'
# we may be using resolvconf in the container
# We need to handle that case with care:
# - we create the resolv.conf runtime directory (the
# linked directory) as anyway it will be shadowed when the real
# runned tmpfs mountpoint will be mounted.
# ( /etc/resolv.conf -> ../run/resolvconf/resolv.conf)
# Indeed, it can save us in any other case (running, eg, in a
# bare chroot when repairing or preparing the container for
# operation.
# - We also teach resolvconf to use the aforementioned dns.
# - We finally also set /etc/resolv.conf in all cases
rstr = __salt__['test.random_hash']()
# no tmp here, apparmor won't let us execute !
script = '/sbin/{0}_dns.sh'.format(rstr)
DNS_SCRIPT = "\n".join([
# 'set -x',
'#!/usr/bin/env bash',
'if [ -h /etc/resolv.conf ];then',
' if [ "x$(readlink /etc/resolv.conf)"'
' = "x../run/resolvconf/resolv.conf" ];then',
' if [ ! -d /run/resolvconf/ ];then',
' mkdir -p /run/resolvconf',
' fi',
' cat > /etc/resolvconf/resolv.conf.d/head <<EOF',
dns,
'EOF',
'',
' fi',
'fi',
'cat > /etc/resolv.conf <<EOF',
dns,
'EOF',
''])
result = run_all(
name, 'tee {0}'.format(script), path=path,
stdin=DNS_SCRIPT, python_shell=True)
if result['retcode'] == 0:
result = run_all(
name, 'sh -c "chmod +x {0};{0}"'.format(script),
path=path, python_shell=True)
# blindly delete the setter file
run_all(name,
'sh -c \'if [ -f "{0}" ];then rm -f "{0}";fi\''.format(script),
path=path, python_shell=True)
if result['retcode'] != 0:
error = ('Unable to write to /etc/resolv.conf in container \'{0}\''
.format(name))
if result['stderr']:
error += ': {0}'.format(result['stderr'])
raise CommandExecutionError(error)
return True
def running_systemd(name, cache=True, path=None):
'''
Determine if systemD is running
path
path to the container parent
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.running_systemd ubuntu
'''
k = 'lxc.systemd.test.{0}{1}'.format(name, path)
ret = __context__.get(k, None)
if ret is None or not cache:
rstr = __salt__['test.random_hash']()
# no tmp here, apparmor won't let us execute !
script = '/sbin/{0}_testsystemd.sh'.format(rstr)
# ubuntu already had since trusty some bits of systemd but was
# still using upstart ...
# we need to be a bit more careful that just testing that systemd
# is present
_script = textwrap.dedent(
'''\
#!/usr/bin/env bash
set -x
if ! command -v systemctl 1>/dev/null 2>/dev/null;then exit 2;fi
for i in \\
/run/systemd/journal/dev-log\\
/run/systemd/journal/flushed\\
/run/systemd/journal/kernel-seqnum\\
/run/systemd/journal/socket\\
/run/systemd/journal/stdout\\
/var/run/systemd/journal/dev-log\\
/var/run/systemd/journal/flushed\\
/var/run/systemd/journal/kernel-seqnum\\
/var/run/systemd/journal/socket\\
/var/run/systemd/journal/stdout\\
;do\\
if test -e ${i};then exit 0;fi
done
if test -d /var/systemd/system;then exit 0;fi
exit 2
''')
result = run_all(
name, 'tee {0}'.format(script), path=path,
stdin=_script, python_shell=True)
if result['retcode'] == 0:
result = run_all(name,
'sh -c "chmod +x {0};{0}"'''.format(script),
path=path,
python_shell=True)
else:
raise CommandExecutionError(
'lxc {0} failed to copy initd tester'.format(name))
run_all(name,
'sh -c \'if [ -f "{0}" ];then rm -f "{0}";fi\''
''.format(script),
path=path,
ignore_retcode=True,
python_shell=True)
if result['retcode'] != 0:
error = ('Unable to determine if the container \'{0}\''
' was running systemd, assmuming it is not.'
''.format(name))
if result['stderr']:
error += ': {0}'.format(result['stderr'])
# only cache result if we got a known exit code
if result['retcode'] in (0, 2):
__context__[k] = ret = not result['retcode']
return ret
def systemd_running_state(name, path=None):
'''
Get the operational state of a systemd based container
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.systemd_running_state ubuntu
'''
try:
ret = run_all(name,
'systemctl is-system-running',
path=path,
ignore_retcode=True)['stdout']
except CommandExecutionError:
ret = ''
return ret
def test_sd_started_state(name, path=None):
'''
Test if a systemd container is fully started
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.test_sd_started_state ubuntu
'''
qstate = systemd_running_state(name, path=path)
if qstate in ('initializing', 'starting'):
return False
elif qstate == '':
return None
else:
return True
def test_bare_started_state(name, path=None):
'''
Test if a non systemd container is fully started
For now, it consists only to test if the container is attachable
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.test_bare_started_state ubuntu
'''
try:
ret = run_all(
name, 'ls', path=path, ignore_retcode=True
)['retcode'] == 0
except (CommandExecutionError,):
ret = None
return ret
def wait_started(name, path=None, timeout=300):
'''
Check that the system has fully inited
This is actually very important for systemD based containers
see https://github.com/saltstack/salt/issues/23847
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.wait_started ubuntu
'''
if not exists(name, path=path):
raise CommandExecutionError(
'Container {0} does does exists'.format(name))
if not state(name, path=path) == 'running':
raise CommandExecutionError(
'Container {0} is not running'.format(name))
ret = False
if running_systemd(name, path=path):
test_started = test_sd_started_state
logger = log.error
else:
test_started = test_bare_started_state
logger = log.debug
now = time.time()
expire = now + timeout
now = time.time()
started = test_started(name, path=path)
while time.time() < expire and not started:
time.sleep(0.3)
started = test_started(name, path=path)
if started is None:
logger(
'Assuming %s is started, although we failed to detect that'
' is fully started correctly', name)
ret = True
else:
ret = started
return ret
def _needs_install(name, path=None):
ret = 0
has_minion = retcode(name,
'which salt-minion',
path=path,
ignore_retcode=True)
# we assume that installing is when no minion is running
# but testing the executable presence is not enougth for custom
# installs where the bootstrap can do much more than installing
# the bare salt binaries.
if has_minion:
processes = run_stdout(name, "ps aux", path=path)
if 'salt-minion' not in processes:
ret = 1
else:
retcode(name, 'salt-call --local service.stop salt-minion')
else:
ret = 1
return ret
def bootstrap(name,
config=None,
approve_key=True,
install=True,
pub_key=None,
priv_key=None,
bootstrap_url=None,
force_install=False,
unconditional_install=False,
path=None,
bootstrap_delay=None,
bootstrap_args=None,
bootstrap_shell=None):
'''
Install and configure salt in a container.
config
Minion configuration options. By default, the ``master`` option is set
to the target host's master.
approve_key
Request a pre-approval of the generated minion key. Requires
that the salt-master be configured to either auto-accept all keys or
expect a signing request from the target host. Default: ``True``
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
pub_key
Explicit public key to pressed the minion with (optional).
This can be either a filepath or a string representing the key
priv_key
Explicit private key to pressed the minion with (optional).
This can be either a filepath or a string representing the key
bootstrap_delay
Delay in seconds between end of container creation and bootstrapping.
Useful when waiting for container to obtain a DHCP lease.
.. versionadded:: 2015.5.0
bootstrap_url
url, content or filepath to the salt bootstrap script
bootstrap_args
salt bootstrap script arguments
bootstrap_shell
shell to execute the script into
install
Whether to attempt a full installation of salt-minion if needed.
force_install
Force installation even if salt-minion is detected,
this is the way to run vendor bootstrap scripts even
if a salt minion is already present in the container
unconditional_install
Run the script even if the container seems seeded
CLI Examples:
.. code-block:: bash
salt 'minion' lxc.bootstrap container_name [config=config_data] \\
[approve_key=(True|False)] [install=(True|False)]
'''
wait_started(name, path=path)
if bootstrap_delay is not None:
try:
log.info('LXC %s: bootstrap_delay: %s', name, bootstrap_delay)
time.sleep(bootstrap_delay)
except TypeError:
# Bad input, but assume since a value was passed that
# a delay was desired, and sleep for 5 seconds
time.sleep(5)
c_info = info(name, path=path)
if not c_info:
return None
# default set here as we cannot set them
# in def as it can come from a chain of procedures.
if bootstrap_args:
# custom bootstrap args can be totally customized, and user could
# have inserted the placeholder for the config directory.
# For example, some salt bootstrap script do not use at all -c
if '{0}' not in bootstrap_args:
bootstrap_args += ' -c {0}'
else:
bootstrap_args = '-c {0}'
if not bootstrap_shell:
bootstrap_shell = 'sh'
orig_state = _ensure_running(name, path=path)
if not orig_state:
return orig_state
if not force_install:
needs_install = _needs_install(name, path=path)
else:
needs_install = True
seeded = retcode(name,
'test -e \'{0}\''.format(SEED_MARKER),
path=path,
chroot_fallback=True,
ignore_retcode=True) == 0
tmp = tempfile.mkdtemp()
if seeded and not unconditional_install:
ret = True
else:
ret = False
cfg_files = __salt__['seed.mkconfig'](
config, tmp=tmp, id_=name, approve_key=approve_key,
pub_key=pub_key, priv_key=priv_key)
if needs_install or force_install or unconditional_install:
if install:
rstr = __salt__['test.random_hash']()
configdir = '/var/tmp/.c_{0}'.format(rstr)
cmd = 'install -m 0700 -d {0}'.format(configdir)
if run_all(
name, cmd, path=path, python_shell=False
)['retcode'] != 0:
log.error('tmpdir %s creation failed %s', configdir, cmd)
return False
bs_ = __salt__['config.gather_bootstrap_script'](
bootstrap=bootstrap_url)
script = '/sbin/{0}_bootstrap.sh'.format(rstr)
copy_to(name, bs_, script, path=path)
result = run_all(name,
'sh -c "chmod +x {0}"'.format(script),
path=path,
python_shell=True)
copy_to(name, cfg_files['config'],
os.path.join(configdir, 'minion'),
path=path)
copy_to(name, cfg_files['privkey'],
os.path.join(configdir, 'minion.pem'),
path=path)
copy_to(name, cfg_files['pubkey'],
os.path.join(configdir, 'minion.pub'),
path=path)
bootstrap_args = bootstrap_args.format(configdir)
cmd = ('{0} {2} {1}'
.format(bootstrap_shell,
bootstrap_args.replace("'", "''"),
script))
# log ASAP the forged bootstrap command which can be wrapped
# out of the output in case of unexpected problem
log.info('Running %s in LXC container \'%s\'', cmd, name)
ret = retcode(name, cmd, output_loglevel='info',
path=path, use_vt=True) == 0
run_all(name,
'sh -c \'if [ -f "{0}" ];then rm -f "{0}";fi\''
''.format(script),
path=path,
ignore_retcode=True,
python_shell=True)
else:
ret = False
else:
minion_config = salt.config.minion_config(cfg_files['config'])
pki_dir = minion_config['pki_dir']
copy_to(name,
cfg_files['config'],
'/etc/salt/minion',
path=path)
copy_to(name,
cfg_files['privkey'],
os.path.join(pki_dir, 'minion.pem'),
path=path)
copy_to(name,
cfg_files['pubkey'],
os.path.join(pki_dir, 'minion.pub'),
path=path)
run(name,
'salt-call --local service.enable salt-minion',
path=path,
python_shell=False)
ret = True
shutil.rmtree(tmp)
if orig_state == 'stopped':
stop(name, path=path)
elif orig_state == 'frozen':
freeze(name, path=path)
# mark seeded upon successful install
if ret:
run(name,
'touch \'{0}\''.format(SEED_MARKER),
path=path,
python_shell=False)
return ret
def attachable(name, path=None):
'''
Return True if the named container can be attached to via the lxc-attach
command
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt 'minion' lxc.attachable ubuntu
'''
cachekey = 'lxc.attachable{0}{1}'.format(name, path)
try:
return __context__[cachekey]
except KeyError:
_ensure_exists(name, path=path)
# Can't use run() here because it uses attachable() and would
# endlessly recurse, resulting in a traceback
log.debug('Checking if LXC container %s is attachable', name)
cmd = 'lxc-attach'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' --clear-env -n {0} -- /usr/bin/env'.format(name)
result = __salt__['cmd.retcode'](cmd,
python_shell=False,
output_loglevel='quiet',
ignore_retcode=True) == 0
__context__[cachekey] = result
return __context__[cachekey]
def _run(name,
cmd,
output=None,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=None,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
Common logic for lxc.run functions
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
'''
orig_state = state(name, path=path)
try:
if attachable(name, path=path):
ret = __salt__['container_resource.run'](
name,
cmd,
path=path,
container_type=__virtualname__,
exec_driver=EXEC_DRIVER,
output=output,
no_start=no_start,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
ignore_retcode=ignore_retcode,
use_vt=use_vt,
keep_env=keep_env)
else:
if not chroot_fallback:
raise CommandExecutionError(
'{0} is not attachable.'.format(name))
rootfs = info(name, path=path).get('rootfs')
# Set context var to make cmd.run_chroot run cmd.run instead of
# cmd.run_all.
__context__['cmd.run_chroot.func'] = __salt__['cmd.run']
ret = __salt__['cmd.run_chroot'](rootfs,
cmd,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
ignore_retcode=ignore_retcode)
except Exception:
raise
finally:
# Make sure we honor preserve_state, even if there was an exception
new_state = state(name, path=path)
if preserve_state:
if orig_state == 'stopped' and new_state != 'stopped':
stop(name, path=path)
elif orig_state == 'frozen' and new_state != 'frozen':
freeze(name, start=True, path=path)
if output in (None, 'all'):
return ret
else:
return ret[output]
def run(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.8.0
Run :mod:`cmd.run <salt.modules.cmdmod.run>` within a container
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed in stderr if the command being run
does not exist. If no output is returned using this function, try using
:mod:`lxc.run_stderr <salt.modules.lxc.run_stderr>` or
:mod:`lxc.run_all <salt.modules.lxc.run_all>`.
name
Name of the container in which to run the command
cmd
Command to run
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console. Assumes
``output=all``.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
CLI Example:
.. code-block:: bash
salt myminion lxc.run mycontainer 'ifconfig -a'
'''
return _run(name,
cmd,
path=path,
output=None,
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def run_stdout(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.5.0
Run :mod:`cmd.run_stdout <salt.modules.cmdmod.run_stdout>` within a container
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed in stderr if the command being run
does not exist. If no output is returned using this function, try using
:mod:`lxc.run_stderr <salt.modules.lxc.run_stderr>` or
:mod:`lxc.run_all <salt.modules.lxc.run_all>`.
name
Name of the container in which to run the command
cmd
Command to run
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console
``output=all``.
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
CLI Example:
.. code-block:: bash
salt myminion lxc.run_stdout mycontainer 'ifconfig -a'
'''
return _run(name,
cmd,
path=path,
output='stdout',
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def run_stderr(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.5.0
Run :mod:`cmd.run_stderr <salt.modules.cmdmod.run_stderr>` within a container
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed if the command being run does not
exist.
name
Name of the container in which to run the command
cmd
Command to run
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console
``output=all``.
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
CLI Example:
.. code-block:: bash
salt myminion lxc.run_stderr mycontainer 'ip addr show'
'''
return _run(name,
cmd,
path=path,
output='stderr',
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def retcode(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.5.0
Run :mod:`cmd.retcode <salt.modules.cmdmod.retcode>` within a container
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed in stderr if the command being run
does not exist. If the retcode is nonzero and not what was expected,
try using :mod:`lxc.run_stderr <salt.modules.lxc.run_stderr>`
or :mod:`lxc.run_all <salt.modules.lxc.run_all>`.
name
Name of the container in which to run the command
cmd
Command to run
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console
``output=all``.
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
CLI Example:
.. code-block:: bash
salt myminion lxc.retcode mycontainer 'ip addr show'
'''
return _run(name,
cmd,
output='retcode',
path=path,
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def run_all(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.5.0
Run :mod:`cmd.run_all <salt.modules.cmdmod.run_all>` within a container
.. note::
While the command is run within the container, it is initiated from the
host. Therefore, the PID in the return dict is from the host, not from
the container.
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed in stderr if the command being run
does not exist.
name
Name of the container in which to run the command
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
cmd
Command to run
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console
``output=all``.
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
CLI Example:
.. code-block:: bash
salt myminion lxc.run_all mycontainer 'ip addr show'
'''
return _run(name,
cmd,
output='all',
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
path=path,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def _get_md5(name, path):
'''
Get the MD5 checksum of a file from a container
'''
output = run_stdout(name, 'md5sum "{0}"'.format(path),
chroot_fallback=True,
ignore_retcode=True)
try:
return output.split()[0]
except IndexError:
# Destination file does not exist or could not be accessed
return None
def copy_to(name, source, dest, overwrite=False, makedirs=False, path=None):
'''
.. versionchanged:: 2015.8.0
Function renamed from ``lxc.cp`` to ``lxc.copy_to`` for consistency
with other container types. ``lxc.cp`` will continue to work, however.
For versions 2015.2.x and earlier, use ``lxc.cp``.
Copy a file or directory from the host into a container
name
Container name
source
File to be copied to the container
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
dest
Destination on the container. Must be an absolute path.
.. versionchanged:: 2015.5.0
If the destination is a directory, the file will be copied into
that directory.
overwrite : False
Unless this option is set to ``True``, then if a file exists at the
location specified by the ``dest`` argument, an error will be raised.
.. versionadded:: 2015.8.0
makedirs : False
Create the parent directory on the container if it does not already
exist.
.. versionadded:: 2015.5.0
CLI Example:
.. code-block:: bash
salt 'minion' lxc.copy_to /tmp/foo /root/foo
salt 'minion' lxc.cp /tmp/foo /root/foo
'''
_ensure_running(name, no_start=True, path=path)
return __salt__['container_resource.copy_to'](
name,
source,
dest,
container_type=__virtualname__,
path=path,
exec_driver=EXEC_DRIVER,
overwrite=overwrite,
makedirs=makedirs)
cp = salt.utils.functools.alias_function(copy_to, 'cp')
def read_conf(conf_file, out_format='simple'):
'''
Read in an LXC configuration file. By default returns a simple, unsorted
dict, but can also return a more detailed structure including blank lines
and comments.
out_format:
set to 'simple' if you need the old and unsupported behavior.
This won't support the multiple lxc values (eg: multiple network nics)
CLI Examples:
.. code-block:: bash
salt 'minion' lxc.read_conf /etc/lxc/mycontainer.conf
salt 'minion' lxc.read_conf /etc/lxc/mycontainer.conf out_format=commented
'''
ret_commented = []
ret_simple = {}
with salt.utils.files.fopen(conf_file, 'r') as fp_:
for line in salt.utils.data.decode(fp_.readlines()):
if '=' not in line:
ret_commented.append(line)
continue
comps = line.split('=')
value = '='.join(comps[1:]).strip()
comment = None
if value.strip().startswith('#'):
vcomps = value.strip().split('#')
value = vcomps[1].strip()
comment = '#'.join(vcomps[1:]).strip()
ret_commented.append({comps[0].strip(): {
'value': value,
'comment': comment,
}})
else:
ret_commented.append({comps[0].strip(): value})
ret_simple[comps[0].strip()] = value
if out_format == 'simple':
return ret_simple
return ret_commented
def write_conf(conf_file, conf):
'''
Write out an LXC configuration file
This is normally only used internally. The format of the data structure
must match that which is returned from ``lxc.read_conf()``, with
``out_format`` set to ``commented``.
An example might look like:
.. code-block:: python
[
{'lxc.utsname': '$CONTAINER_NAME'},
'# This is a commented line\\n',
'\\n',
{'lxc.mount': '$CONTAINER_FSTAB'},
{'lxc.rootfs': {'comment': 'This is another test',
'value': 'This is another test'}},
'\\n',
{'lxc.network.type': 'veth'},
{'lxc.network.flags': 'up'},
{'lxc.network.link': 'br0'},
{'lxc.network.mac': '$CONTAINER_MACADDR'},
{'lxc.network.ipv4': '$CONTAINER_IPADDR'},
{'lxc.network.name': '$CONTAINER_DEVICENAME'},
]
CLI Example:
.. code-block:: bash
salt 'minion' lxc.write_conf /etc/lxc/mycontainer.conf \\
out_format=commented
'''
if not isinstance(conf, list):
raise SaltInvocationError('Configuration must be passed as a list')
# construct the content prior to write to the file
# to avoid half written configs
content = ''
for line in conf:
if isinstance(line, (six.text_type, six.string_types)):
content += line
elif isinstance(line, dict):
for key in list(line.keys()):
out_line = None
if isinstance(
line[key],
(six.text_type, six.string_types, six.integer_types, float)
):
out_line = ' = '.join((key, "{0}".format(line[key])))
elif isinstance(line[key], dict):
out_line = ' = '.join((key, line[key]['value']))
if 'comment' in line[key]:
out_line = ' # '.join((out_line, line[key]['comment']))
if out_line:
content += out_line
content += '\n'
with salt.utils.files.fopen(conf_file, 'w') as fp_:
fp_.write(salt.utils.stringutils.to_str(content))
return {}
def edit_conf(conf_file,
out_format='simple',
read_only=False,
lxc_config=None,
**kwargs):
'''
Edit an LXC configuration file. If a setting is already present inside the
file, its value will be replaced. If it does not exist, it will be appended
to the end of the file. Comments and blank lines will be kept in-tact if
they already exist in the file.
out_format:
Set to simple if you need backward compatibility (multiple items for a
simple key is not supported)
read_only:
return only the edited configuration without applying it
to the underlying lxc configuration file
lxc_config:
List of dict containning lxc configuration items
For network configuration, you also need to add the device it belongs
to, otherwise it will default to eth0.
Also, any change to a network parameter will result in the whole
network reconfiguration to avoid mismatchs, be aware of that !
After the file is edited, its contents will be returned. By default, it
will be returned in ``simple`` format, meaning an unordered dict (which
may not represent the actual file order). Passing in an ``out_format`` of
``commented`` will return a data structure which accurately represents the
order and content of the file.
CLI Example:
.. code-block:: bash
salt 'minion' lxc.edit_conf /etc/lxc/mycontainer.conf \\
out_format=commented lxc.network.type=veth
salt 'minion' lxc.edit_conf /etc/lxc/mycontainer.conf \\
out_format=commented \\
lxc_config="[{'lxc.network.name': 'eth0', \\
'lxc.network.ipv4': '1.2.3.4'},
{'lxc.network.name': 'eth2', \\
'lxc.network.ipv4': '1.2.3.5',\\
'lxc.network.gateway': '1.2.3.1'}]"
'''
data = []
try:
conf = read_conf(conf_file, out_format=out_format)
except Exception:
conf = []
if not lxc_config:
lxc_config = []
lxc_config = copy.deepcopy(lxc_config)
# search if we want to access net config
# in that case, we will replace all the net configuration
net_config = []
for lxc_kws in lxc_config + [kwargs]:
net_params = {}
for kwarg in [a for a in lxc_kws]:
if kwarg.startswith('__'):
continue
if kwarg.startswith('lxc.network.'):
net_params[kwarg] = lxc_kws[kwarg]
lxc_kws.pop(kwarg, None)
if net_params:
net_config.append(net_params)
nic_opts = salt.utils.odict.OrderedDict()
for params in net_config:
dev = params.get('lxc.network.name', DEFAULT_NIC)
dev_opts = nic_opts.setdefault(dev, salt.utils.odict.OrderedDict())
for param in params:
opt = param.replace('lxc.network.', '')
opt = {'hwaddr': 'mac'}.get(opt, opt)
dev_opts[opt] = params[param]
net_changes = []
if nic_opts:
net_changes = _config_list(conf, only_net=True,
**{'network_profile': DEFAULT_NIC,
'nic_opts': nic_opts})
if net_changes:
lxc_config.extend(net_changes)
for line in conf:
if not isinstance(line, dict):
data.append(line)
continue
else:
for key in list(line.keys()):
val = line[key]
if net_changes and key.startswith('lxc.network.'):
continue
found = False
for ix in range(len(lxc_config)):
kw = lxc_config[ix]
if key in kw:
found = True
data.append({key: kw[key]})
del kw[key]
if not found:
data.append({key: val})
for lxc_kws in lxc_config:
for kwarg in lxc_kws:
data.append({kwarg: lxc_kws[kwarg]})
if read_only:
return data
write_conf(conf_file, data)
return read_conf(conf_file, out_format)
def reboot(name, path=None):
'''
Reboot a container.
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Examples:
.. code-block:: bash
salt 'minion' lxc.reboot myvm
'''
ret = {'result': True,
'changes': {},
'comment': '{0} rebooted'.format(name)}
does_exist = exists(name, path=path)
if does_exist and (state(name, path=path) == 'running'):
try:
stop(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
ret['result'] = False
return ret
if does_exist and (state(name, path=path) != 'running'):
try:
start(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
ret['result'] = False
return ret
ret['changes'][name] = 'rebooted'
return ret
def reconfigure(name,
cpu=None,
cpuset=None,
cpushare=None,
memory=None,
profile=None,
network_profile=None,
nic_opts=None,
bridge=None,
gateway=None,
autostart=None,
utsname=None,
rootfs=None,
path=None,
**kwargs):
'''
Reconfigure a container.
This only applies to a few property
name
Name of the container.
utsname
utsname of the container.
.. versionadded:: 2016.3.0
rootfs
rootfs of the container.
.. versionadded:: 2016.3.0
cpu
Select a random number of cpu cores and assign it to the cpuset, if the
cpuset option is set then this option will be ignored
cpuset
Explicitly define the cpus this container will be bound to
cpushare
cgroups cpu shares.
autostart
autostart container on reboot
memory
cgroups memory limit, in MB.
(0 for nolimit, None for old default 1024MB)
gateway
the ipv4 gateway to use
the default does nothing more than lxcutils does
bridge
the bridge to use
the default does nothing more than lxcutils does
nic
Network interfaces profile (defined in config or pillar).
nic_opts
Extra options for network interfaces, will override
``{"eth0": {"mac": "aa:bb:cc:dd:ee:ff", "ipv4": "10.1.1.1", "ipv6": "2001:db8::ff00:42:8329"}}``
or
``{"eth0": {"mac": "aa:bb:cc:dd:ee:ff", "ipv4": "10.1.1.1/24", "ipv6": "2001:db8::ff00:42:8329"}}``
path
path to the container parent
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt-call -lall mc_lxc_fork.reconfigure foobar nic_opts="{'eth1': {'mac': '00:16:3e:dd:ee:44'}}" memory=4
'''
changes = {}
cpath = get_root_path(path)
path = os.path.join(cpath, name, 'config')
ret = {'name': name,
'comment': 'config for {0} up to date'.format(name),
'result': True,
'changes': changes}
profile = get_container_profile(copy.deepcopy(profile))
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, _marker)
profile_match = profile.pop(key, default)
# let kwarg overrides be the preferred choice
if kw_overrides_match is _marker:
return profile_match
return kw_overrides_match
if nic_opts is not None and not network_profile:
network_profile = DEFAULT_NIC
if autostart is not None:
autostart = select('autostart', autostart)
else:
autostart = 'keep'
if not utsname:
utsname = select('utsname', utsname)
if os.path.exists(path):
old_chunks = read_conf(path, out_format='commented')
make_kw = salt.utils.odict.OrderedDict([
('utsname', utsname),
('rootfs', rootfs),
('autostart', autostart),
('cpu', cpu),
('gateway', gateway),
('cpuset', cpuset),
('cpushare', cpushare),
('network_profile', network_profile),
('nic_opts', nic_opts),
('bridge', bridge)])
# match 0 and none as memory = 0 in lxc config is harmful
if memory:
make_kw['memory'] = memory
kw = salt.utils.odict.OrderedDict()
for key, val in six.iteritems(make_kw):
if val is not None:
kw[key] = val
new_cfg = _config_list(conf_tuples=old_chunks, **kw)
if new_cfg:
edit_conf(path, out_format='commented', lxc_config=new_cfg)
chunks = read_conf(path, out_format='commented')
if old_chunks != chunks:
ret['comment'] = '{0} lxc config updated'.format(name)
if state(name, path=path) == 'running':
cret = reboot(name, path=path)
ret['result'] = cret['result']
return ret
def apply_network_profile(name, network_profile, nic_opts=None, path=None):
'''
.. versionadded:: 2015.5.0
Apply a network profile to a container
network_profile
profile name or default values (dict)
nic_opts
values to override in defaults (dict)
indexed by nic card names
path
path to the container parent
.. versionadded:: 2015.8.0
CLI Examples:
.. code-block:: bash
salt 'minion' lxc.apply_network_profile web1 centos
salt 'minion' lxc.apply_network_profile web1 centos \\
nic_opts="{'eth0': {'mac': 'xx:xx:xx:xx:xx:xx'}}"
salt 'minion' lxc.apply_network_profile web1 \\
"{'eth0': {'mac': 'xx:xx:xx:xx:xx:yy'}}"
nic_opts="{'eth0': {'mac': 'xx:xx:xx:xx:xx:xx'}}"
The special case to disable use of ethernet nics:
.. code-block:: bash
salt 'minion' lxc.apply_network_profile web1 centos \\
"{eth0: {disable: true}}"
'''
cpath = get_root_path(path)
cfgpath = os.path.join(cpath, name, 'config')
before = []
with salt.utils.files.fopen(cfgpath, 'r') as fp_:
for line in fp_:
before.append(line)
lxcconfig = _LXCConfig(name=name, path=path)
old_net = lxcconfig._filter_data('lxc.network')
network_params = {}
for param in _network_conf(
conf_tuples=old_net,
network_profile=network_profile, nic_opts=nic_opts
):
network_params.update(param)
if network_params:
edit_conf(cfgpath, out_format='commented', **network_params)
after = []
with salt.utils.files.fopen(cfgpath, 'r') as fp_:
for line in fp_:
after.append(line)
diff = ''
for line in difflib.unified_diff(before,
after,
fromfile='before',
tofile='after'):
diff += line
return diff
def get_pid(name, path=None):
'''
Returns a container pid.
Throw an exception if the container isn't running.
CLI Example:
.. code-block:: bash
salt '*' lxc.get_pid name
'''
if name not in list_(limit='running', path=path):
raise CommandExecutionError('Container {0} is not running, can\'t determine PID'.format(name))
info = __salt__['cmd.run']('lxc-info -n {0}'.format(name)).split("\n")
pid = [line.split(':')[1].strip() for line in info if re.match(r'\s*PID', line)][0]
return pid
def add_veth(name, interface_name, bridge=None, path=None):
'''
Add a veth to a container.
Note : this function doesn't update the container config, just add the interface at runtime
name
Name of the container
interface_name
Name of the interface in the container
bridge
Name of the bridge to attach the interface to (facultative)
CLI Examples:
.. code-block:: bash
salt '*' lxc.add_veth container_name eth1 br1
salt '*' lxc.add_veth container_name eth1
'''
# Get container init PID
pid = get_pid(name, path=path)
# Generate a ramdom string for veth and ensure that is isn't present on the system
while True:
random_veth = 'veth'+''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(6))
if random_veth not in __salt__['network.interfaces']().keys():
break
# Check prerequisites
if not __salt__['file.directory_exists']('/var/run/'):
raise CommandExecutionError('Directory /var/run required for lxc.add_veth doesn\'t exists')
if not __salt__['file.file_exists']('/proc/{0}/ns/net'.format(pid)):
raise CommandExecutionError('Proc file for container {0} network namespace doesn\'t exists'.format(name))
if not __salt__['file.directory_exists']('/var/run/netns'):
__salt__['file.mkdir']('/var/run/netns')
# Ensure that the symlink is up to date (change on container restart)
if __salt__['file.is_link']('/var/run/netns/{0}'.format(name)):
__salt__['file.remove']('/var/run/netns/{0}'.format(name))
__salt__['file.symlink']('/proc/{0}/ns/net'.format(pid), '/var/run/netns/{0}'.format(name))
# Ensure that interface doesn't exists
interface_exists = 0 == __salt__['cmd.retcode']('ip netns exec {netns} ip address list {interface}'.format(
netns=name,
interface=interface_name
))
if interface_exists:
raise CommandExecutionError('Interface {interface} already exists in {container}'.format(
interface=interface_name,
container=name
))
# Create veth and bring it up
if __salt__['cmd.retcode']('ip link add name {veth} type veth peer name {veth}_c'.format(veth=random_veth)) != 0:
raise CommandExecutionError('Error while creating the veth pair {0}'.format(random_veth))
if __salt__['cmd.retcode']('ip link set dev {0} up'.format(random_veth)) != 0:
raise CommandExecutionError('Error while bringing up host-side veth {0}'.format(random_veth))
# Attach it to the container
attached = 0 == __salt__['cmd.retcode']('ip link set dev {veth}_c netns {container} name {interface_name}'.format(
veth=random_veth,
container=name,
interface_name=interface_name
))
if not attached:
raise CommandExecutionError('Error while attaching the veth {veth} to container {container}'.format(
veth=random_veth,
container=name
))
__salt__['file.remove']('/var/run/netns/{0}'.format(name))
if bridge is not None:
__salt__['bridge.addif'](bridge, random_veth)
|
saltstack/salt
|
salt/modules/lxc.py
|
stop
|
python
|
def stop(name, kill=False, path=None, use_vt=None):
'''
Stop the named container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
kill: False
Do not wait for the container to stop, kill all tasks in the container.
Older LXC versions will stop containers like this irrespective of this
argument.
.. versionchanged:: 2015.5.0
Default value changed to ``False``
use_vt
run the command through VT
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.stop name
'''
_ensure_exists(name, path=path)
orig_state = state(name, path=path)
if orig_state == 'frozen' and not kill:
# Gracefully stopping a frozen container is slower than unfreezing and
# then stopping it (at least in my testing), so if we're not
# force-stopping the container, unfreeze it first.
unfreeze(name, path=path)
cmd = 'lxc-stop'
if kill:
cmd += ' -k'
ret = _change_state(cmd, name, 'stopped', use_vt=use_vt, path=path)
ret['state']['old'] = orig_state
return ret
|
Stop the named container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
kill: False
Do not wait for the container to stop, kill all tasks in the container.
Older LXC versions will stop containers like this irrespective of this
argument.
.. versionchanged:: 2015.5.0
Default value changed to ``False``
use_vt
run the command through VT
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.stop name
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/lxc.py#L2440-L2481
|
[
"def state(name, path=None):\n '''\n Returns the state of a container.\n\n path\n path to the container parent directory (default: /var/lib/lxc)\n\n .. versionadded:: 2015.8.0\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' lxc.state name\n '''\n # Don't use _ensure_exists() here, it will mess with _change_state()\n\n cachekey = 'lxc.state.{0}{1}'.format(name, path)\n try:\n return __context__[cachekey]\n except KeyError:\n if not exists(name, path=path):\n __context__[cachekey] = None\n else:\n cmd = 'lxc-info'\n if path:\n cmd += ' -P {0}'.format(pipes.quote(path))\n cmd += ' -n {0}'.format(name)\n ret = __salt__['cmd.run_all'](cmd, python_shell=False)\n if ret['retcode'] != 0:\n _clear_context()\n raise CommandExecutionError(\n 'Unable to get state of container \\'{0}\\''.format(name)\n )\n c_infos = ret['stdout'].splitlines()\n c_state = None\n for c_info in c_infos:\n stat = c_info.split(':')\n if stat[0].lower() == 'state':\n c_state = stat[1].strip().lower()\n break\n __context__[cachekey] = c_state\n return __context__[cachekey]\n",
"def _change_state(cmd,\n name,\n expected,\n stdin=_marker,\n stdout=_marker,\n stderr=_marker,\n with_communicate=_marker,\n use_vt=_marker,\n path=None):\n pre = state(name, path=path)\n if pre == expected:\n return {'result': True,\n 'state': {'old': expected, 'new': expected},\n 'comment': 'Container \\'{0}\\' already {1}'\n .format(name, expected)}\n\n if cmd == 'lxc-destroy':\n # Kill the container first\n scmd = 'lxc-stop'\n if path:\n scmd += ' -P {0}'.format(pipes.quote(path))\n scmd += ' -k -n {0}'.format(name)\n __salt__['cmd.run'](scmd,\n python_shell=False)\n\n if path and ' -P ' not in cmd:\n cmd += ' -P {0}'.format(pipes.quote(path))\n cmd += ' -n {0}'.format(name)\n\n # certain lxc commands need to be taken with care (lxc-start)\n # as te command itself mess with double forks; we must not\n # communicate with it, but just wait for the exit status\n pkwargs = {'python_shell': False,\n 'redirect_stderr': True,\n 'with_communicate': with_communicate,\n 'use_vt': use_vt,\n 'stdin': stdin,\n 'stdout': stdout}\n for i in [a for a in pkwargs]:\n val = pkwargs[i]\n if val is _marker:\n pkwargs.pop(i, None)\n\n _cmdout = __salt__['cmd.run_all'](cmd, **pkwargs)\n\n if _cmdout['retcode'] != 0:\n raise CommandExecutionError(\n 'Error changing state for container \\'{0}\\' using command '\n '\\'{1}\\': {2}'.format(name, cmd, _cmdout['stdout'])\n )\n if expected is not None:\n # some commands do not wait, so we will\n rcmd = 'lxc-wait'\n if path:\n rcmd += ' -P {0}'.format(pipes.quote(path))\n rcmd += ' -n {0} -s {1}'.format(name, expected.upper())\n __salt__['cmd.run'](rcmd, python_shell=False, timeout=30)\n _clear_context()\n post = state(name, path=path)\n ret = {'result': post == expected,\n 'state': {'old': pre, 'new': post}}\n return ret\n",
"def unfreeze(name, path=None, use_vt=None):\n '''\n Unfreeze the named container.\n\n path\n path to the container parent directory\n default: /var/lib/lxc (system)\n\n .. versionadded:: 2015.8.0\n\n use_vt\n run the command through VT\n\n .. versionadded:: 2015.8.0\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' lxc.unfreeze name\n '''\n _ensure_exists(name, path=path)\n if state(name, path=path) == 'stopped':\n raise CommandExecutionError(\n 'Container \\'{0}\\' is stopped'.format(name)\n )\n cmd = 'lxc-unfreeze'\n if path:\n cmd += ' -P {0}'.format(pipes.quote(path))\n return _change_state(cmd, name, 'running', path=path, use_vt=use_vt)\n",
"def _ensure_exists(name, path=None):\n '''\n Raise an exception if the container does not exist\n '''\n if not exists(name, path=path):\n raise CommandExecutionError(\n 'Container \\'{0}\\' does not exist'.format(name)\n )\n"
] |
# -*- coding: utf-8 -*-
'''
Control Linux Containers via Salt
:depends: lxc package for distribution
lxc >= 1.0 (even beta alpha) is required
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import datetime
import copy
import string
import textwrap
import difflib
import logging
import tempfile
import os
import pipes
import time
import shutil
import re
import random
# Import salt libs
import salt.utils.args
import salt.utils.cloud
import salt.utils.data
import salt.utils.dictupdate
import salt.utils.files
import salt.utils.functools
import salt.utils.hashutils
import salt.utils.network
import salt.utils.odict
import salt.utils.path
import salt.utils.stringutils
from salt.exceptions import CommandExecutionError, SaltInvocationError
import salt.config
from salt.utils.versions import LooseVersion as _LooseVersion
# Import 3rd-party libs
from salt.ext import six
# pylint: disable=import-error,no-name-in-module
from salt.ext.six.moves import range # pylint: disable=redefined-builtin
from salt.ext.six.moves.urllib.parse import urlparse as _urlparse
# pylint: enable=import-error,no-name-in-module
# Set up logging
log = logging.getLogger(__name__)
# Don't shadow built-in's.
__func_alias__ = {
'list_': 'list',
'ls_': 'ls'
}
__virtualname__ = 'lxc'
DEFAULT_NIC = 'eth0'
DEFAULT_BR = 'br0'
SEED_MARKER = '/lxc.initial_seed'
EXEC_DRIVER = 'lxc-attach'
DEFAULT_PATH = '/var/lib/lxc'
_marker = object()
def __virtual__():
if salt.utils.path.which('lxc-start'):
return __virtualname__
# To speed up the whole thing, we decided to not use the
# subshell way and assume things are in place for lxc
# Discussion made by @kiorky and @thatch45
# lxc-version presence is not sufficient, in lxc1.0 alpha
# (precise backports), we have it and it is sufficient
# for the module to execute.
# elif salt.utils.path.which('lxc-version'):
# passed = False
# try:
# passed = subprocess.check_output(
# 'lxc-version').split(':')[1].strip() >= '1.0'
# except Exception:
# pass
# if not passed:
# log.warning('Support for lxc < 1.0 may be incomplete.')
# return 'lxc'
# return False
#
return (False, 'The lxc execution module cannot be loaded: the lxc-start binary is not in the path.')
def get_root_path(path):
'''
Get the configured lxc root for containers
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.get_root_path
'''
if not path:
path = __opts__.get('lxc.root_path', DEFAULT_PATH)
return path
def version():
'''
Return the actual lxc client version
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.version
'''
k = 'lxc.version'
if not __context__.get(k, None):
cversion = __salt__['cmd.run_all']('lxc-info --version')
if not cversion['retcode']:
ver = _LooseVersion(cversion['stdout'])
if ver < _LooseVersion('1.0'):
raise CommandExecutionError('LXC should be at least 1.0')
__context__[k] = "{0}".format(ver)
return __context__.get(k, None)
def _clear_context():
'''
Clear any lxc variables set in __context__
'''
for var in [x for x in __context__ if x.startswith('lxc.')]:
log.trace('Clearing __context__[\'%s\']', var)
__context__.pop(var, None)
def _ip_sort(ip):
'''Ip sorting'''
idx = '001'
if ip == '127.0.0.1':
idx = '200'
if ip == '::1':
idx = '201'
elif '::' in ip:
idx = '100'
return '{0}___{1}'.format(idx, ip)
def search_lxc_bridges():
'''
Search which bridges are potentially available as LXC bridges
CLI Example:
.. code-block:: bash
salt '*' lxc.search_lxc_bridges
'''
bridges = __context__.get('lxc.bridges', None)
# either match not yet called or no bridges were found
# to handle the case where lxc was not installed on the first
# call
if not bridges:
bridges = set()
running_bridges = set()
bridges.add(DEFAULT_BR)
try:
output = __salt__['cmd.run_all']('brctl show')
for line in output['stdout'].splitlines()[1:]:
if not line.startswith(' '):
running_bridges.add(line.split()[0].strip())
except (SaltInvocationError, CommandExecutionError):
pass
for ifc, ip in six.iteritems(
__grains__.get('ip_interfaces', {})
):
if ifc in running_bridges:
bridges.add(ifc)
elif os.path.exists(
'/sys/devices/virtual/net/{0}/bridge'.format(ifc)
):
bridges.add(ifc)
bridges = list(bridges)
# if we found interfaces that have lxc in their names
# we filter them as being the potential lxc bridges
# we also try to default on br0 on other cases
def sort_bridges(a):
pref = 'z'
if 'lxc' in a:
pref = 'a'
elif 'br0' == a:
pref = 'c'
return '{0}_{1}'.format(pref, a)
bridges.sort(key=sort_bridges)
__context__['lxc.bridges'] = bridges
return bridges
def search_lxc_bridge():
'''
Search the first bridge which is potentially available as LXC bridge
CLI Example:
.. code-block:: bash
salt '*' lxc.search_lxc_bridge
'''
return search_lxc_bridges()[0]
def _get_salt_config(config, **kwargs):
if not config:
config = kwargs.get('minion', {})
if not config:
config = {}
config.setdefault('master',
kwargs.get('master',
__opts__.get('master',
__opts__['id'])))
config.setdefault(
'master_port',
kwargs.get('master_port',
__opts__.get('master_port',
__opts__.get('ret_port',
__opts__.get('4506')))))
if not config['master']:
config = {}
return config
def cloud_init_interface(name, vm_=None, **kwargs):
'''
Interface between salt.cloud.lxc driver and lxc.init
``vm_`` is a mapping of vm opts in the salt.cloud format
as documented for the lxc driver.
This can be used either:
- from the salt cloud driver
- because you find the argument to give easier here
than using directly lxc.init
.. warning::
BE REALLY CAREFUL CHANGING DEFAULTS !!!
IT'S A RETRO COMPATIBLE INTERFACE WITH
THE SALT CLOUD DRIVER (ask kiorky).
name
name of the lxc container to create
pub_key
public key to preseed the minion with.
Can be the keycontent or a filepath
priv_key
private key to preseed the minion with.
Can be the keycontent or a filepath
path
path to the container parent directory (default: /var/lib/lxc)
.. versionadded:: 2015.8.0
profile
:ref:`profile <tutorial-lxc-profiles-container>` selection
network_profile
:ref:`network profile <tutorial-lxc-profiles-network>` selection
nic_opts
per interface settings compatibles with
network profile (ipv4/ipv6/link/gateway/mac/netmask)
eg::
- {'eth0': {'mac': '00:16:3e:01:29:40',
'gateway': None, (default)
'link': 'br0', (default)
'gateway': None, (default)
'netmask': '', (default)
'ip': '22.1.4.25'}}
unconditional_install
given to lxc.bootstrap (see relative doc)
force_install
given to lxc.bootstrap (see relative doc)
config
any extra argument for the salt minion config
dnsservers
list of DNS servers to set inside the container
dns_via_dhcp
do not set the dns servers, let them be set by the dhcp.
autostart
autostart the container at boot time
password
administrative password for the container
bootstrap_delay
delay before launching bootstrap script at Container init
.. warning::
Legacy but still supported options:
from_container
which container we use as a template
when running lxc.clone
image
which template do we use when we
are using lxc.create. This is the default
mode unless you specify something in from_container
backing
which backing store to use.
Values can be: overlayfs, dir(default), lvm, zfs, brtfs
fstype
When using a blockdevice level backing store,
which filesystem to use on
size
When using a blockdevice level backing store,
which size for the filesystem to use on
snapshot
Use snapshot when cloning the container source
vgname
if using LVM: vgname
lvname
if using LVM: lvname
thinpool:
if using LVM: thinpool
ip
ip for the primary nic
mac
mac address for the primary nic
netmask
netmask for the primary nic (24)
= ``vm_.get('netmask', '24')``
bridge
bridge for the primary nic (lxcbr0)
gateway
network gateway for the container
additional_ips
additional ips which will be wired on the main bridge (br0)
which is connected to internet.
Be aware that you may use manual virtual mac addresses
providen by you provider (online, ovh, etc).
This is a list of mappings {ip: '', mac: '', netmask:''}
Set gateway to None and an interface with a gateway
to escape from another interface that eth0.
eg::
- {'mac': '00:16:3e:01:29:40',
'gateway': None, (default)
'link': 'br0', (default)
'netmask': '', (default)
'ip': '22.1.4.25'}
users
administrative users for the container
default: [root] and [root, ubuntu] on ubuntu
default_nic
name of the first interface, you should
really not override this
CLI Example:
.. code-block:: bash
salt '*' lxc.cloud_init_interface foo
'''
if vm_ is None:
vm_ = {}
vm_ = copy.deepcopy(vm_)
vm_ = salt.utils.dictupdate.update(vm_, kwargs)
profile_data = copy.deepcopy(
vm_.get('lxc_profile',
vm_.get('profile', {})))
if not isinstance(profile_data, (dict, six.string_types)):
profile_data = {}
profile = get_container_profile(profile_data)
def _cloud_get(k, default=None):
return vm_.get(k, profile.get(k, default))
if name is None:
name = vm_['name']
# if we are on ubuntu, default to ubuntu
default_template = ''
if __grains__.get('os', '') in ['Ubuntu']:
default_template = 'ubuntu'
image = _cloud_get('image')
if not image:
_cloud_get('template', default_template)
backing = _cloud_get('backing', 'dir')
if image:
profile['template'] = image
vgname = _cloud_get('vgname', None)
if vgname:
profile['vgname'] = vgname
if backing:
profile['backing'] = backing
snapshot = _cloud_get('snapshot', False)
autostart = bool(_cloud_get('autostart', True))
dnsservers = _cloud_get('dnsservers', [])
dns_via_dhcp = _cloud_get('dns_via_dhcp', True)
password = _cloud_get('password', 's3cr3t')
password_encrypted = _cloud_get('password_encrypted', False)
fstype = _cloud_get('fstype', None)
lvname = _cloud_get('lvname', None)
thinpool = _cloud_get('thinpool', None)
pub_key = _cloud_get('pub_key', None)
priv_key = _cloud_get('priv_key', None)
size = _cloud_get('size', '20G')
script = _cloud_get('script', None)
script_args = _cloud_get('script_args', None)
users = _cloud_get('users', None)
if users is None:
users = []
ssh_username = _cloud_get('ssh_username', None)
if ssh_username and (ssh_username not in users):
users.append(ssh_username)
network_profile = _cloud_get('network_profile', None)
nic_opts = kwargs.get('nic_opts', None)
netmask = _cloud_get('netmask', '24')
path = _cloud_get('path', None)
bridge = _cloud_get('bridge', None)
gateway = _cloud_get('gateway', None)
unconditional_install = _cloud_get('unconditional_install', False)
force_install = _cloud_get('force_install', True)
config = _get_salt_config(_cloud_get('config', {}), **vm_)
default_nic = _cloud_get('default_nic', DEFAULT_NIC)
# do the interface with lxc.init mainly via nic_opts
# to avoid extra and confusing extra use cases.
if not isinstance(nic_opts, dict):
nic_opts = salt.utils.odict.OrderedDict()
# have a reference to the default nic
eth0 = nic_opts.setdefault(default_nic,
salt.utils.odict.OrderedDict())
# lxc config is based of ifc order, be sure to use odicts.
if not isinstance(nic_opts, salt.utils.odict.OrderedDict):
bnic_opts = salt.utils.odict.OrderedDict()
bnic_opts.update(nic_opts)
nic_opts = bnic_opts
gw = None
# legacy salt.cloud scheme for network interfaces settings support
bridge = _cloud_get('bridge', None)
ip = _cloud_get('ip', None)
mac = _cloud_get('mac', None)
if ip:
fullip = ip
if netmask:
fullip += '/{0}'.format(netmask)
eth0['ipv4'] = fullip
if mac is not None:
eth0['mac'] = mac
for ix, iopts in enumerate(_cloud_get("additional_ips", [])):
ifh = "eth{0}".format(ix+1)
ethx = nic_opts.setdefault(ifh, {})
if gw is None:
gw = iopts.get('gateway', ethx.get('gateway', None))
if gw:
# only one and only one default gateway is allowed !
eth0.pop('gateway', None)
gateway = None
# even if the gateway if on default "eth0" nic
# and we popped it will work
# as we reinject or set it here.
ethx['gateway'] = gw
elink = iopts.get('link', ethx.get('link', None))
if elink:
ethx['link'] = elink
# allow dhcp
aip = iopts.get('ipv4', iopts.get('ip', None))
if aip:
ethx['ipv4'] = aip
nm = iopts.get('netmask', '')
if nm:
ethx['ipv4'] += '/{0}'.format(nm)
for i in ('mac', 'hwaddr'):
if i in iopts:
ethx['mac'] = iopts[i]
break
if 'mac' not in ethx:
ethx['mac'] = salt.utils.network.gen_mac()
# last round checking for unique gateway and such
gw = None
for ethx in [a for a in nic_opts]:
ndata = nic_opts[ethx]
if gw:
ndata.pop('gateway', None)
if 'gateway' in ndata:
gw = ndata['gateway']
gateway = None
# only use a default bridge / gateway if we configured them
# via the legacy salt cloud configuration style.
# On other cases, we should rely on settings provided by the new
# salt lxc network profile style configuration which can
# be also be overridden or a per interface basis via the nic_opts dict.
if bridge:
eth0['link'] = bridge
if gateway:
eth0['gateway'] = gateway
#
lxc_init_interface = {}
lxc_init_interface['name'] = name
lxc_init_interface['config'] = config
lxc_init_interface['memory'] = _cloud_get('memory', 0) # nolimit
lxc_init_interface['pub_key'] = pub_key
lxc_init_interface['priv_key'] = priv_key
lxc_init_interface['nic_opts'] = nic_opts
for clone_from in ['clone_from', 'clone', 'from_container']:
# clone_from should default to None if not available
lxc_init_interface['clone_from'] = _cloud_get(clone_from, None)
if lxc_init_interface['clone_from'] is not None:
break
lxc_init_interface['profile'] = profile
lxc_init_interface['snapshot'] = snapshot
lxc_init_interface['dnsservers'] = dnsservers
lxc_init_interface['fstype'] = fstype
lxc_init_interface['path'] = path
lxc_init_interface['vgname'] = vgname
lxc_init_interface['size'] = size
lxc_init_interface['lvname'] = lvname
lxc_init_interface['thinpool'] = thinpool
lxc_init_interface['force_install'] = force_install
lxc_init_interface['unconditional_install'] = (
unconditional_install
)
lxc_init_interface['bootstrap_url'] = script
lxc_init_interface['bootstrap_args'] = script_args
lxc_init_interface['bootstrap_shell'] = _cloud_get('bootstrap_shell', 'sh')
lxc_init_interface['bootstrap_delay'] = _cloud_get('bootstrap_delay', None)
lxc_init_interface['autostart'] = autostart
lxc_init_interface['users'] = users
lxc_init_interface['password'] = password
lxc_init_interface['password_encrypted'] = password_encrypted
# be sure not to let objects goes inside the return
# as this return will be msgpacked for use in the runner !
lxc_init_interface['network_profile'] = network_profile
for i in ['cpu', 'cpuset', 'cpushare']:
if _cloud_get(i, None):
try:
lxc_init_interface[i] = vm_[i]
except KeyError:
lxc_init_interface[i] = profile[i]
return lxc_init_interface
def _get_profile(key, name, **kwargs):
if isinstance(name, dict):
profilename = name.pop('name', None)
return _get_profile(key, profilename, **name)
if name is None:
profile_match = {}
else:
profile_match = \
__salt__['config.get'](
'lxc.{1}:{0}'.format(name, key),
default=None,
merge='recurse'
)
if profile_match is None:
# No matching profile, make the profile an empty dict so that
# overrides can be applied below.
profile_match = {}
if not isinstance(profile_match, dict):
raise CommandExecutionError('lxc.{0} must be a dictionary'.format(key))
# Overlay the kwargs to override matched profile data
overrides = salt.utils.args.clean_kwargs(**copy.deepcopy(kwargs))
profile_match = salt.utils.dictupdate.update(
copy.deepcopy(profile_match),
overrides
)
return profile_match
def get_container_profile(name=None, **kwargs):
'''
.. versionadded:: 2015.5.0
Gather a pre-configured set of container configuration parameters. If no
arguments are passed, an empty profile is returned.
Profiles can be defined in the minion or master config files, or in pillar
or grains, and are loaded using :mod:`config.get
<salt.modules.config.get>`. The key under which LXC profiles must be
configured is ``lxc.container_profile.profile_name``. An example container
profile would be as follows:
.. code-block:: yaml
lxc.container_profile:
ubuntu:
template: ubuntu
backing: lvm
vgname: lxc
size: 1G
Parameters set in a profile can be overridden by passing additional
container creation arguments (such as the ones passed to :mod:`lxc.create
<salt.modules.lxc.create>`) to this function.
A profile can be defined either as the name of the profile, or a dictionary
of variable names and values. See the :ref:`LXC Tutorial
<tutorial-lxc-profiles>` for more information on how to use LXC profiles.
CLI Example:
.. code-block:: bash
salt-call lxc.get_container_profile centos
salt-call lxc.get_container_profile ubuntu template=ubuntu backing=overlayfs
'''
profile = _get_profile('container_profile', name, **kwargs)
return profile
def get_network_profile(name=None, **kwargs):
'''
.. versionadded:: 2015.5.0
Gather a pre-configured set of network configuration parameters. If no
arguments are passed, the following default profile is returned:
.. code-block:: python
{'eth0': {'link': 'br0', 'type': 'veth', 'flags': 'up'}}
Profiles can be defined in the minion or master config files, or in pillar
or grains, and are loaded using :mod:`config.get
<salt.modules.config.get>`. The key under which LXC profiles must be
configured is ``lxc.network_profile``. An example network profile would be
as follows:
.. code-block:: yaml
lxc.network_profile.centos:
eth0:
link: br0
type: veth
flags: up
To disable networking entirely:
.. code-block:: yaml
lxc.network_profile.centos:
eth0:
disable: true
Parameters set in a profile can be overridden by passing additional
arguments to this function.
A profile can be passed either as the name of the profile, or a
dictionary of variable names and values. See the :ref:`LXC Tutorial
<tutorial-lxc-profiles>` for more information on how to use network
profiles.
.. warning::
The ``ipv4``, ``ipv6``, ``gateway``, and ``link`` (bridge) settings in
network profiles will only work if the container doesn't redefine the
network configuration (for example in
``/etc/sysconfig/network-scripts/ifcfg-<interface_name>`` on
RHEL/CentOS, or ``/etc/network/interfaces`` on Debian/Ubuntu/etc.)
CLI Example:
.. code-block:: bash
salt-call lxc.get_network_profile default
'''
profile = _get_profile('network_profile', name, **kwargs)
return profile
def _rand_cpu_str(cpu):
'''
Return a random subset of cpus for the cpuset config
'''
cpu = int(cpu)
avail = __salt__['status.nproc']()
if cpu < avail:
return '0-{0}'.format(avail)
to_set = set()
while len(to_set) < cpu:
choice = random.randint(0, avail - 1)
if choice not in to_set:
to_set.add(six.text_type(choice))
return ','.join(sorted(to_set))
def _network_conf(conf_tuples=None, **kwargs):
'''
Network configuration defaults
network_profile
as for containers, we can either call this function
either with a network_profile dict or network profile name
in the kwargs
nic_opts
overrides or extra nics in the form {nic_name: {set: tings}
'''
nic = kwargs.get('network_profile', None)
ret = []
nic_opts = kwargs.get('nic_opts', {})
if nic_opts is None:
# coming from elsewhere
nic_opts = {}
if not conf_tuples:
conf_tuples = []
old = _get_veths(conf_tuples)
if not old:
old = {}
# if we have a profile name, get the profile and load the network settings
# this will obviously by default look for a profile called "eth0"
# or by what is defined in nic_opts
# and complete each nic settings by sane defaults
if nic and isinstance(nic, (six.string_types, dict)):
nicp = get_network_profile(nic)
else:
nicp = {}
if DEFAULT_NIC not in nicp:
nicp[DEFAULT_NIC] = {}
kwargs = copy.deepcopy(kwargs)
gateway = kwargs.pop('gateway', None)
bridge = kwargs.get('bridge', None)
if nic_opts:
for dev, args in six.iteritems(nic_opts):
ethx = nicp.setdefault(dev, {})
try:
ethx = salt.utils.dictupdate.update(ethx, args)
except AttributeError:
raise SaltInvocationError('Invalid nic_opts configuration')
ifs = [a for a in nicp]
ifs += [a for a in old if a not in nicp]
ifs.sort()
gateway_set = False
for dev in ifs:
args = nicp.get(dev, {})
opts = nic_opts.get(dev, {}) if nic_opts else {}
old_if = old.get(dev, {})
disable = opts.get('disable', args.get('disable', False))
if disable:
continue
mac = opts.get('mac',
opts.get('hwaddr',
args.get('mac',
args.get('hwaddr', ''))))
type_ = opts.get('type', args.get('type', ''))
flags = opts.get('flags', args.get('flags', ''))
link = opts.get('link', args.get('link', ''))
ipv4 = opts.get('ipv4', args.get('ipv4', ''))
ipv6 = opts.get('ipv6', args.get('ipv6', ''))
infos = salt.utils.odict.OrderedDict([
('lxc.network.type', {
'test': not type_,
'value': type_,
'old': old_if.get('lxc.network.type'),
'default': 'veth'}),
('lxc.network.name', {
'test': False,
'value': dev,
'old': dev,
'default': dev}),
('lxc.network.flags', {
'test': not flags,
'value': flags,
'old': old_if.get('lxc.network.flags'),
'default': 'up'}),
('lxc.network.link', {
'test': not link,
'value': link,
'old': old_if.get('lxc.network.link'),
'default': search_lxc_bridge()}),
('lxc.network.hwaddr', {
'test': not mac,
'value': mac,
'old': old_if.get('lxc.network.hwaddr'),
'default': salt.utils.network.gen_mac()}),
('lxc.network.ipv4', {
'test': not ipv4,
'value': ipv4,
'old': old_if.get('lxc.network.ipv4', ''),
'default': None}),
('lxc.network.ipv6', {
'test': not ipv6,
'value': ipv6,
'old': old_if.get('lxc.network.ipv6', ''),
'default': None})])
# for each parameter, if not explicitly set, the
# config value present in the LXC configuration should
# take precedence over the profile configuration
for info in list(infos.keys()):
bundle = infos[info]
if bundle['test']:
if bundle['old']:
bundle['value'] = bundle['old']
elif bundle['default']:
bundle['value'] = bundle['default']
for info, data in six.iteritems(infos):
if data['value']:
ret.append({info: data['value']})
for key, val in six.iteritems(args):
if key == 'link' and bridge:
val = bridge
val = opts.get(key, val)
if key in [
'type', 'flags', 'name',
'gateway', 'mac', 'link', 'ipv4', 'ipv6'
]:
continue
ret.append({'lxc.network.{0}'.format(key): val})
# gateway (in automode) must be appended following network conf !
if not gateway:
gateway = args.get('gateway', None)
if gateway is not None and not gateway_set:
ret.append({'lxc.network.ipv4.gateway': gateway})
# only one network gateway ;)
gateway_set = True
# normally, this won't happen
# set the gateway if specified even if we did
# not managed the network underlying
if gateway is not None and not gateway_set:
ret.append({'lxc.network.ipv4.gateway': gateway})
# only one network gateway ;)
gateway_set = True
new = _get_veths(ret)
# verify that we did not loose the mac settings
for iface in [a for a in new]:
ndata = new[iface]
nmac = ndata.get('lxc.network.hwaddr', '')
ntype = ndata.get('lxc.network.type', '')
omac, otype = '', ''
if iface in old:
odata = old[iface]
omac = odata.get('lxc.network.hwaddr', '')
otype = odata.get('lxc.network.type', '')
# default for network type is setted here
# attention not to change the network type
# without a good and explicit reason to.
if otype and not ntype:
ntype = otype
if not ntype:
ntype = 'veth'
new[iface]['lxc.network.type'] = ntype
if omac and not nmac:
new[iface]['lxc.network.hwaddr'] = omac
ret = []
for val in six.itervalues(new):
for row in val:
ret.append(salt.utils.odict.OrderedDict([(row, val[row])]))
# on old versions of lxc, still support the gateway auto mode
# if we didn't explicitly say no to
# (lxc.network.ipv4.gateway: auto)
if _LooseVersion(version()) <= _LooseVersion('1.0.7') and \
True not in ['lxc.network.ipv4.gateway' in a for a in ret] and \
True in ['lxc.network.ipv4' in a for a in ret]:
ret.append({'lxc.network.ipv4.gateway': 'auto'})
return ret
def _get_lxc_default_data(**kwargs):
kwargs = copy.deepcopy(kwargs)
ret = {}
for k in ['utsname', 'rootfs']:
val = kwargs.get(k, None)
if val is not None:
ret['lxc.{0}'.format(k)] = val
autostart = kwargs.get('autostart')
# autostart can have made in kwargs, but with the None
# value which is invalid, we need an explicit boolean
# autostart = on is the default.
if autostart is None:
autostart = True
# we will set the regular lxc marker to restart container at
# machine (re)boot only if we did not explicitly ask
# not to touch to the autostart settings via
# autostart == 'keep'
if autostart != 'keep':
if autostart:
ret['lxc.start.auto'] = '1'
else:
ret['lxc.start.auto'] = '0'
memory = kwargs.get('memory')
if memory is not None:
# converting the config value from MB to bytes
ret['lxc.cgroup.memory.limit_in_bytes'] = memory * 1024 * 1024
cpuset = kwargs.get('cpuset')
if cpuset:
ret['lxc.cgroup.cpuset.cpus'] = cpuset
cpushare = kwargs.get('cpushare')
cpu = kwargs.get('cpu')
if cpushare:
ret['lxc.cgroup.cpu.shares'] = cpushare
if cpu and not cpuset:
ret['lxc.cgroup.cpuset.cpus'] = _rand_cpu_str(cpu)
return ret
def _config_list(conf_tuples=None, only_net=False, **kwargs):
'''
Return a list of dicts from the salt level configurations
conf_tuples
_LXCConfig compatible list of entries which can contain
- string line
- tuple (lxc config param,value)
- dict of one entry: {lxc config param: value)
only_net
by default we add to the tuples a reflection of both
the real config if avalaible and a certain amount of
default values like the cpu parameters, the memory
and etc.
On the other hand, we also no matter the case reflect
the network configuration computed from the actual config if
available and given values.
if no_default_loads is set, we will only
reflect the network configuration back to the conf tuples
list
'''
# explicit cast
only_net = bool(only_net)
if not conf_tuples:
conf_tuples = []
kwargs = copy.deepcopy(kwargs)
ret = []
if not only_net:
default_data = _get_lxc_default_data(**kwargs)
for k, val in six.iteritems(default_data):
ret.append({k: val})
net_datas = _network_conf(conf_tuples=conf_tuples, **kwargs)
ret.extend(net_datas)
return ret
def _get_veths(net_data):
'''
Parse the nic setup inside lxc conf tuples back to a dictionary indexed by
network interface
'''
if isinstance(net_data, dict):
net_data = list(net_data.items())
nics = salt.utils.odict.OrderedDict()
current_nic = salt.utils.odict.OrderedDict()
no_names = True
for item in net_data:
if item and isinstance(item, dict):
item = list(item.items())[0]
# skip LXC configuration comment lines, and play only with tuples conf
elif isinstance(item, six.string_types):
# deal with reflection of commented lxc configs
sitem = item.strip()
if sitem.startswith('#') or not sitem:
continue
elif '=' in item:
item = tuple([a.strip() for a in item.split('=', 1)])
if item[0] == 'lxc.network.type':
current_nic = salt.utils.odict.OrderedDict()
if item[0] == 'lxc.network.name':
no_names = False
nics[item[1].strip()] = current_nic
current_nic[item[0].strip()] = item[1].strip()
# if not ethernet card name has been collected, assuming we collected
# data for eth0
if no_names and current_nic:
nics[DEFAULT_NIC] = current_nic
return nics
class _LXCConfig(object):
'''
LXC configuration data
'''
pattern = re.compile(r'^(\S+)(\s*)(=)(\s*)(.*)')
non_interpretable_pattern = re.compile(r'^((#.*)|(\s*))$')
def __init__(self, **kwargs):
kwargs = copy.deepcopy(kwargs)
self.name = kwargs.pop('name', None)
path = get_root_path(kwargs.get('path', None))
self.data = []
if self.name:
self.path = os.path.join(path, self.name, 'config')
if os.path.isfile(self.path):
with salt.utils.files.fopen(self.path) as fhr:
for line in salt.utils.data.decode(fhr.readlines()):
match = self.pattern.findall((line.strip()))
if match:
self.data.append((match[0][0], match[0][-1]))
match = self.non_interpretable_pattern.findall(
(line.strip()))
if match:
self.data.append(('', match[0][0]))
else:
self.path = None
def _replace(key, val):
if val:
self._filter_data(key)
self.data.append((key, val))
default_data = _get_lxc_default_data(**kwargs)
for key, val in six.iteritems(default_data):
_replace(key, val)
old_net = self._filter_data('lxc.network')
net_datas = _network_conf(conf_tuples=old_net, **kwargs)
if net_datas:
for row in net_datas:
self.data.extend(list(row.items()))
# be sure to reset harmful settings
for idx in ['lxc.cgroup.memory.limit_in_bytes']:
if not default_data.get(idx):
self._filter_data(idx)
def as_string(self):
chunks = ('{0[0]}{1}{0[1]}'.format(item, (' = ' if item[0] else '')) for item in self.data)
return '\n'.join(chunks) + '\n'
def write(self):
if self.path:
content = self.as_string()
# 2 step rendering to be sure not to open/wipe the config
# before as_string succeeds.
with salt.utils.files.fopen(self.path, 'w') as fic:
fic.write(salt.utils.stringutils.to_str(content))
fic.flush()
def tempfile(self):
# this might look like the function name is shadowing the
# module, but it's not since the method belongs to the class
ntf = tempfile.NamedTemporaryFile()
ntf.write(self.as_string())
ntf.flush()
return ntf
def _filter_data(self, pattern):
'''
Removes parameters which match the pattern from the config data
'''
removed = []
filtered = []
for param in self.data:
if not param[0].startswith(pattern):
filtered.append(param)
else:
removed.append(param)
self.data = filtered
return removed
def _get_base(**kwargs):
'''
If the needed base does not exist, then create it, if it does exist
create nothing and return the name of the base lxc container so
it can be cloned.
'''
profile = get_container_profile(copy.deepcopy(kwargs.get('profile')))
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, _marker)
profile_match = profile.pop(key, default)
# let kwarg overrides be the preferred choice
if kw_overrides_match is _marker:
return profile_match
return kw_overrides_match
template = select('template')
image = select('image')
vgname = select('vgname')
path = kwargs.get('path', None)
# remove the above three variables from kwargs, if they exist, to avoid
# duplicates if create() is invoked below.
for param in ('path', 'image', 'vgname', 'template'):
kwargs.pop(param, None)
if image:
proto = _urlparse(image).scheme
img_tar = __salt__['cp.cache_file'](image)
img_name = os.path.basename(img_tar)
hash_ = salt.utils.hashutils.get_hash(
img_tar,
__salt__['config.get']('hash_type'))
name = '__base_{0}_{1}_{2}'.format(proto, img_name, hash_)
if not exists(name, path=path):
create(name, template=template, image=image,
path=path, vgname=vgname, **kwargs)
if vgname:
rootfs = os.path.join('/dev', vgname, name)
edit_conf(info(name, path=path)['config'],
out_format='commented', **{'lxc.rootfs': rootfs})
return name
elif template:
name = '__base_{0}'.format(template)
if not exists(name, path=path):
create(name, template=template, image=image, path=path,
vgname=vgname, **kwargs)
if vgname:
rootfs = os.path.join('/dev', vgname, name)
edit_conf(info(name, path=path)['config'],
out_format='commented', **{'lxc.rootfs': rootfs})
return name
return ''
def init(name,
config=None,
cpuset=None,
cpushare=None,
memory=None,
profile=None,
network_profile=None,
nic_opts=None,
cpu=None,
autostart=True,
password=None,
password_encrypted=None,
users=None,
dnsservers=None,
searchdomains=None,
bridge=None,
gateway=None,
pub_key=None,
priv_key=None,
force_install=False,
unconditional_install=False,
bootstrap_delay=None,
bootstrap_args=None,
bootstrap_shell=None,
bootstrap_url=None,
**kwargs):
'''
Initialize a new container.
This is a partial idempotent function as if it is already provisioned, we
will reset a bit the lxc configuration file but much of the hard work will
be escaped as markers will prevent re-execution of harmful tasks.
name
Name of the container
image
A tar archive to use as the rootfs for the container. Conflicts with
the ``template`` argument.
cpus
Select a random number of cpu cores and assign it to the cpuset, if the
cpuset option is set then this option will be ignored
cpuset
Explicitly define the cpus this container will be bound to
cpushare
cgroups cpu shares
autostart
autostart container on reboot
memory
cgroups memory limit, in MB
.. versionchanged:: 2015.5.0
If no value is passed, no limit is set. In earlier Salt versions,
not passing this value causes a 1024MB memory limit to be set, and
it was necessary to pass ``memory=0`` to set no limit.
gateway
the ipv4 gateway to use
the default does nothing more than lxcutils does
bridge
the bridge to use
the default does nothing more than lxcutils does
network_profile
Network profile to use for the container
.. versionadded:: 2015.5.0
nic_opts
Extra options for network interfaces, will override
``{"eth0": {"hwaddr": "aa:bb:cc:dd:ee:ff", "ipv4": "10.1.1.1", "ipv6": "2001:db8::ff00:42:8329"}}``
or
``{"eth0": {"hwaddr": "aa:bb:cc:dd:ee:ff", "ipv4": "10.1.1.1/24", "ipv6": "2001:db8::ff00:42:8329"}}``
users
Users for which the password defined in the ``password`` param should
be set. Can be passed as a comma separated list or a python list.
Defaults to just the ``root`` user.
password
Set the initial password for the users defined in the ``users``
parameter
password_encrypted : False
Set to ``True`` to denote a password hash instead of a plaintext
password
.. versionadded:: 2015.5.0
profile
A LXC profile (defined in config or pillar).
This can be either a real profile mapping or a string
to retrieve it in configuration
start
Start the newly-created container
dnsservers
list of dns servers to set in the container, default [] (no setting)
seed
Seed the container with the minion config. Default: ``True``
install
If salt-minion is not already installed, install it. Default: ``True``
config
Optional config parameters. By default, the id is set to
the name of the container.
master
salt master (default to minion's master)
master_port
salt master port (default to minion's master port)
pub_key
Explicit public key to preseed the minion with (optional).
This can be either a filepath or a string representing the key
priv_key
Explicit private key to preseed the minion with (optional).
This can be either a filepath or a string representing the key
approve_key
If explicit preseeding is not used;
Attempt to request key approval from the master. Default: ``True``
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
clone_from
Original from which to use a clone operation to create the container.
Default: ``None``
bootstrap_delay
Delay in seconds between end of container creation and bootstrapping.
Useful when waiting for container to obtain a DHCP lease.
.. versionadded:: 2015.5.0
bootstrap_url
See lxc.bootstrap
bootstrap_shell
See lxc.bootstrap
bootstrap_args
See lxc.bootstrap
force_install
Force installation even if salt-minion is detected,
this is the way to run vendor bootstrap scripts even
if a salt minion is already present in the container
unconditional_install
Run the script even if the container seems seeded
CLI Example:
.. code-block:: bash
salt 'minion' lxc.init name [cpuset=cgroups_cpuset] \\
[cpushare=cgroups_cpushare] [memory=cgroups_memory] \\
[nic=nic_profile] [profile=lxc_profile] \\
[nic_opts=nic_opts] [start=(True|False)] \\
[seed=(True|False)] [install=(True|False)] \\
[config=minion_config] [approve_key=(True|False) \\
[clone_from=original] [autostart=True] \\
[priv_key=/path_or_content] [pub_key=/path_or_content] \\
[bridge=lxcbr0] [gateway=10.0.3.1] \\
[dnsservers[dns1,dns2]] \\
[users=[foo]] [password='secret'] \\
[password_encrypted=(True|False)]
'''
ret = {'name': name,
'changes': {}}
profile = get_container_profile(copy.deepcopy(profile))
if not network_profile:
network_profile = profile.get('network_profile')
if not network_profile:
network_profile = DEFAULT_NIC
# Changes is a pointer to changes_dict['init']. This method is used so that
# we can have a list of changes as they are made, providing an ordered list
# of things that were changed.
changes_dict = {'init': []}
changes = changes_dict.get('init')
if users is None:
users = []
dusers = ['root']
for user in dusers:
if user not in users:
users.append(user)
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, _marker)
profile_match = profile.pop(key, default)
# let kwarg overrides be the preferred choice
if kw_overrides_match is _marker:
return profile_match
return kw_overrides_match
path = select('path')
bpath = get_root_path(path)
state_pre = state(name, path=path)
tvg = select('vgname')
vgname = tvg if tvg else __salt__['config.get']('lxc.vgname')
start_ = select('start', True)
autostart = select('autostart', autostart)
seed = select('seed', True)
install = select('install', True)
seed_cmd = select('seed_cmd')
salt_config = _get_salt_config(config, **kwargs)
approve_key = select('approve_key', True)
clone_from = select('clone_from')
# If using a volume group then set up to make snapshot cow clones
if vgname and not clone_from:
try:
kwargs['vgname'] = vgname
clone_from = _get_base(profile=profile, **kwargs)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = exc.strerror
if changes:
ret['changes'] = changes_dict
return ret
if not kwargs.get('snapshot') is False:
kwargs['snapshot'] = True
does_exist = exists(name, path=path)
to_reboot = False
remove_seed_marker = False
if does_exist:
pass
elif clone_from:
remove_seed_marker = True
try:
clone(name, clone_from, profile=profile, **kwargs)
changes.append({'create': 'Container cloned'})
except (SaltInvocationError, CommandExecutionError) as exc:
if 'already exists' in exc.strerror:
changes.append({'create': 'Container already exists'})
else:
ret['result'] = False
ret['comment'] = exc.strerror
if changes:
ret['changes'] = changes_dict
return ret
cfg = _LXCConfig(name=name, network_profile=network_profile,
nic_opts=nic_opts, bridge=bridge, path=path,
gateway=gateway, autostart=autostart,
cpuset=cpuset, cpushare=cpushare, memory=memory)
old_chunks = read_conf(cfg.path, out_format='commented')
cfg.write()
chunks = read_conf(cfg.path, out_format='commented')
if old_chunks != chunks:
to_reboot = True
else:
remove_seed_marker = True
cfg = _LXCConfig(network_profile=network_profile,
nic_opts=nic_opts, cpuset=cpuset, path=path,
bridge=bridge, gateway=gateway,
autostart=autostart,
cpushare=cpushare, memory=memory)
with cfg.tempfile() as cfile:
try:
create(name, config=cfile.name, profile=profile, **kwargs)
changes.append({'create': 'Container created'})
except (SaltInvocationError, CommandExecutionError) as exc:
if 'already exists' in exc.strerror:
changes.append({'create': 'Container already exists'})
else:
ret['comment'] = exc.strerror
if changes:
ret['changes'] = changes_dict
return ret
cpath = os.path.join(bpath, name, 'config')
old_chunks = []
if os.path.exists(cpath):
old_chunks = read_conf(cpath, out_format='commented')
new_cfg = _config_list(conf_tuples=old_chunks,
cpu=cpu,
network_profile=network_profile,
nic_opts=nic_opts, bridge=bridge,
cpuset=cpuset, cpushare=cpushare,
memory=memory)
if new_cfg:
edit_conf(cpath, out_format='commented', lxc_config=new_cfg)
chunks = read_conf(cpath, out_format='commented')
if old_chunks != chunks:
to_reboot = True
# last time to be sure any of our property is correctly applied
cfg = _LXCConfig(name=name, network_profile=network_profile,
nic_opts=nic_opts, bridge=bridge, path=path,
gateway=gateway, autostart=autostart,
cpuset=cpuset, cpushare=cpushare, memory=memory)
old_chunks = []
if os.path.exists(cfg.path):
old_chunks = read_conf(cfg.path, out_format='commented')
cfg.write()
chunks = read_conf(cfg.path, out_format='commented')
if old_chunks != chunks:
changes.append({'config': 'Container configuration updated'})
to_reboot = True
if to_reboot:
try:
stop(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
if changes:
ret['changes'] = changes_dict
return ret
if not does_exist or (does_exist and state(name, path=path) != 'running'):
try:
start(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
if changes:
ret['changes'] = changes_dict
return ret
if remove_seed_marker:
run(name,
'rm -f \'{0}\''.format(SEED_MARKER),
path=path,
chroot_fallback=False,
python_shell=False)
# set the default user/password, only the first time
if ret.get('result', True) and password:
gid = '/.lxc.initial_pass'
gids = [gid,
'/lxc.initial_pass',
'/.lxc.{0}.initial_pass'.format(name)]
if not any(retcode(name,
'test -e "{0}"'.format(x),
chroot_fallback=True,
path=path,
ignore_retcode=True) == 0
for x in gids):
# think to touch the default user generated by default templates
# which has a really unsecure passwords...
# root is defined as a member earlier in the code
for default_user in ['ubuntu']:
if (
default_user not in users and
retcode(name,
'id {0}'.format(default_user),
python_shell=False,
path=path,
chroot_fallback=True,
ignore_retcode=True) == 0
):
users.append(default_user)
for user in users:
try:
cret = set_password(name,
users=[user],
path=path,
password=password,
encrypted=password_encrypted)
except (SaltInvocationError, CommandExecutionError) as exc:
msg = '{0}: Failed to set password'.format(
user) + exc.strerror
# only hardfail in unrecoverable situation:
# root cannot be setted up
if user == 'root':
ret['comment'] = msg
ret['result'] = False
else:
log.debug(msg)
if ret.get('result', True):
changes.append({'password': 'Password(s) updated'})
if retcode(name,
('sh -c \'touch "{0}"; test -e "{0}"\''
.format(gid)),
path=path,
chroot_fallback=True,
ignore_retcode=True) != 0:
ret['comment'] = 'Failed to set password marker'
changes[-1]['password'] += '. ' + ret['comment'] + '.'
ret['result'] = False
# set dns servers if any, only the first time
if ret.get('result', True) and dnsservers:
# retro compatibility, test also old markers
gid = '/.lxc.initial_dns'
gids = [gid,
'/lxc.initial_dns',
'/lxc.{0}.initial_dns'.format(name)]
if not any(retcode(name,
'test -e "{0}"'.format(x),
chroot_fallback=True,
path=path,
ignore_retcode=True) == 0
for x in gids):
try:
set_dns(name,
path=path,
dnsservers=dnsservers,
searchdomains=searchdomains)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Failed to set DNS: ' + exc.strerror
ret['result'] = False
else:
changes.append({'dns': 'DNS updated'})
if retcode(name,
('sh -c \'touch "{0}"; test -e "{0}"\''
.format(gid)),
chroot_fallback=True,
path=path,
ignore_retcode=True) != 0:
ret['comment'] = 'Failed to set DNS marker'
changes[-1]['dns'] += '. ' + ret['comment'] + '.'
ret['result'] = False
# retro compatibility, test also old markers
if remove_seed_marker:
run(name,
'rm -f \'{0}\''.format(SEED_MARKER),
path=path,
python_shell=False)
gid = '/.lxc.initial_seed'
gids = [gid, '/lxc.initial_seed']
if (
any(retcode(name,
'test -e {0}'.format(x),
path=path,
chroot_fallback=True,
ignore_retcode=True) == 0
for x in gids) or not ret.get('result', True)
):
pass
elif seed or seed_cmd:
if seed:
try:
result = bootstrap(
name, config=salt_config, path=path,
approve_key=approve_key,
pub_key=pub_key, priv_key=priv_key,
install=install,
force_install=force_install,
unconditional_install=unconditional_install,
bootstrap_delay=bootstrap_delay,
bootstrap_url=bootstrap_url,
bootstrap_shell=bootstrap_shell,
bootstrap_args=bootstrap_args)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Bootstrap failed: ' + exc.strerror
ret['result'] = False
else:
if not result:
ret['comment'] = ('Bootstrap failed, see minion log for '
'more information')
ret['result'] = False
else:
changes.append(
{'bootstrap': 'Container successfully bootstrapped'}
)
elif seed_cmd:
try:
result = __salt__[seed_cmd](info(name, path=path)['rootfs'],
name,
salt_config)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = ('Bootstrap via seed_cmd \'{0}\' failed: {1}'
.format(seed_cmd, exc.strerror))
ret['result'] = False
else:
if not result:
ret['comment'] = ('Bootstrap via seed_cmd \'{0}\' failed, '
'see minion log for more information '
.format(seed_cmd))
ret['result'] = False
else:
changes.append(
{'bootstrap': 'Container successfully bootstrapped '
'using seed_cmd \'{0}\''
.format(seed_cmd)}
)
if ret.get('result', True) and not start_:
try:
stop(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
ret['result'] = False
state_post = state(name, path=path)
if state_pre != state_post:
changes.append({'state': {'old': state_pre, 'new': state_post}})
if ret.get('result', True):
ret['comment'] = ('Container \'{0}\' successfully initialized'
.format(name))
ret['result'] = True
if changes:
ret['changes'] = changes_dict
return ret
def cloud_init(name, vm_=None, **kwargs):
'''
Thin wrapper to lxc.init to be used from the saltcloud lxc driver
name
Name of the container
may be None and then guessed from saltcloud mapping
`vm_`
saltcloud mapping defaults for the vm
CLI Example:
.. code-block:: bash
salt '*' lxc.cloud_init foo
'''
init_interface = cloud_init_interface(name, vm_, **kwargs)
name = init_interface.pop('name', name)
return init(name, **init_interface)
def images(dist=None):
'''
.. versionadded:: 2015.5.0
List the available images for LXC's ``download`` template.
dist : None
Filter results to a single Linux distribution
CLI Examples:
.. code-block:: bash
salt myminion lxc.images
salt myminion lxc.images dist=centos
'''
out = __salt__['cmd.run_stdout'](
'lxc-create -n __imgcheck -t download -- --list',
ignore_retcode=True
)
if 'DIST' not in out:
raise CommandExecutionError(
'Unable to run the \'download\' template script. Is it installed?'
)
ret = {}
passed_header = False
for line in out.splitlines():
try:
distro, release, arch, variant, build_time = line.split()
except ValueError:
continue
if not passed_header:
if distro == 'DIST':
passed_header = True
continue
dist_list = ret.setdefault(distro, [])
dist_list.append({
'release': release,
'arch': arch,
'variant': variant,
'build_time': build_time,
})
if dist is not None:
return dict([(dist, ret.get(dist, []))])
return ret
def templates():
'''
.. versionadded:: 2015.5.0
List the available LXC template scripts installed on the minion
CLI Examples:
.. code-block:: bash
salt myminion lxc.templates
'''
try:
template_scripts = os.listdir('/usr/share/lxc/templates')
except OSError:
return []
else:
return [x[4:] for x in template_scripts if x.startswith('lxc-')]
def _after_ignition_network_profile(cmd,
ret,
name,
network_profile,
path,
nic_opts):
_clear_context()
if ret['retcode'] == 0 and exists(name, path=path):
if network_profile:
network_changes = apply_network_profile(name,
network_profile,
path=path,
nic_opts=nic_opts)
if network_changes:
log.info(
'Network changes from applying network profile \'%s\' '
'to newly-created container \'%s\':\n%s',
network_profile, name, network_changes
)
c_state = state(name, path=path)
return {'result': True,
'state': {'old': None, 'new': c_state}}
else:
if exists(name, path=path):
# destroy the container if it was partially created
cmd = 'lxc-destroy'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0}'.format(name)
__salt__['cmd.retcode'](cmd, python_shell=False)
raise CommandExecutionError(
'Container could not be created with cmd \'{0}\': {1}'
.format(cmd, ret['stderr'])
)
def create(name,
config=None,
profile=None,
network_profile=None,
nic_opts=None,
**kwargs):
'''
Create a new container.
name
Name of the container
config
The config file to use for the container. Defaults to system-wide
config (usually in /etc/lxc/lxc.conf).
profile
Profile to use in container creation (see
:mod:`lxc.get_container_profile
<salt.modules.lxc.get_container_profile>`). Values in a profile will be
overridden by the **Container Creation Arguments** listed below.
network_profile
Network profile to use for container
.. versionadded:: 2015.5.0
**Container Creation Arguments**
template
The template to use. For example, ``ubuntu`` or ``fedora``.
For a full list of available templates, check out
the :mod:`lxc.templates <salt.modules.lxc.templates>` function.
Conflicts with the ``image`` argument.
.. note::
The ``download`` template requires the following three parameters
to be defined in ``options``:
* **dist** - The name of the distribution
* **release** - Release name/version
* **arch** - Architecture of the container
The available images can be listed using the :mod:`lxc.images
<salt.modules.lxc.images>` function.
options
Template-specific options to pass to the lxc-create command. These
correspond to the long options (ones beginning with two dashes) that
the template script accepts. For example:
.. code-block:: bash
options='{"dist": "centos", "release": "6", "arch": "amd64"}'
For available template options, refer to the lxc template scripts
which are ususally located under ``/usr/share/lxc/templates``,
or run ``lxc-create -t <template> -h``.
image
A tar archive to use as the rootfs for the container. Conflicts with
the ``template`` argument.
backing
The type of storage to use. Set to ``lvm`` to use an LVM group.
Defaults to filesystem within /var/lib/lxc.
fstype
Filesystem type to use on LVM logical volume
size : 1G
Size of the volume to create. Only applicable if ``backing=lvm``.
vgname : lxc
Name of the LVM volume group in which to create the volume for this
container. Only applicable if ``backing=lvm``.
lvname
Name of the LVM logical volume in which to create the volume for this
container. Only applicable if ``backing=lvm``.
thinpool
Name of a pool volume that will be used for thin-provisioning this
container. Only applicable if ``backing=lvm``.
nic_opts
give extra opts overriding network profile values
path
parent path for the container creation (default: /var/lib/lxc)
zfsroot
Name of the ZFS root in which to create the volume for this container.
Only applicable if ``backing=zfs``. (default: tank/lxc)
.. versionadded:: 2015.8.0
'''
# Required params for 'download' template
download_template_deps = ('dist', 'release', 'arch')
cmd = 'lxc-create -n {0}'.format(name)
profile = get_container_profile(copy.deepcopy(profile))
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, None)
profile_match = profile.pop(key, default)
# Return the profile match if the the kwarg match was None, as the
# lxc.present state will pass these kwargs set to None by default.
if kw_overrides_match is None:
return profile_match
return kw_overrides_match
path = select('path')
if exists(name, path=path):
raise CommandExecutionError(
'Container \'{0}\' already exists'.format(name)
)
tvg = select('vgname')
vgname = tvg if tvg else __salt__['config.get']('lxc.vgname')
# The 'template' and 'image' params conflict
template = select('template')
image = select('image')
if template and image:
raise SaltInvocationError(
'Only one of \'template\' and \'image\' is permitted'
)
elif not any((template, image, profile)):
raise SaltInvocationError(
'At least one of \'template\', \'image\', and \'profile\' is '
'required'
)
options = select('options') or {}
backing = select('backing')
if vgname and not backing:
backing = 'lvm'
lvname = select('lvname')
thinpool = select('thinpool')
fstype = select('fstype')
size = select('size', '1G')
zfsroot = select('zfsroot')
if backing in ('dir', 'overlayfs', 'btrfs', 'zfs'):
fstype = None
size = None
# some backends won't support some parameters
if backing in ('aufs', 'dir', 'overlayfs', 'btrfs'):
lvname = vgname = thinpool = None
if image:
img_tar = __salt__['cp.cache_file'](image)
template = os.path.join(
os.path.dirname(salt.__file__),
'templates',
'lxc',
'salt_tarball')
options['imgtar'] = img_tar
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
if not os.path.exists(path):
os.makedirs(path)
if config:
cmd += ' -f {0}'.format(config)
if template:
cmd += ' -t {0}'.format(template)
if backing:
backing = backing.lower()
cmd += ' -B {0}'.format(backing)
if backing in ('zfs',):
if zfsroot:
cmd += ' --zfsroot {0}'.format(zfsroot)
if backing in ('lvm',):
if lvname:
cmd += ' --lvname {0}'.format(lvname)
if vgname:
cmd += ' --vgname {0}'.format(vgname)
if thinpool:
cmd += ' --thinpool {0}'.format(thinpool)
if backing not in ('dir', 'overlayfs'):
if fstype:
cmd += ' --fstype {0}'.format(fstype)
if size:
cmd += ' --fssize {0}'.format(size)
if options:
if template == 'download':
missing_deps = [x for x in download_template_deps
if x not in options]
if missing_deps:
raise SaltInvocationError(
'Missing params in \'options\' dict: {0}'
.format(', '.join(missing_deps))
)
cmd += ' --'
for key, val in six.iteritems(options):
cmd += ' --{0} {1}'.format(key, val)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
# please do not merge extra conflicting stuff
# inside those two line (ret =, return)
return _after_ignition_network_profile(cmd,
ret,
name,
network_profile,
path,
nic_opts)
def clone(name,
orig,
profile=None,
network_profile=None,
nic_opts=None,
**kwargs):
'''
Create a new container as a clone of another container
name
Name of the container
orig
Name of the original container to be cloned
profile
Profile to use in container cloning (see
:mod:`lxc.get_container_profile
<salt.modules.lxc.get_container_profile>`). Values in a profile will be
overridden by the **Container Cloning Arguments** listed below.
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
**Container Cloning Arguments**
snapshot
Use Copy On Write snapshots (LVM)
size : 1G
Size of the volume to create. Only applicable if ``backing=lvm``.
backing
The type of storage to use. Set to ``lvm`` to use an LVM group.
Defaults to filesystem within /var/lib/lxc.
network_profile
Network profile to use for container
.. versionadded:: 2015.8.0
nic_opts
give extra opts overriding network profile values
.. versionadded:: 2015.8.0
CLI Examples:
.. code-block:: bash
salt '*' lxc.clone myclone orig=orig_container
salt '*' lxc.clone myclone orig=orig_container snapshot=True
'''
profile = get_container_profile(copy.deepcopy(profile))
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, None)
profile_match = profile.pop(key, default)
# let kwarg overrides be the preferred choice
if kw_overrides_match is None:
return profile_match
return kw_overrides_match
path = select('path')
if exists(name, path=path):
raise CommandExecutionError(
'Container \'{0}\' already exists'.format(name)
)
_ensure_exists(orig, path=path)
if state(orig, path=path) != 'stopped':
raise CommandExecutionError(
'Container \'{0}\' must be stopped to be cloned'.format(orig)
)
backing = select('backing')
snapshot = select('snapshot')
if backing in ('dir',):
snapshot = False
if not snapshot:
snapshot = ''
else:
snapshot = '-s'
size = select('size', '1G')
if backing in ('dir', 'overlayfs', 'btrfs'):
size = None
# LXC commands and options changed in 2.0 - CF issue #34086 for details
if _LooseVersion(version()) >= _LooseVersion('2.0'):
# https://linuxcontainers.org/lxc/manpages//man1/lxc-copy.1.html
cmd = 'lxc-copy'
cmd += ' {0} -n {1} -N {2}'.format(snapshot, orig, name)
else:
# https://linuxcontainers.org/lxc/manpages//man1/lxc-clone.1.html
cmd = 'lxc-clone'
cmd += ' {0} -o {1} -n {2}'.format(snapshot, orig, name)
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
if not os.path.exists(path):
os.makedirs(path)
if backing:
backing = backing.lower()
cmd += ' -B {0}'.format(backing)
if backing not in ('dir', 'overlayfs'):
if size:
cmd += ' -L {0}'.format(size)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
# please do not merge extra conflicting stuff
# inside those two line (ret =, return)
return _after_ignition_network_profile(cmd,
ret,
name,
network_profile,
path,
nic_opts)
def ls_(active=None, cache=True, path=None):
'''
Return a list of the containers available on the minion
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
active
If ``True``, return only active (i.e. running) containers
.. versionadded:: 2015.5.0
CLI Example:
.. code-block:: bash
salt '*' lxc.ls
salt '*' lxc.ls active=True
'''
contextvar = 'lxc.ls{0}'.format(path)
if active:
contextvar += '.active'
if cache and (contextvar in __context__):
return __context__[contextvar]
else:
ret = []
cmd = 'lxc-ls'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
if active:
cmd += ' --active'
output = __salt__['cmd.run_stdout'](cmd, python_shell=False)
for line in output.splitlines():
ret.extend(line.split())
__context__[contextvar] = ret
return ret
def list_(extra=False, limit=None, path=None):
'''
List containers classified by state
extra
Also get per-container specific info. This will change the return data.
Instead of returning a list of containers, a dictionary of containers
and each container's output from :mod:`lxc.info
<salt.modules.lxc.info>`.
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
limit
Return output matching a specific state (**frozen**, **running**, or
**stopped**).
.. versionadded:: 2015.5.0
CLI Examples:
.. code-block:: bash
salt '*' lxc.list
salt '*' lxc.list extra=True
salt '*' lxc.list limit=running
'''
ctnrs = ls_(path=path)
if extra:
stopped = {}
frozen = {}
running = {}
else:
stopped = []
frozen = []
running = []
ret = {'running': running,
'stopped': stopped,
'frozen': frozen}
for container in ctnrs:
cmd = 'lxc-info'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0}'.format(container)
c_info = __salt__['cmd.run'](
cmd,
python_shell=False,
output_loglevel='debug'
)
c_state = None
for line in c_info.splitlines():
stat = line.split(':')
if stat[0] in ('State', 'state'):
c_state = stat[1].strip()
break
if not c_state or (limit is not None and c_state.lower() != limit):
continue
if extra:
infos = info(container, path=path)
method = 'update'
value = {container: infos}
else:
method = 'append'
value = container
if c_state == 'STOPPED':
getattr(stopped, method)(value)
continue
if c_state == 'FROZEN':
getattr(frozen, method)(value)
continue
if c_state == 'RUNNING':
getattr(running, method)(value)
continue
if limit is not None:
return ret.get(limit, {} if extra else [])
return ret
def _change_state(cmd,
name,
expected,
stdin=_marker,
stdout=_marker,
stderr=_marker,
with_communicate=_marker,
use_vt=_marker,
path=None):
pre = state(name, path=path)
if pre == expected:
return {'result': True,
'state': {'old': expected, 'new': expected},
'comment': 'Container \'{0}\' already {1}'
.format(name, expected)}
if cmd == 'lxc-destroy':
# Kill the container first
scmd = 'lxc-stop'
if path:
scmd += ' -P {0}'.format(pipes.quote(path))
scmd += ' -k -n {0}'.format(name)
__salt__['cmd.run'](scmd,
python_shell=False)
if path and ' -P ' not in cmd:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0}'.format(name)
# certain lxc commands need to be taken with care (lxc-start)
# as te command itself mess with double forks; we must not
# communicate with it, but just wait for the exit status
pkwargs = {'python_shell': False,
'redirect_stderr': True,
'with_communicate': with_communicate,
'use_vt': use_vt,
'stdin': stdin,
'stdout': stdout}
for i in [a for a in pkwargs]:
val = pkwargs[i]
if val is _marker:
pkwargs.pop(i, None)
_cmdout = __salt__['cmd.run_all'](cmd, **pkwargs)
if _cmdout['retcode'] != 0:
raise CommandExecutionError(
'Error changing state for container \'{0}\' using command '
'\'{1}\': {2}'.format(name, cmd, _cmdout['stdout'])
)
if expected is not None:
# some commands do not wait, so we will
rcmd = 'lxc-wait'
if path:
rcmd += ' -P {0}'.format(pipes.quote(path))
rcmd += ' -n {0} -s {1}'.format(name, expected.upper())
__salt__['cmd.run'](rcmd, python_shell=False, timeout=30)
_clear_context()
post = state(name, path=path)
ret = {'result': post == expected,
'state': {'old': pre, 'new': post}}
return ret
def _ensure_exists(name, path=None):
'''
Raise an exception if the container does not exist
'''
if not exists(name, path=path):
raise CommandExecutionError(
'Container \'{0}\' does not exist'.format(name)
)
def _ensure_running(name, no_start=False, path=None):
'''
If the container is not currently running, start it. This function returns
the state that the container was in before changing
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
'''
_ensure_exists(name, path=path)
pre = state(name, path=path)
if pre == 'running':
# This will be a no-op but running the function will give us a pretty
# return dict.
return start(name, path=path)
elif pre == 'stopped':
if no_start:
raise CommandExecutionError(
'Container \'{0}\' is not running'.format(name)
)
return start(name, path=path)
elif pre == 'frozen':
if no_start:
raise CommandExecutionError(
'Container \'{0}\' is not running'.format(name)
)
return unfreeze(name, path=path)
def restart(name, path=None, lxc_config=None, force=False):
'''
.. versionadded:: 2015.5.0
Restart the named container. If the container was not running, the
container will merely be started.
name
The name of the container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
lxc_config
path to a lxc config file
config file will be guessed from container name otherwise
.. versionadded:: 2015.8.0
force : False
If ``True``, the container will be force-stopped instead of gracefully
shut down
CLI Example:
.. code-block:: bash
salt myminion lxc.restart name
'''
_ensure_exists(name, path=path)
orig_state = state(name, path=path)
if orig_state != 'stopped':
stop(name, kill=force, path=path)
ret = start(name, path=path, lxc_config=lxc_config)
ret['state']['old'] = orig_state
if orig_state != 'stopped':
ret['restarted'] = True
return ret
def start(name, **kwargs):
'''
Start the named container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
lxc_config
path to a lxc config file
config file will be guessed from container name otherwise
.. versionadded:: 2015.8.0
use_vt
run the command through VT
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.start name
'''
path = kwargs.get('path', None)
cpath = get_root_path(path)
lxc_config = kwargs.get('lxc_config', None)
cmd = 'lxc-start'
if not lxc_config:
lxc_config = os.path.join(cpath, name, 'config')
# we try to start, even without config, if global opts are there
if os.path.exists(lxc_config):
cmd += ' -f {0}'.format(pipes.quote(lxc_config))
cmd += ' -d'
_ensure_exists(name, path=path)
if state(name, path=path) == 'frozen':
raise CommandExecutionError(
'Container \'{0}\' is frozen, use lxc.unfreeze'.format(name)
)
# lxc-start daemonize itself violently, we must not communicate with it
use_vt = kwargs.get('use_vt', None)
with_communicate = kwargs.get('with_communicate', False)
return _change_state(cmd, name, 'running',
stdout=None,
stderr=None,
stdin=None,
with_communicate=with_communicate,
path=path,
use_vt=use_vt)
def freeze(name, **kwargs):
'''
Freeze the named container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
start : False
If ``True`` and the container is stopped, the container will be started
before attempting to freeze.
.. versionadded:: 2015.5.0
use_vt
run the command through VT
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.freeze name
'''
use_vt = kwargs.get('use_vt', None)
path = kwargs.get('path', None)
_ensure_exists(name, path=path)
orig_state = state(name, path=path)
start_ = kwargs.get('start', False)
if orig_state == 'stopped':
if not start_:
raise CommandExecutionError(
'Container \'{0}\' is stopped'.format(name)
)
start(name, path=path)
cmd = 'lxc-freeze'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
ret = _change_state(cmd, name, 'frozen', use_vt=use_vt, path=path)
if orig_state == 'stopped' and start_:
ret['state']['old'] = orig_state
ret['started'] = True
ret['state']['new'] = state(name, path=path)
return ret
def unfreeze(name, path=None, use_vt=None):
'''
Unfreeze the named container.
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
use_vt
run the command through VT
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.unfreeze name
'''
_ensure_exists(name, path=path)
if state(name, path=path) == 'stopped':
raise CommandExecutionError(
'Container \'{0}\' is stopped'.format(name)
)
cmd = 'lxc-unfreeze'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
return _change_state(cmd, name, 'running', path=path, use_vt=use_vt)
def destroy(name, stop=False, path=None):
'''
Destroy the named container.
.. warning::
Destroys all data associated with the container.
path
path to the container parent directory (default: /var/lib/lxc)
.. versionadded:: 2015.8.0
stop : False
If ``True``, the container will be destroyed even if it is
running/frozen.
.. versionchanged:: 2015.5.0
Default value changed to ``False``. This more closely matches the
behavior of ``lxc-destroy(1)``, and also makes it less likely that
an accidental command will destroy a running container that was
being used for important things.
CLI Examples:
.. code-block:: bash
salt '*' lxc.destroy foo
salt '*' lxc.destroy foo stop=True
'''
_ensure_exists(name, path=path)
if not stop and state(name, path=path) != 'stopped':
raise CommandExecutionError(
'Container \'{0}\' is not stopped'.format(name)
)
return _change_state('lxc-destroy', name, None, path=path)
# Compatibility between LXC and nspawn
remove = salt.utils.functools.alias_function(destroy, 'remove')
def exists(name, path=None):
'''
Returns whether the named container exists.
path
path to the container parent directory (default: /var/lib/lxc)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.exists name
'''
_exists = name in ls_(path=path)
# container may be just created but we did cached earlier the
# lxc-ls results
if not _exists:
_exists = name in ls_(cache=False, path=path)
return _exists
def state(name, path=None):
'''
Returns the state of a container.
path
path to the container parent directory (default: /var/lib/lxc)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.state name
'''
# Don't use _ensure_exists() here, it will mess with _change_state()
cachekey = 'lxc.state.{0}{1}'.format(name, path)
try:
return __context__[cachekey]
except KeyError:
if not exists(name, path=path):
__context__[cachekey] = None
else:
cmd = 'lxc-info'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0}'.format(name)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
if ret['retcode'] != 0:
_clear_context()
raise CommandExecutionError(
'Unable to get state of container \'{0}\''.format(name)
)
c_infos = ret['stdout'].splitlines()
c_state = None
for c_info in c_infos:
stat = c_info.split(':')
if stat[0].lower() == 'state':
c_state = stat[1].strip().lower()
break
__context__[cachekey] = c_state
return __context__[cachekey]
def get_parameter(name, parameter, path=None):
'''
Returns the value of a cgroup parameter for a container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.get_parameter container_name memory.limit_in_bytes
'''
_ensure_exists(name, path=path)
cmd = 'lxc-cgroup'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0} {1}'.format(name, parameter)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
if ret['retcode'] != 0:
raise CommandExecutionError(
'Unable to retrieve value for \'{0}\''.format(parameter)
)
return ret['stdout'].strip()
def set_parameter(name, parameter, value, path=None):
'''
Set the value of a cgroup parameter for a container.
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.set_parameter name parameter value
'''
if not exists(name, path=path):
return None
cmd = 'lxc-cgroup'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0} {1} {2}'.format(name, parameter, value)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
if ret['retcode'] != 0:
return False
else:
return True
def info(name, path=None):
'''
Returns information about a container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.info name
'''
cachekey = 'lxc.info.{0}{1}'.format(name, path)
try:
return __context__[cachekey]
except KeyError:
_ensure_exists(name, path=path)
cpath = get_root_path(path)
try:
conf_file = os.path.join(cpath, name, 'config')
except AttributeError:
conf_file = os.path.join(cpath, six.text_type(name), 'config')
if not os.path.isfile(conf_file):
raise CommandExecutionError(
'LXC config file {0} does not exist'.format(conf_file)
)
ret = {}
config = []
with salt.utils.files.fopen(conf_file) as fp_:
for line in fp_:
line = salt.utils.stringutils.to_unicode(line)
comps = [x.strip() for x in
line.split('#', 1)[0].strip().split('=', 1)]
if len(comps) == 2:
config.append(tuple(comps))
ifaces = []
current = None
for key, val in config:
if key == 'lxc.network.type':
current = {'type': val}
ifaces.append(current)
elif not current:
continue
elif key.startswith('lxc.network.'):
current[key.replace('lxc.network.', '', 1)] = val
if ifaces:
ret['nics'] = ifaces
ret['rootfs'] = next(
(x[1] for x in config if x[0] == 'lxc.rootfs'),
None
)
ret['state'] = state(name, path=path)
ret['ips'] = []
ret['public_ips'] = []
ret['private_ips'] = []
ret['public_ipv4_ips'] = []
ret['public_ipv6_ips'] = []
ret['private_ipv4_ips'] = []
ret['private_ipv6_ips'] = []
ret['ipv4_ips'] = []
ret['ipv6_ips'] = []
ret['size'] = None
ret['config'] = conf_file
if ret['state'] == 'running':
try:
limit = int(get_parameter(name, 'memory.limit_in_bytes'))
except (CommandExecutionError, TypeError, ValueError):
limit = 0
try:
usage = int(get_parameter(name, 'memory.usage_in_bytes'))
except (CommandExecutionError, TypeError, ValueError):
usage = 0
free = limit - usage
ret['memory_limit'] = limit
ret['memory_free'] = free
size = run_stdout(name, 'df /', path=path, python_shell=False)
# The size is the 2nd column of the last line
ret['size'] = size.splitlines()[-1].split()[1]
# First try iproute2
ip_cmd = run_all(
name, 'ip link show', path=path, python_shell=False)
if ip_cmd['retcode'] == 0:
ip_data = ip_cmd['stdout']
ip_cmd = run_all(
name, 'ip addr show', path=path, python_shell=False)
ip_data += '\n' + ip_cmd['stdout']
ip_data = salt.utils.network._interfaces_ip(ip_data)
else:
# That didn't work, try ifconfig
ip_cmd = run_all(
name, 'ifconfig', path=path, python_shell=False)
if ip_cmd['retcode'] == 0:
ip_data = \
salt.utils.network._interfaces_ifconfig(
ip_cmd['stdout'])
else:
# Neither was successful, give up
log.warning(
'Unable to run ip or ifconfig in container \'%s\'', name
)
ip_data = {}
ret['ipv4_ips'] = salt.utils.network.ip_addrs(
include_loopback=True,
interface_data=ip_data
)
ret['ipv6_ips'] = salt.utils.network.ip_addrs6(
include_loopback=True,
interface_data=ip_data
)
ret['ips'] = ret['ipv4_ips'] + ret['ipv6_ips']
for address in ret['ipv4_ips']:
if address == '127.0.0.1':
ret['private_ips'].append(address)
ret['private_ipv4_ips'].append(address)
elif salt.utils.cloud.is_public_ip(address):
ret['public_ips'].append(address)
ret['public_ipv4_ips'].append(address)
else:
ret['private_ips'].append(address)
ret['private_ipv4_ips'].append(address)
for address in ret['ipv6_ips']:
if address == '::1' or address.startswith('fe80'):
ret['private_ips'].append(address)
ret['private_ipv6_ips'].append(address)
else:
ret['public_ips'].append(address)
ret['public_ipv6_ips'].append(address)
for key in [x for x in ret if x == 'ips' or x.endswith('ips')]:
ret[key].sort(key=_ip_sort)
__context__[cachekey] = ret
return __context__[cachekey]
def set_password(name, users, password, encrypted=True, path=None):
'''
.. versionchanged:: 2015.5.0
Function renamed from ``set_pass`` to ``set_password``. Additionally,
this function now supports (and defaults to using) a password hash
instead of a plaintext password.
Set the password of one or more system users inside containers
users
Comma-separated list (or python list) of users to change password
password
Password to set for the specified user(s)
encrypted : True
If true, ``password`` must be a password hash. Set to ``False`` to set
a plaintext password (not recommended).
.. versionadded:: 2015.5.0
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.set_pass container-name root '$6$uJ2uAyLU$KoI67t8As/0fXtJOPcHKGXmUpcoYUcVR2K6x93walnShTCQvjRwq25yIkiCBOqgbfdKQSFnAo28/ek6716vEV1'
salt '*' lxc.set_pass container-name root foo encrypted=False
'''
def _bad_user_input():
raise SaltInvocationError('Invalid input for \'users\' parameter')
if not isinstance(users, list):
try:
users = users.split(',')
except AttributeError:
_bad_user_input()
if not users:
_bad_user_input()
failed_users = []
for user in users:
result = retcode(name,
'chpasswd{0}'.format(' -e' if encrypted else ''),
stdin=':'.join((user, password)),
python_shell=False,
path=path,
chroot_fallback=True,
output_loglevel='quiet')
if result != 0:
failed_users.append(user)
if failed_users:
raise CommandExecutionError(
'Password change failed for the following user(s): {0}'
.format(', '.join(failed_users))
)
return True
set_pass = salt.utils.functools.alias_function(set_password, 'set_pass')
def update_lxc_conf(name, lxc_conf, lxc_conf_unset, path=None):
'''
Edit LXC configuration options
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.update_lxc_conf ubuntu \\
lxc_conf="[{'network.ipv4.ip':'10.0.3.5'}]" \\
lxc_conf_unset="['lxc.utsname']"
'''
_ensure_exists(name, path=path)
cpath = get_root_path(path)
lxc_conf_p = os.path.join(cpath, name, 'config')
if not os.path.exists(lxc_conf_p):
raise SaltInvocationError(
'Configuration file {0} does not exist'.format(lxc_conf_p)
)
changes = {'edited': [], 'added': [], 'removed': []}
ret = {'changes': changes, 'result': True, 'comment': ''}
# do not use salt.utils.files.fopen !
with salt.utils.files.fopen(lxc_conf_p, 'r') as fic:
filtered_lxc_conf = []
for row in lxc_conf:
if not row:
continue
for conf in row:
filtered_lxc_conf.append((conf.strip(),
row[conf].strip()))
ret['comment'] = 'lxc.conf is up to date'
lines = []
orig_config = salt.utils.stringutils.to_unicode(fic.read())
for line in orig_config.splitlines():
if line.startswith('#') or not line.strip():
lines.append([line, ''])
else:
line = line.split('=')
index = line.pop(0)
val = (index.strip(), '='.join(line).strip())
if val not in lines:
lines.append(val)
for key, item in filtered_lxc_conf:
matched = False
for idx, line in enumerate(lines[:]):
if line[0] == key:
matched = True
lines[idx] = (key, item)
if '='.join(line[1:]).strip() != item.strip():
changes['edited'].append(
({line[0]: line[1:]}, {key: item}))
break
if not matched:
if (key, item) not in lines:
lines.append((key, item))
changes['added'].append({key: item})
dest_lxc_conf = []
# filter unset
if lxc_conf_unset:
for line in lines:
for opt in lxc_conf_unset:
if (
not line[0].startswith(opt) and
line not in dest_lxc_conf
):
dest_lxc_conf.append(line)
else:
changes['removed'].append(opt)
else:
dest_lxc_conf = lines
conf = ''
for key, val in dest_lxc_conf:
if not val:
conf += '{0}\n'.format(key)
else:
conf += '{0} = {1}\n'.format(key.strip(), val.strip())
conf_changed = conf != orig_config
chrono = datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S')
if conf_changed:
# DO NOT USE salt.utils.files.fopen here, i got (kiorky)
# problems with lxc configs which were wiped !
with salt.utils.files.fopen('{0}.{1}'.format(lxc_conf_p, chrono), 'w') as wfic:
wfic.write(salt.utils.stringutils.to_str(conf))
with salt.utils.files.fopen(lxc_conf_p, 'w') as wfic:
wfic.write(salt.utils.stringutils.to_str(conf))
ret['comment'] = 'Updated'
ret['result'] = True
if not any(changes[x] for x in changes):
# Ensure an empty changes dict if nothing was modified
ret['changes'] = {}
return ret
def set_dns(name, dnsservers=None, searchdomains=None, path=None):
'''
.. versionchanged:: 2015.5.0
The ``dnsservers`` and ``searchdomains`` parameters can now be passed
as a comma-separated list.
Update /etc/resolv.confo
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.set_dns ubuntu "['8.8.8.8', '4.4.4.4']"
'''
if dnsservers is None:
dnsservers = ['8.8.8.8', '4.4.4.4']
elif not isinstance(dnsservers, list):
try:
dnsservers = dnsservers.split(',')
except AttributeError:
raise SaltInvocationError(
'Invalid input for \'dnsservers\' parameter'
)
if searchdomains is None:
searchdomains = []
elif not isinstance(searchdomains, list):
try:
searchdomains = searchdomains.split(',')
except AttributeError:
raise SaltInvocationError(
'Invalid input for \'searchdomains\' parameter'
)
dns = ['nameserver {0}'.format(x) for x in dnsservers]
dns.extend(['search {0}'.format(x) for x in searchdomains])
dns = '\n'.join(dns) + '\n'
# we may be using resolvconf in the container
# We need to handle that case with care:
# - we create the resolv.conf runtime directory (the
# linked directory) as anyway it will be shadowed when the real
# runned tmpfs mountpoint will be mounted.
# ( /etc/resolv.conf -> ../run/resolvconf/resolv.conf)
# Indeed, it can save us in any other case (running, eg, in a
# bare chroot when repairing or preparing the container for
# operation.
# - We also teach resolvconf to use the aforementioned dns.
# - We finally also set /etc/resolv.conf in all cases
rstr = __salt__['test.random_hash']()
# no tmp here, apparmor won't let us execute !
script = '/sbin/{0}_dns.sh'.format(rstr)
DNS_SCRIPT = "\n".join([
# 'set -x',
'#!/usr/bin/env bash',
'if [ -h /etc/resolv.conf ];then',
' if [ "x$(readlink /etc/resolv.conf)"'
' = "x../run/resolvconf/resolv.conf" ];then',
' if [ ! -d /run/resolvconf/ ];then',
' mkdir -p /run/resolvconf',
' fi',
' cat > /etc/resolvconf/resolv.conf.d/head <<EOF',
dns,
'EOF',
'',
' fi',
'fi',
'cat > /etc/resolv.conf <<EOF',
dns,
'EOF',
''])
result = run_all(
name, 'tee {0}'.format(script), path=path,
stdin=DNS_SCRIPT, python_shell=True)
if result['retcode'] == 0:
result = run_all(
name, 'sh -c "chmod +x {0};{0}"'.format(script),
path=path, python_shell=True)
# blindly delete the setter file
run_all(name,
'sh -c \'if [ -f "{0}" ];then rm -f "{0}";fi\''.format(script),
path=path, python_shell=True)
if result['retcode'] != 0:
error = ('Unable to write to /etc/resolv.conf in container \'{0}\''
.format(name))
if result['stderr']:
error += ': {0}'.format(result['stderr'])
raise CommandExecutionError(error)
return True
def running_systemd(name, cache=True, path=None):
'''
Determine if systemD is running
path
path to the container parent
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.running_systemd ubuntu
'''
k = 'lxc.systemd.test.{0}{1}'.format(name, path)
ret = __context__.get(k, None)
if ret is None or not cache:
rstr = __salt__['test.random_hash']()
# no tmp here, apparmor won't let us execute !
script = '/sbin/{0}_testsystemd.sh'.format(rstr)
# ubuntu already had since trusty some bits of systemd but was
# still using upstart ...
# we need to be a bit more careful that just testing that systemd
# is present
_script = textwrap.dedent(
'''\
#!/usr/bin/env bash
set -x
if ! command -v systemctl 1>/dev/null 2>/dev/null;then exit 2;fi
for i in \\
/run/systemd/journal/dev-log\\
/run/systemd/journal/flushed\\
/run/systemd/journal/kernel-seqnum\\
/run/systemd/journal/socket\\
/run/systemd/journal/stdout\\
/var/run/systemd/journal/dev-log\\
/var/run/systemd/journal/flushed\\
/var/run/systemd/journal/kernel-seqnum\\
/var/run/systemd/journal/socket\\
/var/run/systemd/journal/stdout\\
;do\\
if test -e ${i};then exit 0;fi
done
if test -d /var/systemd/system;then exit 0;fi
exit 2
''')
result = run_all(
name, 'tee {0}'.format(script), path=path,
stdin=_script, python_shell=True)
if result['retcode'] == 0:
result = run_all(name,
'sh -c "chmod +x {0};{0}"'''.format(script),
path=path,
python_shell=True)
else:
raise CommandExecutionError(
'lxc {0} failed to copy initd tester'.format(name))
run_all(name,
'sh -c \'if [ -f "{0}" ];then rm -f "{0}";fi\''
''.format(script),
path=path,
ignore_retcode=True,
python_shell=True)
if result['retcode'] != 0:
error = ('Unable to determine if the container \'{0}\''
' was running systemd, assmuming it is not.'
''.format(name))
if result['stderr']:
error += ': {0}'.format(result['stderr'])
# only cache result if we got a known exit code
if result['retcode'] in (0, 2):
__context__[k] = ret = not result['retcode']
return ret
def systemd_running_state(name, path=None):
'''
Get the operational state of a systemd based container
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.systemd_running_state ubuntu
'''
try:
ret = run_all(name,
'systemctl is-system-running',
path=path,
ignore_retcode=True)['stdout']
except CommandExecutionError:
ret = ''
return ret
def test_sd_started_state(name, path=None):
'''
Test if a systemd container is fully started
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.test_sd_started_state ubuntu
'''
qstate = systemd_running_state(name, path=path)
if qstate in ('initializing', 'starting'):
return False
elif qstate == '':
return None
else:
return True
def test_bare_started_state(name, path=None):
'''
Test if a non systemd container is fully started
For now, it consists only to test if the container is attachable
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.test_bare_started_state ubuntu
'''
try:
ret = run_all(
name, 'ls', path=path, ignore_retcode=True
)['retcode'] == 0
except (CommandExecutionError,):
ret = None
return ret
def wait_started(name, path=None, timeout=300):
'''
Check that the system has fully inited
This is actually very important for systemD based containers
see https://github.com/saltstack/salt/issues/23847
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.wait_started ubuntu
'''
if not exists(name, path=path):
raise CommandExecutionError(
'Container {0} does does exists'.format(name))
if not state(name, path=path) == 'running':
raise CommandExecutionError(
'Container {0} is not running'.format(name))
ret = False
if running_systemd(name, path=path):
test_started = test_sd_started_state
logger = log.error
else:
test_started = test_bare_started_state
logger = log.debug
now = time.time()
expire = now + timeout
now = time.time()
started = test_started(name, path=path)
while time.time() < expire and not started:
time.sleep(0.3)
started = test_started(name, path=path)
if started is None:
logger(
'Assuming %s is started, although we failed to detect that'
' is fully started correctly', name)
ret = True
else:
ret = started
return ret
def _needs_install(name, path=None):
ret = 0
has_minion = retcode(name,
'which salt-minion',
path=path,
ignore_retcode=True)
# we assume that installing is when no minion is running
# but testing the executable presence is not enougth for custom
# installs where the bootstrap can do much more than installing
# the bare salt binaries.
if has_minion:
processes = run_stdout(name, "ps aux", path=path)
if 'salt-minion' not in processes:
ret = 1
else:
retcode(name, 'salt-call --local service.stop salt-minion')
else:
ret = 1
return ret
def bootstrap(name,
config=None,
approve_key=True,
install=True,
pub_key=None,
priv_key=None,
bootstrap_url=None,
force_install=False,
unconditional_install=False,
path=None,
bootstrap_delay=None,
bootstrap_args=None,
bootstrap_shell=None):
'''
Install and configure salt in a container.
config
Minion configuration options. By default, the ``master`` option is set
to the target host's master.
approve_key
Request a pre-approval of the generated minion key. Requires
that the salt-master be configured to either auto-accept all keys or
expect a signing request from the target host. Default: ``True``
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
pub_key
Explicit public key to pressed the minion with (optional).
This can be either a filepath or a string representing the key
priv_key
Explicit private key to pressed the minion with (optional).
This can be either a filepath or a string representing the key
bootstrap_delay
Delay in seconds between end of container creation and bootstrapping.
Useful when waiting for container to obtain a DHCP lease.
.. versionadded:: 2015.5.0
bootstrap_url
url, content or filepath to the salt bootstrap script
bootstrap_args
salt bootstrap script arguments
bootstrap_shell
shell to execute the script into
install
Whether to attempt a full installation of salt-minion if needed.
force_install
Force installation even if salt-minion is detected,
this is the way to run vendor bootstrap scripts even
if a salt minion is already present in the container
unconditional_install
Run the script even if the container seems seeded
CLI Examples:
.. code-block:: bash
salt 'minion' lxc.bootstrap container_name [config=config_data] \\
[approve_key=(True|False)] [install=(True|False)]
'''
wait_started(name, path=path)
if bootstrap_delay is not None:
try:
log.info('LXC %s: bootstrap_delay: %s', name, bootstrap_delay)
time.sleep(bootstrap_delay)
except TypeError:
# Bad input, but assume since a value was passed that
# a delay was desired, and sleep for 5 seconds
time.sleep(5)
c_info = info(name, path=path)
if not c_info:
return None
# default set here as we cannot set them
# in def as it can come from a chain of procedures.
if bootstrap_args:
# custom bootstrap args can be totally customized, and user could
# have inserted the placeholder for the config directory.
# For example, some salt bootstrap script do not use at all -c
if '{0}' not in bootstrap_args:
bootstrap_args += ' -c {0}'
else:
bootstrap_args = '-c {0}'
if not bootstrap_shell:
bootstrap_shell = 'sh'
orig_state = _ensure_running(name, path=path)
if not orig_state:
return orig_state
if not force_install:
needs_install = _needs_install(name, path=path)
else:
needs_install = True
seeded = retcode(name,
'test -e \'{0}\''.format(SEED_MARKER),
path=path,
chroot_fallback=True,
ignore_retcode=True) == 0
tmp = tempfile.mkdtemp()
if seeded and not unconditional_install:
ret = True
else:
ret = False
cfg_files = __salt__['seed.mkconfig'](
config, tmp=tmp, id_=name, approve_key=approve_key,
pub_key=pub_key, priv_key=priv_key)
if needs_install or force_install or unconditional_install:
if install:
rstr = __salt__['test.random_hash']()
configdir = '/var/tmp/.c_{0}'.format(rstr)
cmd = 'install -m 0700 -d {0}'.format(configdir)
if run_all(
name, cmd, path=path, python_shell=False
)['retcode'] != 0:
log.error('tmpdir %s creation failed %s', configdir, cmd)
return False
bs_ = __salt__['config.gather_bootstrap_script'](
bootstrap=bootstrap_url)
script = '/sbin/{0}_bootstrap.sh'.format(rstr)
copy_to(name, bs_, script, path=path)
result = run_all(name,
'sh -c "chmod +x {0}"'.format(script),
path=path,
python_shell=True)
copy_to(name, cfg_files['config'],
os.path.join(configdir, 'minion'),
path=path)
copy_to(name, cfg_files['privkey'],
os.path.join(configdir, 'minion.pem'),
path=path)
copy_to(name, cfg_files['pubkey'],
os.path.join(configdir, 'minion.pub'),
path=path)
bootstrap_args = bootstrap_args.format(configdir)
cmd = ('{0} {2} {1}'
.format(bootstrap_shell,
bootstrap_args.replace("'", "''"),
script))
# log ASAP the forged bootstrap command which can be wrapped
# out of the output in case of unexpected problem
log.info('Running %s in LXC container \'%s\'', cmd, name)
ret = retcode(name, cmd, output_loglevel='info',
path=path, use_vt=True) == 0
run_all(name,
'sh -c \'if [ -f "{0}" ];then rm -f "{0}";fi\''
''.format(script),
path=path,
ignore_retcode=True,
python_shell=True)
else:
ret = False
else:
minion_config = salt.config.minion_config(cfg_files['config'])
pki_dir = minion_config['pki_dir']
copy_to(name,
cfg_files['config'],
'/etc/salt/minion',
path=path)
copy_to(name,
cfg_files['privkey'],
os.path.join(pki_dir, 'minion.pem'),
path=path)
copy_to(name,
cfg_files['pubkey'],
os.path.join(pki_dir, 'minion.pub'),
path=path)
run(name,
'salt-call --local service.enable salt-minion',
path=path,
python_shell=False)
ret = True
shutil.rmtree(tmp)
if orig_state == 'stopped':
stop(name, path=path)
elif orig_state == 'frozen':
freeze(name, path=path)
# mark seeded upon successful install
if ret:
run(name,
'touch \'{0}\''.format(SEED_MARKER),
path=path,
python_shell=False)
return ret
def attachable(name, path=None):
'''
Return True if the named container can be attached to via the lxc-attach
command
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt 'minion' lxc.attachable ubuntu
'''
cachekey = 'lxc.attachable{0}{1}'.format(name, path)
try:
return __context__[cachekey]
except KeyError:
_ensure_exists(name, path=path)
# Can't use run() here because it uses attachable() and would
# endlessly recurse, resulting in a traceback
log.debug('Checking if LXC container %s is attachable', name)
cmd = 'lxc-attach'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' --clear-env -n {0} -- /usr/bin/env'.format(name)
result = __salt__['cmd.retcode'](cmd,
python_shell=False,
output_loglevel='quiet',
ignore_retcode=True) == 0
__context__[cachekey] = result
return __context__[cachekey]
def _run(name,
cmd,
output=None,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=None,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
Common logic for lxc.run functions
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
'''
orig_state = state(name, path=path)
try:
if attachable(name, path=path):
ret = __salt__['container_resource.run'](
name,
cmd,
path=path,
container_type=__virtualname__,
exec_driver=EXEC_DRIVER,
output=output,
no_start=no_start,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
ignore_retcode=ignore_retcode,
use_vt=use_vt,
keep_env=keep_env)
else:
if not chroot_fallback:
raise CommandExecutionError(
'{0} is not attachable.'.format(name))
rootfs = info(name, path=path).get('rootfs')
# Set context var to make cmd.run_chroot run cmd.run instead of
# cmd.run_all.
__context__['cmd.run_chroot.func'] = __salt__['cmd.run']
ret = __salt__['cmd.run_chroot'](rootfs,
cmd,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
ignore_retcode=ignore_retcode)
except Exception:
raise
finally:
# Make sure we honor preserve_state, even if there was an exception
new_state = state(name, path=path)
if preserve_state:
if orig_state == 'stopped' and new_state != 'stopped':
stop(name, path=path)
elif orig_state == 'frozen' and new_state != 'frozen':
freeze(name, start=True, path=path)
if output in (None, 'all'):
return ret
else:
return ret[output]
def run(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.8.0
Run :mod:`cmd.run <salt.modules.cmdmod.run>` within a container
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed in stderr if the command being run
does not exist. If no output is returned using this function, try using
:mod:`lxc.run_stderr <salt.modules.lxc.run_stderr>` or
:mod:`lxc.run_all <salt.modules.lxc.run_all>`.
name
Name of the container in which to run the command
cmd
Command to run
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console. Assumes
``output=all``.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
CLI Example:
.. code-block:: bash
salt myminion lxc.run mycontainer 'ifconfig -a'
'''
return _run(name,
cmd,
path=path,
output=None,
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def run_stdout(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.5.0
Run :mod:`cmd.run_stdout <salt.modules.cmdmod.run_stdout>` within a container
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed in stderr if the command being run
does not exist. If no output is returned using this function, try using
:mod:`lxc.run_stderr <salt.modules.lxc.run_stderr>` or
:mod:`lxc.run_all <salt.modules.lxc.run_all>`.
name
Name of the container in which to run the command
cmd
Command to run
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console
``output=all``.
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
CLI Example:
.. code-block:: bash
salt myminion lxc.run_stdout mycontainer 'ifconfig -a'
'''
return _run(name,
cmd,
path=path,
output='stdout',
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def run_stderr(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.5.0
Run :mod:`cmd.run_stderr <salt.modules.cmdmod.run_stderr>` within a container
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed if the command being run does not
exist.
name
Name of the container in which to run the command
cmd
Command to run
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console
``output=all``.
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
CLI Example:
.. code-block:: bash
salt myminion lxc.run_stderr mycontainer 'ip addr show'
'''
return _run(name,
cmd,
path=path,
output='stderr',
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def retcode(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.5.0
Run :mod:`cmd.retcode <salt.modules.cmdmod.retcode>` within a container
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed in stderr if the command being run
does not exist. If the retcode is nonzero and not what was expected,
try using :mod:`lxc.run_stderr <salt.modules.lxc.run_stderr>`
or :mod:`lxc.run_all <salt.modules.lxc.run_all>`.
name
Name of the container in which to run the command
cmd
Command to run
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console
``output=all``.
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
CLI Example:
.. code-block:: bash
salt myminion lxc.retcode mycontainer 'ip addr show'
'''
return _run(name,
cmd,
output='retcode',
path=path,
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def run_all(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.5.0
Run :mod:`cmd.run_all <salt.modules.cmdmod.run_all>` within a container
.. note::
While the command is run within the container, it is initiated from the
host. Therefore, the PID in the return dict is from the host, not from
the container.
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed in stderr if the command being run
does not exist.
name
Name of the container in which to run the command
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
cmd
Command to run
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console
``output=all``.
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
CLI Example:
.. code-block:: bash
salt myminion lxc.run_all mycontainer 'ip addr show'
'''
return _run(name,
cmd,
output='all',
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
path=path,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def _get_md5(name, path):
'''
Get the MD5 checksum of a file from a container
'''
output = run_stdout(name, 'md5sum "{0}"'.format(path),
chroot_fallback=True,
ignore_retcode=True)
try:
return output.split()[0]
except IndexError:
# Destination file does not exist or could not be accessed
return None
def copy_to(name, source, dest, overwrite=False, makedirs=False, path=None):
'''
.. versionchanged:: 2015.8.0
Function renamed from ``lxc.cp`` to ``lxc.copy_to`` for consistency
with other container types. ``lxc.cp`` will continue to work, however.
For versions 2015.2.x and earlier, use ``lxc.cp``.
Copy a file or directory from the host into a container
name
Container name
source
File to be copied to the container
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
dest
Destination on the container. Must be an absolute path.
.. versionchanged:: 2015.5.0
If the destination is a directory, the file will be copied into
that directory.
overwrite : False
Unless this option is set to ``True``, then if a file exists at the
location specified by the ``dest`` argument, an error will be raised.
.. versionadded:: 2015.8.0
makedirs : False
Create the parent directory on the container if it does not already
exist.
.. versionadded:: 2015.5.0
CLI Example:
.. code-block:: bash
salt 'minion' lxc.copy_to /tmp/foo /root/foo
salt 'minion' lxc.cp /tmp/foo /root/foo
'''
_ensure_running(name, no_start=True, path=path)
return __salt__['container_resource.copy_to'](
name,
source,
dest,
container_type=__virtualname__,
path=path,
exec_driver=EXEC_DRIVER,
overwrite=overwrite,
makedirs=makedirs)
cp = salt.utils.functools.alias_function(copy_to, 'cp')
def read_conf(conf_file, out_format='simple'):
'''
Read in an LXC configuration file. By default returns a simple, unsorted
dict, but can also return a more detailed structure including blank lines
and comments.
out_format:
set to 'simple' if you need the old and unsupported behavior.
This won't support the multiple lxc values (eg: multiple network nics)
CLI Examples:
.. code-block:: bash
salt 'minion' lxc.read_conf /etc/lxc/mycontainer.conf
salt 'minion' lxc.read_conf /etc/lxc/mycontainer.conf out_format=commented
'''
ret_commented = []
ret_simple = {}
with salt.utils.files.fopen(conf_file, 'r') as fp_:
for line in salt.utils.data.decode(fp_.readlines()):
if '=' not in line:
ret_commented.append(line)
continue
comps = line.split('=')
value = '='.join(comps[1:]).strip()
comment = None
if value.strip().startswith('#'):
vcomps = value.strip().split('#')
value = vcomps[1].strip()
comment = '#'.join(vcomps[1:]).strip()
ret_commented.append({comps[0].strip(): {
'value': value,
'comment': comment,
}})
else:
ret_commented.append({comps[0].strip(): value})
ret_simple[comps[0].strip()] = value
if out_format == 'simple':
return ret_simple
return ret_commented
def write_conf(conf_file, conf):
'''
Write out an LXC configuration file
This is normally only used internally. The format of the data structure
must match that which is returned from ``lxc.read_conf()``, with
``out_format`` set to ``commented``.
An example might look like:
.. code-block:: python
[
{'lxc.utsname': '$CONTAINER_NAME'},
'# This is a commented line\\n',
'\\n',
{'lxc.mount': '$CONTAINER_FSTAB'},
{'lxc.rootfs': {'comment': 'This is another test',
'value': 'This is another test'}},
'\\n',
{'lxc.network.type': 'veth'},
{'lxc.network.flags': 'up'},
{'lxc.network.link': 'br0'},
{'lxc.network.mac': '$CONTAINER_MACADDR'},
{'lxc.network.ipv4': '$CONTAINER_IPADDR'},
{'lxc.network.name': '$CONTAINER_DEVICENAME'},
]
CLI Example:
.. code-block:: bash
salt 'minion' lxc.write_conf /etc/lxc/mycontainer.conf \\
out_format=commented
'''
if not isinstance(conf, list):
raise SaltInvocationError('Configuration must be passed as a list')
# construct the content prior to write to the file
# to avoid half written configs
content = ''
for line in conf:
if isinstance(line, (six.text_type, six.string_types)):
content += line
elif isinstance(line, dict):
for key in list(line.keys()):
out_line = None
if isinstance(
line[key],
(six.text_type, six.string_types, six.integer_types, float)
):
out_line = ' = '.join((key, "{0}".format(line[key])))
elif isinstance(line[key], dict):
out_line = ' = '.join((key, line[key]['value']))
if 'comment' in line[key]:
out_line = ' # '.join((out_line, line[key]['comment']))
if out_line:
content += out_line
content += '\n'
with salt.utils.files.fopen(conf_file, 'w') as fp_:
fp_.write(salt.utils.stringutils.to_str(content))
return {}
def edit_conf(conf_file,
out_format='simple',
read_only=False,
lxc_config=None,
**kwargs):
'''
Edit an LXC configuration file. If a setting is already present inside the
file, its value will be replaced. If it does not exist, it will be appended
to the end of the file. Comments and blank lines will be kept in-tact if
they already exist in the file.
out_format:
Set to simple if you need backward compatibility (multiple items for a
simple key is not supported)
read_only:
return only the edited configuration without applying it
to the underlying lxc configuration file
lxc_config:
List of dict containning lxc configuration items
For network configuration, you also need to add the device it belongs
to, otherwise it will default to eth0.
Also, any change to a network parameter will result in the whole
network reconfiguration to avoid mismatchs, be aware of that !
After the file is edited, its contents will be returned. By default, it
will be returned in ``simple`` format, meaning an unordered dict (which
may not represent the actual file order). Passing in an ``out_format`` of
``commented`` will return a data structure which accurately represents the
order and content of the file.
CLI Example:
.. code-block:: bash
salt 'minion' lxc.edit_conf /etc/lxc/mycontainer.conf \\
out_format=commented lxc.network.type=veth
salt 'minion' lxc.edit_conf /etc/lxc/mycontainer.conf \\
out_format=commented \\
lxc_config="[{'lxc.network.name': 'eth0', \\
'lxc.network.ipv4': '1.2.3.4'},
{'lxc.network.name': 'eth2', \\
'lxc.network.ipv4': '1.2.3.5',\\
'lxc.network.gateway': '1.2.3.1'}]"
'''
data = []
try:
conf = read_conf(conf_file, out_format=out_format)
except Exception:
conf = []
if not lxc_config:
lxc_config = []
lxc_config = copy.deepcopy(lxc_config)
# search if we want to access net config
# in that case, we will replace all the net configuration
net_config = []
for lxc_kws in lxc_config + [kwargs]:
net_params = {}
for kwarg in [a for a in lxc_kws]:
if kwarg.startswith('__'):
continue
if kwarg.startswith('lxc.network.'):
net_params[kwarg] = lxc_kws[kwarg]
lxc_kws.pop(kwarg, None)
if net_params:
net_config.append(net_params)
nic_opts = salt.utils.odict.OrderedDict()
for params in net_config:
dev = params.get('lxc.network.name', DEFAULT_NIC)
dev_opts = nic_opts.setdefault(dev, salt.utils.odict.OrderedDict())
for param in params:
opt = param.replace('lxc.network.', '')
opt = {'hwaddr': 'mac'}.get(opt, opt)
dev_opts[opt] = params[param]
net_changes = []
if nic_opts:
net_changes = _config_list(conf, only_net=True,
**{'network_profile': DEFAULT_NIC,
'nic_opts': nic_opts})
if net_changes:
lxc_config.extend(net_changes)
for line in conf:
if not isinstance(line, dict):
data.append(line)
continue
else:
for key in list(line.keys()):
val = line[key]
if net_changes and key.startswith('lxc.network.'):
continue
found = False
for ix in range(len(lxc_config)):
kw = lxc_config[ix]
if key in kw:
found = True
data.append({key: kw[key]})
del kw[key]
if not found:
data.append({key: val})
for lxc_kws in lxc_config:
for kwarg in lxc_kws:
data.append({kwarg: lxc_kws[kwarg]})
if read_only:
return data
write_conf(conf_file, data)
return read_conf(conf_file, out_format)
def reboot(name, path=None):
'''
Reboot a container.
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Examples:
.. code-block:: bash
salt 'minion' lxc.reboot myvm
'''
ret = {'result': True,
'changes': {},
'comment': '{0} rebooted'.format(name)}
does_exist = exists(name, path=path)
if does_exist and (state(name, path=path) == 'running'):
try:
stop(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
ret['result'] = False
return ret
if does_exist and (state(name, path=path) != 'running'):
try:
start(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
ret['result'] = False
return ret
ret['changes'][name] = 'rebooted'
return ret
def reconfigure(name,
cpu=None,
cpuset=None,
cpushare=None,
memory=None,
profile=None,
network_profile=None,
nic_opts=None,
bridge=None,
gateway=None,
autostart=None,
utsname=None,
rootfs=None,
path=None,
**kwargs):
'''
Reconfigure a container.
This only applies to a few property
name
Name of the container.
utsname
utsname of the container.
.. versionadded:: 2016.3.0
rootfs
rootfs of the container.
.. versionadded:: 2016.3.0
cpu
Select a random number of cpu cores and assign it to the cpuset, if the
cpuset option is set then this option will be ignored
cpuset
Explicitly define the cpus this container will be bound to
cpushare
cgroups cpu shares.
autostart
autostart container on reboot
memory
cgroups memory limit, in MB.
(0 for nolimit, None for old default 1024MB)
gateway
the ipv4 gateway to use
the default does nothing more than lxcutils does
bridge
the bridge to use
the default does nothing more than lxcutils does
nic
Network interfaces profile (defined in config or pillar).
nic_opts
Extra options for network interfaces, will override
``{"eth0": {"mac": "aa:bb:cc:dd:ee:ff", "ipv4": "10.1.1.1", "ipv6": "2001:db8::ff00:42:8329"}}``
or
``{"eth0": {"mac": "aa:bb:cc:dd:ee:ff", "ipv4": "10.1.1.1/24", "ipv6": "2001:db8::ff00:42:8329"}}``
path
path to the container parent
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt-call -lall mc_lxc_fork.reconfigure foobar nic_opts="{'eth1': {'mac': '00:16:3e:dd:ee:44'}}" memory=4
'''
changes = {}
cpath = get_root_path(path)
path = os.path.join(cpath, name, 'config')
ret = {'name': name,
'comment': 'config for {0} up to date'.format(name),
'result': True,
'changes': changes}
profile = get_container_profile(copy.deepcopy(profile))
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, _marker)
profile_match = profile.pop(key, default)
# let kwarg overrides be the preferred choice
if kw_overrides_match is _marker:
return profile_match
return kw_overrides_match
if nic_opts is not None and not network_profile:
network_profile = DEFAULT_NIC
if autostart is not None:
autostart = select('autostart', autostart)
else:
autostart = 'keep'
if not utsname:
utsname = select('utsname', utsname)
if os.path.exists(path):
old_chunks = read_conf(path, out_format='commented')
make_kw = salt.utils.odict.OrderedDict([
('utsname', utsname),
('rootfs', rootfs),
('autostart', autostart),
('cpu', cpu),
('gateway', gateway),
('cpuset', cpuset),
('cpushare', cpushare),
('network_profile', network_profile),
('nic_opts', nic_opts),
('bridge', bridge)])
# match 0 and none as memory = 0 in lxc config is harmful
if memory:
make_kw['memory'] = memory
kw = salt.utils.odict.OrderedDict()
for key, val in six.iteritems(make_kw):
if val is not None:
kw[key] = val
new_cfg = _config_list(conf_tuples=old_chunks, **kw)
if new_cfg:
edit_conf(path, out_format='commented', lxc_config=new_cfg)
chunks = read_conf(path, out_format='commented')
if old_chunks != chunks:
ret['comment'] = '{0} lxc config updated'.format(name)
if state(name, path=path) == 'running':
cret = reboot(name, path=path)
ret['result'] = cret['result']
return ret
def apply_network_profile(name, network_profile, nic_opts=None, path=None):
'''
.. versionadded:: 2015.5.0
Apply a network profile to a container
network_profile
profile name or default values (dict)
nic_opts
values to override in defaults (dict)
indexed by nic card names
path
path to the container parent
.. versionadded:: 2015.8.0
CLI Examples:
.. code-block:: bash
salt 'minion' lxc.apply_network_profile web1 centos
salt 'minion' lxc.apply_network_profile web1 centos \\
nic_opts="{'eth0': {'mac': 'xx:xx:xx:xx:xx:xx'}}"
salt 'minion' lxc.apply_network_profile web1 \\
"{'eth0': {'mac': 'xx:xx:xx:xx:xx:yy'}}"
nic_opts="{'eth0': {'mac': 'xx:xx:xx:xx:xx:xx'}}"
The special case to disable use of ethernet nics:
.. code-block:: bash
salt 'minion' lxc.apply_network_profile web1 centos \\
"{eth0: {disable: true}}"
'''
cpath = get_root_path(path)
cfgpath = os.path.join(cpath, name, 'config')
before = []
with salt.utils.files.fopen(cfgpath, 'r') as fp_:
for line in fp_:
before.append(line)
lxcconfig = _LXCConfig(name=name, path=path)
old_net = lxcconfig._filter_data('lxc.network')
network_params = {}
for param in _network_conf(
conf_tuples=old_net,
network_profile=network_profile, nic_opts=nic_opts
):
network_params.update(param)
if network_params:
edit_conf(cfgpath, out_format='commented', **network_params)
after = []
with salt.utils.files.fopen(cfgpath, 'r') as fp_:
for line in fp_:
after.append(line)
diff = ''
for line in difflib.unified_diff(before,
after,
fromfile='before',
tofile='after'):
diff += line
return diff
def get_pid(name, path=None):
'''
Returns a container pid.
Throw an exception if the container isn't running.
CLI Example:
.. code-block:: bash
salt '*' lxc.get_pid name
'''
if name not in list_(limit='running', path=path):
raise CommandExecutionError('Container {0} is not running, can\'t determine PID'.format(name))
info = __salt__['cmd.run']('lxc-info -n {0}'.format(name)).split("\n")
pid = [line.split(':')[1].strip() for line in info if re.match(r'\s*PID', line)][0]
return pid
def add_veth(name, interface_name, bridge=None, path=None):
'''
Add a veth to a container.
Note : this function doesn't update the container config, just add the interface at runtime
name
Name of the container
interface_name
Name of the interface in the container
bridge
Name of the bridge to attach the interface to (facultative)
CLI Examples:
.. code-block:: bash
salt '*' lxc.add_veth container_name eth1 br1
salt '*' lxc.add_veth container_name eth1
'''
# Get container init PID
pid = get_pid(name, path=path)
# Generate a ramdom string for veth and ensure that is isn't present on the system
while True:
random_veth = 'veth'+''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(6))
if random_veth not in __salt__['network.interfaces']().keys():
break
# Check prerequisites
if not __salt__['file.directory_exists']('/var/run/'):
raise CommandExecutionError('Directory /var/run required for lxc.add_veth doesn\'t exists')
if not __salt__['file.file_exists']('/proc/{0}/ns/net'.format(pid)):
raise CommandExecutionError('Proc file for container {0} network namespace doesn\'t exists'.format(name))
if not __salt__['file.directory_exists']('/var/run/netns'):
__salt__['file.mkdir']('/var/run/netns')
# Ensure that the symlink is up to date (change on container restart)
if __salt__['file.is_link']('/var/run/netns/{0}'.format(name)):
__salt__['file.remove']('/var/run/netns/{0}'.format(name))
__salt__['file.symlink']('/proc/{0}/ns/net'.format(pid), '/var/run/netns/{0}'.format(name))
# Ensure that interface doesn't exists
interface_exists = 0 == __salt__['cmd.retcode']('ip netns exec {netns} ip address list {interface}'.format(
netns=name,
interface=interface_name
))
if interface_exists:
raise CommandExecutionError('Interface {interface} already exists in {container}'.format(
interface=interface_name,
container=name
))
# Create veth and bring it up
if __salt__['cmd.retcode']('ip link add name {veth} type veth peer name {veth}_c'.format(veth=random_veth)) != 0:
raise CommandExecutionError('Error while creating the veth pair {0}'.format(random_veth))
if __salt__['cmd.retcode']('ip link set dev {0} up'.format(random_veth)) != 0:
raise CommandExecutionError('Error while bringing up host-side veth {0}'.format(random_veth))
# Attach it to the container
attached = 0 == __salt__['cmd.retcode']('ip link set dev {veth}_c netns {container} name {interface_name}'.format(
veth=random_veth,
container=name,
interface_name=interface_name
))
if not attached:
raise CommandExecutionError('Error while attaching the veth {veth} to container {container}'.format(
veth=random_veth,
container=name
))
__salt__['file.remove']('/var/run/netns/{0}'.format(name))
if bridge is not None:
__salt__['bridge.addif'](bridge, random_veth)
|
saltstack/salt
|
salt/modules/lxc.py
|
freeze
|
python
|
def freeze(name, **kwargs):
'''
Freeze the named container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
start : False
If ``True`` and the container is stopped, the container will be started
before attempting to freeze.
.. versionadded:: 2015.5.0
use_vt
run the command through VT
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.freeze name
'''
use_vt = kwargs.get('use_vt', None)
path = kwargs.get('path', None)
_ensure_exists(name, path=path)
orig_state = state(name, path=path)
start_ = kwargs.get('start', False)
if orig_state == 'stopped':
if not start_:
raise CommandExecutionError(
'Container \'{0}\' is stopped'.format(name)
)
start(name, path=path)
cmd = 'lxc-freeze'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
ret = _change_state(cmd, name, 'frozen', use_vt=use_vt, path=path)
if orig_state == 'stopped' and start_:
ret['state']['old'] = orig_state
ret['started'] = True
ret['state']['new'] = state(name, path=path)
return ret
|
Freeze the named container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
start : False
If ``True`` and the container is stopped, the container will be started
before attempting to freeze.
.. versionadded:: 2015.5.0
use_vt
run the command through VT
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.freeze name
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/lxc.py#L2484-L2530
|
[
"def start(name, **kwargs):\n '''\n Start the named container\n\n path\n path to the container parent directory\n default: /var/lib/lxc (system)\n\n .. versionadded:: 2015.8.0\n\n lxc_config\n path to a lxc config file\n config file will be guessed from container name otherwise\n\n .. versionadded:: 2015.8.0\n\n use_vt\n run the command through VT\n\n .. versionadded:: 2015.8.0\n\n CLI Example:\n\n .. code-block:: bash\n\n salt myminion lxc.start name\n '''\n path = kwargs.get('path', None)\n cpath = get_root_path(path)\n lxc_config = kwargs.get('lxc_config', None)\n cmd = 'lxc-start'\n if not lxc_config:\n lxc_config = os.path.join(cpath, name, 'config')\n # we try to start, even without config, if global opts are there\n if os.path.exists(lxc_config):\n cmd += ' -f {0}'.format(pipes.quote(lxc_config))\n cmd += ' -d'\n _ensure_exists(name, path=path)\n if state(name, path=path) == 'frozen':\n raise CommandExecutionError(\n 'Container \\'{0}\\' is frozen, use lxc.unfreeze'.format(name)\n )\n # lxc-start daemonize itself violently, we must not communicate with it\n use_vt = kwargs.get('use_vt', None)\n with_communicate = kwargs.get('with_communicate', False)\n return _change_state(cmd, name, 'running',\n stdout=None,\n stderr=None,\n stdin=None,\n with_communicate=with_communicate,\n path=path,\n use_vt=use_vt)\n",
"def state(name, path=None):\n '''\n Returns the state of a container.\n\n path\n path to the container parent directory (default: /var/lib/lxc)\n\n .. versionadded:: 2015.8.0\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' lxc.state name\n '''\n # Don't use _ensure_exists() here, it will mess with _change_state()\n\n cachekey = 'lxc.state.{0}{1}'.format(name, path)\n try:\n return __context__[cachekey]\n except KeyError:\n if not exists(name, path=path):\n __context__[cachekey] = None\n else:\n cmd = 'lxc-info'\n if path:\n cmd += ' -P {0}'.format(pipes.quote(path))\n cmd += ' -n {0}'.format(name)\n ret = __salt__['cmd.run_all'](cmd, python_shell=False)\n if ret['retcode'] != 0:\n _clear_context()\n raise CommandExecutionError(\n 'Unable to get state of container \\'{0}\\''.format(name)\n )\n c_infos = ret['stdout'].splitlines()\n c_state = None\n for c_info in c_infos:\n stat = c_info.split(':')\n if stat[0].lower() == 'state':\n c_state = stat[1].strip().lower()\n break\n __context__[cachekey] = c_state\n return __context__[cachekey]\n",
"def _change_state(cmd,\n name,\n expected,\n stdin=_marker,\n stdout=_marker,\n stderr=_marker,\n with_communicate=_marker,\n use_vt=_marker,\n path=None):\n pre = state(name, path=path)\n if pre == expected:\n return {'result': True,\n 'state': {'old': expected, 'new': expected},\n 'comment': 'Container \\'{0}\\' already {1}'\n .format(name, expected)}\n\n if cmd == 'lxc-destroy':\n # Kill the container first\n scmd = 'lxc-stop'\n if path:\n scmd += ' -P {0}'.format(pipes.quote(path))\n scmd += ' -k -n {0}'.format(name)\n __salt__['cmd.run'](scmd,\n python_shell=False)\n\n if path and ' -P ' not in cmd:\n cmd += ' -P {0}'.format(pipes.quote(path))\n cmd += ' -n {0}'.format(name)\n\n # certain lxc commands need to be taken with care (lxc-start)\n # as te command itself mess with double forks; we must not\n # communicate with it, but just wait for the exit status\n pkwargs = {'python_shell': False,\n 'redirect_stderr': True,\n 'with_communicate': with_communicate,\n 'use_vt': use_vt,\n 'stdin': stdin,\n 'stdout': stdout}\n for i in [a for a in pkwargs]:\n val = pkwargs[i]\n if val is _marker:\n pkwargs.pop(i, None)\n\n _cmdout = __salt__['cmd.run_all'](cmd, **pkwargs)\n\n if _cmdout['retcode'] != 0:\n raise CommandExecutionError(\n 'Error changing state for container \\'{0}\\' using command '\n '\\'{1}\\': {2}'.format(name, cmd, _cmdout['stdout'])\n )\n if expected is not None:\n # some commands do not wait, so we will\n rcmd = 'lxc-wait'\n if path:\n rcmd += ' -P {0}'.format(pipes.quote(path))\n rcmd += ' -n {0} -s {1}'.format(name, expected.upper())\n __salt__['cmd.run'](rcmd, python_shell=False, timeout=30)\n _clear_context()\n post = state(name, path=path)\n ret = {'result': post == expected,\n 'state': {'old': pre, 'new': post}}\n return ret\n",
"def _ensure_exists(name, path=None):\n '''\n Raise an exception if the container does not exist\n '''\n if not exists(name, path=path):\n raise CommandExecutionError(\n 'Container \\'{0}\\' does not exist'.format(name)\n )\n"
] |
# -*- coding: utf-8 -*-
'''
Control Linux Containers via Salt
:depends: lxc package for distribution
lxc >= 1.0 (even beta alpha) is required
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import datetime
import copy
import string
import textwrap
import difflib
import logging
import tempfile
import os
import pipes
import time
import shutil
import re
import random
# Import salt libs
import salt.utils.args
import salt.utils.cloud
import salt.utils.data
import salt.utils.dictupdate
import salt.utils.files
import salt.utils.functools
import salt.utils.hashutils
import salt.utils.network
import salt.utils.odict
import salt.utils.path
import salt.utils.stringutils
from salt.exceptions import CommandExecutionError, SaltInvocationError
import salt.config
from salt.utils.versions import LooseVersion as _LooseVersion
# Import 3rd-party libs
from salt.ext import six
# pylint: disable=import-error,no-name-in-module
from salt.ext.six.moves import range # pylint: disable=redefined-builtin
from salt.ext.six.moves.urllib.parse import urlparse as _urlparse
# pylint: enable=import-error,no-name-in-module
# Set up logging
log = logging.getLogger(__name__)
# Don't shadow built-in's.
__func_alias__ = {
'list_': 'list',
'ls_': 'ls'
}
__virtualname__ = 'lxc'
DEFAULT_NIC = 'eth0'
DEFAULT_BR = 'br0'
SEED_MARKER = '/lxc.initial_seed'
EXEC_DRIVER = 'lxc-attach'
DEFAULT_PATH = '/var/lib/lxc'
_marker = object()
def __virtual__():
if salt.utils.path.which('lxc-start'):
return __virtualname__
# To speed up the whole thing, we decided to not use the
# subshell way and assume things are in place for lxc
# Discussion made by @kiorky and @thatch45
# lxc-version presence is not sufficient, in lxc1.0 alpha
# (precise backports), we have it and it is sufficient
# for the module to execute.
# elif salt.utils.path.which('lxc-version'):
# passed = False
# try:
# passed = subprocess.check_output(
# 'lxc-version').split(':')[1].strip() >= '1.0'
# except Exception:
# pass
# if not passed:
# log.warning('Support for lxc < 1.0 may be incomplete.')
# return 'lxc'
# return False
#
return (False, 'The lxc execution module cannot be loaded: the lxc-start binary is not in the path.')
def get_root_path(path):
'''
Get the configured lxc root for containers
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.get_root_path
'''
if not path:
path = __opts__.get('lxc.root_path', DEFAULT_PATH)
return path
def version():
'''
Return the actual lxc client version
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.version
'''
k = 'lxc.version'
if not __context__.get(k, None):
cversion = __salt__['cmd.run_all']('lxc-info --version')
if not cversion['retcode']:
ver = _LooseVersion(cversion['stdout'])
if ver < _LooseVersion('1.0'):
raise CommandExecutionError('LXC should be at least 1.0')
__context__[k] = "{0}".format(ver)
return __context__.get(k, None)
def _clear_context():
'''
Clear any lxc variables set in __context__
'''
for var in [x for x in __context__ if x.startswith('lxc.')]:
log.trace('Clearing __context__[\'%s\']', var)
__context__.pop(var, None)
def _ip_sort(ip):
'''Ip sorting'''
idx = '001'
if ip == '127.0.0.1':
idx = '200'
if ip == '::1':
idx = '201'
elif '::' in ip:
idx = '100'
return '{0}___{1}'.format(idx, ip)
def search_lxc_bridges():
'''
Search which bridges are potentially available as LXC bridges
CLI Example:
.. code-block:: bash
salt '*' lxc.search_lxc_bridges
'''
bridges = __context__.get('lxc.bridges', None)
# either match not yet called or no bridges were found
# to handle the case where lxc was not installed on the first
# call
if not bridges:
bridges = set()
running_bridges = set()
bridges.add(DEFAULT_BR)
try:
output = __salt__['cmd.run_all']('brctl show')
for line in output['stdout'].splitlines()[1:]:
if not line.startswith(' '):
running_bridges.add(line.split()[0].strip())
except (SaltInvocationError, CommandExecutionError):
pass
for ifc, ip in six.iteritems(
__grains__.get('ip_interfaces', {})
):
if ifc in running_bridges:
bridges.add(ifc)
elif os.path.exists(
'/sys/devices/virtual/net/{0}/bridge'.format(ifc)
):
bridges.add(ifc)
bridges = list(bridges)
# if we found interfaces that have lxc in their names
# we filter them as being the potential lxc bridges
# we also try to default on br0 on other cases
def sort_bridges(a):
pref = 'z'
if 'lxc' in a:
pref = 'a'
elif 'br0' == a:
pref = 'c'
return '{0}_{1}'.format(pref, a)
bridges.sort(key=sort_bridges)
__context__['lxc.bridges'] = bridges
return bridges
def search_lxc_bridge():
'''
Search the first bridge which is potentially available as LXC bridge
CLI Example:
.. code-block:: bash
salt '*' lxc.search_lxc_bridge
'''
return search_lxc_bridges()[0]
def _get_salt_config(config, **kwargs):
if not config:
config = kwargs.get('minion', {})
if not config:
config = {}
config.setdefault('master',
kwargs.get('master',
__opts__.get('master',
__opts__['id'])))
config.setdefault(
'master_port',
kwargs.get('master_port',
__opts__.get('master_port',
__opts__.get('ret_port',
__opts__.get('4506')))))
if not config['master']:
config = {}
return config
def cloud_init_interface(name, vm_=None, **kwargs):
'''
Interface between salt.cloud.lxc driver and lxc.init
``vm_`` is a mapping of vm opts in the salt.cloud format
as documented for the lxc driver.
This can be used either:
- from the salt cloud driver
- because you find the argument to give easier here
than using directly lxc.init
.. warning::
BE REALLY CAREFUL CHANGING DEFAULTS !!!
IT'S A RETRO COMPATIBLE INTERFACE WITH
THE SALT CLOUD DRIVER (ask kiorky).
name
name of the lxc container to create
pub_key
public key to preseed the minion with.
Can be the keycontent or a filepath
priv_key
private key to preseed the minion with.
Can be the keycontent or a filepath
path
path to the container parent directory (default: /var/lib/lxc)
.. versionadded:: 2015.8.0
profile
:ref:`profile <tutorial-lxc-profiles-container>` selection
network_profile
:ref:`network profile <tutorial-lxc-profiles-network>` selection
nic_opts
per interface settings compatibles with
network profile (ipv4/ipv6/link/gateway/mac/netmask)
eg::
- {'eth0': {'mac': '00:16:3e:01:29:40',
'gateway': None, (default)
'link': 'br0', (default)
'gateway': None, (default)
'netmask': '', (default)
'ip': '22.1.4.25'}}
unconditional_install
given to lxc.bootstrap (see relative doc)
force_install
given to lxc.bootstrap (see relative doc)
config
any extra argument for the salt minion config
dnsservers
list of DNS servers to set inside the container
dns_via_dhcp
do not set the dns servers, let them be set by the dhcp.
autostart
autostart the container at boot time
password
administrative password for the container
bootstrap_delay
delay before launching bootstrap script at Container init
.. warning::
Legacy but still supported options:
from_container
which container we use as a template
when running lxc.clone
image
which template do we use when we
are using lxc.create. This is the default
mode unless you specify something in from_container
backing
which backing store to use.
Values can be: overlayfs, dir(default), lvm, zfs, brtfs
fstype
When using a blockdevice level backing store,
which filesystem to use on
size
When using a blockdevice level backing store,
which size for the filesystem to use on
snapshot
Use snapshot when cloning the container source
vgname
if using LVM: vgname
lvname
if using LVM: lvname
thinpool:
if using LVM: thinpool
ip
ip for the primary nic
mac
mac address for the primary nic
netmask
netmask for the primary nic (24)
= ``vm_.get('netmask', '24')``
bridge
bridge for the primary nic (lxcbr0)
gateway
network gateway for the container
additional_ips
additional ips which will be wired on the main bridge (br0)
which is connected to internet.
Be aware that you may use manual virtual mac addresses
providen by you provider (online, ovh, etc).
This is a list of mappings {ip: '', mac: '', netmask:''}
Set gateway to None and an interface with a gateway
to escape from another interface that eth0.
eg::
- {'mac': '00:16:3e:01:29:40',
'gateway': None, (default)
'link': 'br0', (default)
'netmask': '', (default)
'ip': '22.1.4.25'}
users
administrative users for the container
default: [root] and [root, ubuntu] on ubuntu
default_nic
name of the first interface, you should
really not override this
CLI Example:
.. code-block:: bash
salt '*' lxc.cloud_init_interface foo
'''
if vm_ is None:
vm_ = {}
vm_ = copy.deepcopy(vm_)
vm_ = salt.utils.dictupdate.update(vm_, kwargs)
profile_data = copy.deepcopy(
vm_.get('lxc_profile',
vm_.get('profile', {})))
if not isinstance(profile_data, (dict, six.string_types)):
profile_data = {}
profile = get_container_profile(profile_data)
def _cloud_get(k, default=None):
return vm_.get(k, profile.get(k, default))
if name is None:
name = vm_['name']
# if we are on ubuntu, default to ubuntu
default_template = ''
if __grains__.get('os', '') in ['Ubuntu']:
default_template = 'ubuntu'
image = _cloud_get('image')
if not image:
_cloud_get('template', default_template)
backing = _cloud_get('backing', 'dir')
if image:
profile['template'] = image
vgname = _cloud_get('vgname', None)
if vgname:
profile['vgname'] = vgname
if backing:
profile['backing'] = backing
snapshot = _cloud_get('snapshot', False)
autostart = bool(_cloud_get('autostart', True))
dnsservers = _cloud_get('dnsservers', [])
dns_via_dhcp = _cloud_get('dns_via_dhcp', True)
password = _cloud_get('password', 's3cr3t')
password_encrypted = _cloud_get('password_encrypted', False)
fstype = _cloud_get('fstype', None)
lvname = _cloud_get('lvname', None)
thinpool = _cloud_get('thinpool', None)
pub_key = _cloud_get('pub_key', None)
priv_key = _cloud_get('priv_key', None)
size = _cloud_get('size', '20G')
script = _cloud_get('script', None)
script_args = _cloud_get('script_args', None)
users = _cloud_get('users', None)
if users is None:
users = []
ssh_username = _cloud_get('ssh_username', None)
if ssh_username and (ssh_username not in users):
users.append(ssh_username)
network_profile = _cloud_get('network_profile', None)
nic_opts = kwargs.get('nic_opts', None)
netmask = _cloud_get('netmask', '24')
path = _cloud_get('path', None)
bridge = _cloud_get('bridge', None)
gateway = _cloud_get('gateway', None)
unconditional_install = _cloud_get('unconditional_install', False)
force_install = _cloud_get('force_install', True)
config = _get_salt_config(_cloud_get('config', {}), **vm_)
default_nic = _cloud_get('default_nic', DEFAULT_NIC)
# do the interface with lxc.init mainly via nic_opts
# to avoid extra and confusing extra use cases.
if not isinstance(nic_opts, dict):
nic_opts = salt.utils.odict.OrderedDict()
# have a reference to the default nic
eth0 = nic_opts.setdefault(default_nic,
salt.utils.odict.OrderedDict())
# lxc config is based of ifc order, be sure to use odicts.
if not isinstance(nic_opts, salt.utils.odict.OrderedDict):
bnic_opts = salt.utils.odict.OrderedDict()
bnic_opts.update(nic_opts)
nic_opts = bnic_opts
gw = None
# legacy salt.cloud scheme for network interfaces settings support
bridge = _cloud_get('bridge', None)
ip = _cloud_get('ip', None)
mac = _cloud_get('mac', None)
if ip:
fullip = ip
if netmask:
fullip += '/{0}'.format(netmask)
eth0['ipv4'] = fullip
if mac is not None:
eth0['mac'] = mac
for ix, iopts in enumerate(_cloud_get("additional_ips", [])):
ifh = "eth{0}".format(ix+1)
ethx = nic_opts.setdefault(ifh, {})
if gw is None:
gw = iopts.get('gateway', ethx.get('gateway', None))
if gw:
# only one and only one default gateway is allowed !
eth0.pop('gateway', None)
gateway = None
# even if the gateway if on default "eth0" nic
# and we popped it will work
# as we reinject or set it here.
ethx['gateway'] = gw
elink = iopts.get('link', ethx.get('link', None))
if elink:
ethx['link'] = elink
# allow dhcp
aip = iopts.get('ipv4', iopts.get('ip', None))
if aip:
ethx['ipv4'] = aip
nm = iopts.get('netmask', '')
if nm:
ethx['ipv4'] += '/{0}'.format(nm)
for i in ('mac', 'hwaddr'):
if i in iopts:
ethx['mac'] = iopts[i]
break
if 'mac' not in ethx:
ethx['mac'] = salt.utils.network.gen_mac()
# last round checking for unique gateway and such
gw = None
for ethx in [a for a in nic_opts]:
ndata = nic_opts[ethx]
if gw:
ndata.pop('gateway', None)
if 'gateway' in ndata:
gw = ndata['gateway']
gateway = None
# only use a default bridge / gateway if we configured them
# via the legacy salt cloud configuration style.
# On other cases, we should rely on settings provided by the new
# salt lxc network profile style configuration which can
# be also be overridden or a per interface basis via the nic_opts dict.
if bridge:
eth0['link'] = bridge
if gateway:
eth0['gateway'] = gateway
#
lxc_init_interface = {}
lxc_init_interface['name'] = name
lxc_init_interface['config'] = config
lxc_init_interface['memory'] = _cloud_get('memory', 0) # nolimit
lxc_init_interface['pub_key'] = pub_key
lxc_init_interface['priv_key'] = priv_key
lxc_init_interface['nic_opts'] = nic_opts
for clone_from in ['clone_from', 'clone', 'from_container']:
# clone_from should default to None if not available
lxc_init_interface['clone_from'] = _cloud_get(clone_from, None)
if lxc_init_interface['clone_from'] is not None:
break
lxc_init_interface['profile'] = profile
lxc_init_interface['snapshot'] = snapshot
lxc_init_interface['dnsservers'] = dnsservers
lxc_init_interface['fstype'] = fstype
lxc_init_interface['path'] = path
lxc_init_interface['vgname'] = vgname
lxc_init_interface['size'] = size
lxc_init_interface['lvname'] = lvname
lxc_init_interface['thinpool'] = thinpool
lxc_init_interface['force_install'] = force_install
lxc_init_interface['unconditional_install'] = (
unconditional_install
)
lxc_init_interface['bootstrap_url'] = script
lxc_init_interface['bootstrap_args'] = script_args
lxc_init_interface['bootstrap_shell'] = _cloud_get('bootstrap_shell', 'sh')
lxc_init_interface['bootstrap_delay'] = _cloud_get('bootstrap_delay', None)
lxc_init_interface['autostart'] = autostart
lxc_init_interface['users'] = users
lxc_init_interface['password'] = password
lxc_init_interface['password_encrypted'] = password_encrypted
# be sure not to let objects goes inside the return
# as this return will be msgpacked for use in the runner !
lxc_init_interface['network_profile'] = network_profile
for i in ['cpu', 'cpuset', 'cpushare']:
if _cloud_get(i, None):
try:
lxc_init_interface[i] = vm_[i]
except KeyError:
lxc_init_interface[i] = profile[i]
return lxc_init_interface
def _get_profile(key, name, **kwargs):
if isinstance(name, dict):
profilename = name.pop('name', None)
return _get_profile(key, profilename, **name)
if name is None:
profile_match = {}
else:
profile_match = \
__salt__['config.get'](
'lxc.{1}:{0}'.format(name, key),
default=None,
merge='recurse'
)
if profile_match is None:
# No matching profile, make the profile an empty dict so that
# overrides can be applied below.
profile_match = {}
if not isinstance(profile_match, dict):
raise CommandExecutionError('lxc.{0} must be a dictionary'.format(key))
# Overlay the kwargs to override matched profile data
overrides = salt.utils.args.clean_kwargs(**copy.deepcopy(kwargs))
profile_match = salt.utils.dictupdate.update(
copy.deepcopy(profile_match),
overrides
)
return profile_match
def get_container_profile(name=None, **kwargs):
'''
.. versionadded:: 2015.5.0
Gather a pre-configured set of container configuration parameters. If no
arguments are passed, an empty profile is returned.
Profiles can be defined in the minion or master config files, or in pillar
or grains, and are loaded using :mod:`config.get
<salt.modules.config.get>`. The key under which LXC profiles must be
configured is ``lxc.container_profile.profile_name``. An example container
profile would be as follows:
.. code-block:: yaml
lxc.container_profile:
ubuntu:
template: ubuntu
backing: lvm
vgname: lxc
size: 1G
Parameters set in a profile can be overridden by passing additional
container creation arguments (such as the ones passed to :mod:`lxc.create
<salt.modules.lxc.create>`) to this function.
A profile can be defined either as the name of the profile, or a dictionary
of variable names and values. See the :ref:`LXC Tutorial
<tutorial-lxc-profiles>` for more information on how to use LXC profiles.
CLI Example:
.. code-block:: bash
salt-call lxc.get_container_profile centos
salt-call lxc.get_container_profile ubuntu template=ubuntu backing=overlayfs
'''
profile = _get_profile('container_profile', name, **kwargs)
return profile
def get_network_profile(name=None, **kwargs):
'''
.. versionadded:: 2015.5.0
Gather a pre-configured set of network configuration parameters. If no
arguments are passed, the following default profile is returned:
.. code-block:: python
{'eth0': {'link': 'br0', 'type': 'veth', 'flags': 'up'}}
Profiles can be defined in the minion or master config files, or in pillar
or grains, and are loaded using :mod:`config.get
<salt.modules.config.get>`. The key under which LXC profiles must be
configured is ``lxc.network_profile``. An example network profile would be
as follows:
.. code-block:: yaml
lxc.network_profile.centos:
eth0:
link: br0
type: veth
flags: up
To disable networking entirely:
.. code-block:: yaml
lxc.network_profile.centos:
eth0:
disable: true
Parameters set in a profile can be overridden by passing additional
arguments to this function.
A profile can be passed either as the name of the profile, or a
dictionary of variable names and values. See the :ref:`LXC Tutorial
<tutorial-lxc-profiles>` for more information on how to use network
profiles.
.. warning::
The ``ipv4``, ``ipv6``, ``gateway``, and ``link`` (bridge) settings in
network profiles will only work if the container doesn't redefine the
network configuration (for example in
``/etc/sysconfig/network-scripts/ifcfg-<interface_name>`` on
RHEL/CentOS, or ``/etc/network/interfaces`` on Debian/Ubuntu/etc.)
CLI Example:
.. code-block:: bash
salt-call lxc.get_network_profile default
'''
profile = _get_profile('network_profile', name, **kwargs)
return profile
def _rand_cpu_str(cpu):
'''
Return a random subset of cpus for the cpuset config
'''
cpu = int(cpu)
avail = __salt__['status.nproc']()
if cpu < avail:
return '0-{0}'.format(avail)
to_set = set()
while len(to_set) < cpu:
choice = random.randint(0, avail - 1)
if choice not in to_set:
to_set.add(six.text_type(choice))
return ','.join(sorted(to_set))
def _network_conf(conf_tuples=None, **kwargs):
'''
Network configuration defaults
network_profile
as for containers, we can either call this function
either with a network_profile dict or network profile name
in the kwargs
nic_opts
overrides or extra nics in the form {nic_name: {set: tings}
'''
nic = kwargs.get('network_profile', None)
ret = []
nic_opts = kwargs.get('nic_opts', {})
if nic_opts is None:
# coming from elsewhere
nic_opts = {}
if not conf_tuples:
conf_tuples = []
old = _get_veths(conf_tuples)
if not old:
old = {}
# if we have a profile name, get the profile and load the network settings
# this will obviously by default look for a profile called "eth0"
# or by what is defined in nic_opts
# and complete each nic settings by sane defaults
if nic and isinstance(nic, (six.string_types, dict)):
nicp = get_network_profile(nic)
else:
nicp = {}
if DEFAULT_NIC not in nicp:
nicp[DEFAULT_NIC] = {}
kwargs = copy.deepcopy(kwargs)
gateway = kwargs.pop('gateway', None)
bridge = kwargs.get('bridge', None)
if nic_opts:
for dev, args in six.iteritems(nic_opts):
ethx = nicp.setdefault(dev, {})
try:
ethx = salt.utils.dictupdate.update(ethx, args)
except AttributeError:
raise SaltInvocationError('Invalid nic_opts configuration')
ifs = [a for a in nicp]
ifs += [a for a in old if a not in nicp]
ifs.sort()
gateway_set = False
for dev in ifs:
args = nicp.get(dev, {})
opts = nic_opts.get(dev, {}) if nic_opts else {}
old_if = old.get(dev, {})
disable = opts.get('disable', args.get('disable', False))
if disable:
continue
mac = opts.get('mac',
opts.get('hwaddr',
args.get('mac',
args.get('hwaddr', ''))))
type_ = opts.get('type', args.get('type', ''))
flags = opts.get('flags', args.get('flags', ''))
link = opts.get('link', args.get('link', ''))
ipv4 = opts.get('ipv4', args.get('ipv4', ''))
ipv6 = opts.get('ipv6', args.get('ipv6', ''))
infos = salt.utils.odict.OrderedDict([
('lxc.network.type', {
'test': not type_,
'value': type_,
'old': old_if.get('lxc.network.type'),
'default': 'veth'}),
('lxc.network.name', {
'test': False,
'value': dev,
'old': dev,
'default': dev}),
('lxc.network.flags', {
'test': not flags,
'value': flags,
'old': old_if.get('lxc.network.flags'),
'default': 'up'}),
('lxc.network.link', {
'test': not link,
'value': link,
'old': old_if.get('lxc.network.link'),
'default': search_lxc_bridge()}),
('lxc.network.hwaddr', {
'test': not mac,
'value': mac,
'old': old_if.get('lxc.network.hwaddr'),
'default': salt.utils.network.gen_mac()}),
('lxc.network.ipv4', {
'test': not ipv4,
'value': ipv4,
'old': old_if.get('lxc.network.ipv4', ''),
'default': None}),
('lxc.network.ipv6', {
'test': not ipv6,
'value': ipv6,
'old': old_if.get('lxc.network.ipv6', ''),
'default': None})])
# for each parameter, if not explicitly set, the
# config value present in the LXC configuration should
# take precedence over the profile configuration
for info in list(infos.keys()):
bundle = infos[info]
if bundle['test']:
if bundle['old']:
bundle['value'] = bundle['old']
elif bundle['default']:
bundle['value'] = bundle['default']
for info, data in six.iteritems(infos):
if data['value']:
ret.append({info: data['value']})
for key, val in six.iteritems(args):
if key == 'link' and bridge:
val = bridge
val = opts.get(key, val)
if key in [
'type', 'flags', 'name',
'gateway', 'mac', 'link', 'ipv4', 'ipv6'
]:
continue
ret.append({'lxc.network.{0}'.format(key): val})
# gateway (in automode) must be appended following network conf !
if not gateway:
gateway = args.get('gateway', None)
if gateway is not None and not gateway_set:
ret.append({'lxc.network.ipv4.gateway': gateway})
# only one network gateway ;)
gateway_set = True
# normally, this won't happen
# set the gateway if specified even if we did
# not managed the network underlying
if gateway is not None and not gateway_set:
ret.append({'lxc.network.ipv4.gateway': gateway})
# only one network gateway ;)
gateway_set = True
new = _get_veths(ret)
# verify that we did not loose the mac settings
for iface in [a for a in new]:
ndata = new[iface]
nmac = ndata.get('lxc.network.hwaddr', '')
ntype = ndata.get('lxc.network.type', '')
omac, otype = '', ''
if iface in old:
odata = old[iface]
omac = odata.get('lxc.network.hwaddr', '')
otype = odata.get('lxc.network.type', '')
# default for network type is setted here
# attention not to change the network type
# without a good and explicit reason to.
if otype and not ntype:
ntype = otype
if not ntype:
ntype = 'veth'
new[iface]['lxc.network.type'] = ntype
if omac and not nmac:
new[iface]['lxc.network.hwaddr'] = omac
ret = []
for val in six.itervalues(new):
for row in val:
ret.append(salt.utils.odict.OrderedDict([(row, val[row])]))
# on old versions of lxc, still support the gateway auto mode
# if we didn't explicitly say no to
# (lxc.network.ipv4.gateway: auto)
if _LooseVersion(version()) <= _LooseVersion('1.0.7') and \
True not in ['lxc.network.ipv4.gateway' in a for a in ret] and \
True in ['lxc.network.ipv4' in a for a in ret]:
ret.append({'lxc.network.ipv4.gateway': 'auto'})
return ret
def _get_lxc_default_data(**kwargs):
kwargs = copy.deepcopy(kwargs)
ret = {}
for k in ['utsname', 'rootfs']:
val = kwargs.get(k, None)
if val is not None:
ret['lxc.{0}'.format(k)] = val
autostart = kwargs.get('autostart')
# autostart can have made in kwargs, but with the None
# value which is invalid, we need an explicit boolean
# autostart = on is the default.
if autostart is None:
autostart = True
# we will set the regular lxc marker to restart container at
# machine (re)boot only if we did not explicitly ask
# not to touch to the autostart settings via
# autostart == 'keep'
if autostart != 'keep':
if autostart:
ret['lxc.start.auto'] = '1'
else:
ret['lxc.start.auto'] = '0'
memory = kwargs.get('memory')
if memory is not None:
# converting the config value from MB to bytes
ret['lxc.cgroup.memory.limit_in_bytes'] = memory * 1024 * 1024
cpuset = kwargs.get('cpuset')
if cpuset:
ret['lxc.cgroup.cpuset.cpus'] = cpuset
cpushare = kwargs.get('cpushare')
cpu = kwargs.get('cpu')
if cpushare:
ret['lxc.cgroup.cpu.shares'] = cpushare
if cpu and not cpuset:
ret['lxc.cgroup.cpuset.cpus'] = _rand_cpu_str(cpu)
return ret
def _config_list(conf_tuples=None, only_net=False, **kwargs):
'''
Return a list of dicts from the salt level configurations
conf_tuples
_LXCConfig compatible list of entries which can contain
- string line
- tuple (lxc config param,value)
- dict of one entry: {lxc config param: value)
only_net
by default we add to the tuples a reflection of both
the real config if avalaible and a certain amount of
default values like the cpu parameters, the memory
and etc.
On the other hand, we also no matter the case reflect
the network configuration computed from the actual config if
available and given values.
if no_default_loads is set, we will only
reflect the network configuration back to the conf tuples
list
'''
# explicit cast
only_net = bool(only_net)
if not conf_tuples:
conf_tuples = []
kwargs = copy.deepcopy(kwargs)
ret = []
if not only_net:
default_data = _get_lxc_default_data(**kwargs)
for k, val in six.iteritems(default_data):
ret.append({k: val})
net_datas = _network_conf(conf_tuples=conf_tuples, **kwargs)
ret.extend(net_datas)
return ret
def _get_veths(net_data):
'''
Parse the nic setup inside lxc conf tuples back to a dictionary indexed by
network interface
'''
if isinstance(net_data, dict):
net_data = list(net_data.items())
nics = salt.utils.odict.OrderedDict()
current_nic = salt.utils.odict.OrderedDict()
no_names = True
for item in net_data:
if item and isinstance(item, dict):
item = list(item.items())[0]
# skip LXC configuration comment lines, and play only with tuples conf
elif isinstance(item, six.string_types):
# deal with reflection of commented lxc configs
sitem = item.strip()
if sitem.startswith('#') or not sitem:
continue
elif '=' in item:
item = tuple([a.strip() for a in item.split('=', 1)])
if item[0] == 'lxc.network.type':
current_nic = salt.utils.odict.OrderedDict()
if item[0] == 'lxc.network.name':
no_names = False
nics[item[1].strip()] = current_nic
current_nic[item[0].strip()] = item[1].strip()
# if not ethernet card name has been collected, assuming we collected
# data for eth0
if no_names and current_nic:
nics[DEFAULT_NIC] = current_nic
return nics
class _LXCConfig(object):
'''
LXC configuration data
'''
pattern = re.compile(r'^(\S+)(\s*)(=)(\s*)(.*)')
non_interpretable_pattern = re.compile(r'^((#.*)|(\s*))$')
def __init__(self, **kwargs):
kwargs = copy.deepcopy(kwargs)
self.name = kwargs.pop('name', None)
path = get_root_path(kwargs.get('path', None))
self.data = []
if self.name:
self.path = os.path.join(path, self.name, 'config')
if os.path.isfile(self.path):
with salt.utils.files.fopen(self.path) as fhr:
for line in salt.utils.data.decode(fhr.readlines()):
match = self.pattern.findall((line.strip()))
if match:
self.data.append((match[0][0], match[0][-1]))
match = self.non_interpretable_pattern.findall(
(line.strip()))
if match:
self.data.append(('', match[0][0]))
else:
self.path = None
def _replace(key, val):
if val:
self._filter_data(key)
self.data.append((key, val))
default_data = _get_lxc_default_data(**kwargs)
for key, val in six.iteritems(default_data):
_replace(key, val)
old_net = self._filter_data('lxc.network')
net_datas = _network_conf(conf_tuples=old_net, **kwargs)
if net_datas:
for row in net_datas:
self.data.extend(list(row.items()))
# be sure to reset harmful settings
for idx in ['lxc.cgroup.memory.limit_in_bytes']:
if not default_data.get(idx):
self._filter_data(idx)
def as_string(self):
chunks = ('{0[0]}{1}{0[1]}'.format(item, (' = ' if item[0] else '')) for item in self.data)
return '\n'.join(chunks) + '\n'
def write(self):
if self.path:
content = self.as_string()
# 2 step rendering to be sure not to open/wipe the config
# before as_string succeeds.
with salt.utils.files.fopen(self.path, 'w') as fic:
fic.write(salt.utils.stringutils.to_str(content))
fic.flush()
def tempfile(self):
# this might look like the function name is shadowing the
# module, but it's not since the method belongs to the class
ntf = tempfile.NamedTemporaryFile()
ntf.write(self.as_string())
ntf.flush()
return ntf
def _filter_data(self, pattern):
'''
Removes parameters which match the pattern from the config data
'''
removed = []
filtered = []
for param in self.data:
if not param[0].startswith(pattern):
filtered.append(param)
else:
removed.append(param)
self.data = filtered
return removed
def _get_base(**kwargs):
'''
If the needed base does not exist, then create it, if it does exist
create nothing and return the name of the base lxc container so
it can be cloned.
'''
profile = get_container_profile(copy.deepcopy(kwargs.get('profile')))
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, _marker)
profile_match = profile.pop(key, default)
# let kwarg overrides be the preferred choice
if kw_overrides_match is _marker:
return profile_match
return kw_overrides_match
template = select('template')
image = select('image')
vgname = select('vgname')
path = kwargs.get('path', None)
# remove the above three variables from kwargs, if they exist, to avoid
# duplicates if create() is invoked below.
for param in ('path', 'image', 'vgname', 'template'):
kwargs.pop(param, None)
if image:
proto = _urlparse(image).scheme
img_tar = __salt__['cp.cache_file'](image)
img_name = os.path.basename(img_tar)
hash_ = salt.utils.hashutils.get_hash(
img_tar,
__salt__['config.get']('hash_type'))
name = '__base_{0}_{1}_{2}'.format(proto, img_name, hash_)
if not exists(name, path=path):
create(name, template=template, image=image,
path=path, vgname=vgname, **kwargs)
if vgname:
rootfs = os.path.join('/dev', vgname, name)
edit_conf(info(name, path=path)['config'],
out_format='commented', **{'lxc.rootfs': rootfs})
return name
elif template:
name = '__base_{0}'.format(template)
if not exists(name, path=path):
create(name, template=template, image=image, path=path,
vgname=vgname, **kwargs)
if vgname:
rootfs = os.path.join('/dev', vgname, name)
edit_conf(info(name, path=path)['config'],
out_format='commented', **{'lxc.rootfs': rootfs})
return name
return ''
def init(name,
config=None,
cpuset=None,
cpushare=None,
memory=None,
profile=None,
network_profile=None,
nic_opts=None,
cpu=None,
autostart=True,
password=None,
password_encrypted=None,
users=None,
dnsservers=None,
searchdomains=None,
bridge=None,
gateway=None,
pub_key=None,
priv_key=None,
force_install=False,
unconditional_install=False,
bootstrap_delay=None,
bootstrap_args=None,
bootstrap_shell=None,
bootstrap_url=None,
**kwargs):
'''
Initialize a new container.
This is a partial idempotent function as if it is already provisioned, we
will reset a bit the lxc configuration file but much of the hard work will
be escaped as markers will prevent re-execution of harmful tasks.
name
Name of the container
image
A tar archive to use as the rootfs for the container. Conflicts with
the ``template`` argument.
cpus
Select a random number of cpu cores and assign it to the cpuset, if the
cpuset option is set then this option will be ignored
cpuset
Explicitly define the cpus this container will be bound to
cpushare
cgroups cpu shares
autostart
autostart container on reboot
memory
cgroups memory limit, in MB
.. versionchanged:: 2015.5.0
If no value is passed, no limit is set. In earlier Salt versions,
not passing this value causes a 1024MB memory limit to be set, and
it was necessary to pass ``memory=0`` to set no limit.
gateway
the ipv4 gateway to use
the default does nothing more than lxcutils does
bridge
the bridge to use
the default does nothing more than lxcutils does
network_profile
Network profile to use for the container
.. versionadded:: 2015.5.0
nic_opts
Extra options for network interfaces, will override
``{"eth0": {"hwaddr": "aa:bb:cc:dd:ee:ff", "ipv4": "10.1.1.1", "ipv6": "2001:db8::ff00:42:8329"}}``
or
``{"eth0": {"hwaddr": "aa:bb:cc:dd:ee:ff", "ipv4": "10.1.1.1/24", "ipv6": "2001:db8::ff00:42:8329"}}``
users
Users for which the password defined in the ``password`` param should
be set. Can be passed as a comma separated list or a python list.
Defaults to just the ``root`` user.
password
Set the initial password for the users defined in the ``users``
parameter
password_encrypted : False
Set to ``True`` to denote a password hash instead of a plaintext
password
.. versionadded:: 2015.5.0
profile
A LXC profile (defined in config or pillar).
This can be either a real profile mapping or a string
to retrieve it in configuration
start
Start the newly-created container
dnsservers
list of dns servers to set in the container, default [] (no setting)
seed
Seed the container with the minion config. Default: ``True``
install
If salt-minion is not already installed, install it. Default: ``True``
config
Optional config parameters. By default, the id is set to
the name of the container.
master
salt master (default to minion's master)
master_port
salt master port (default to minion's master port)
pub_key
Explicit public key to preseed the minion with (optional).
This can be either a filepath or a string representing the key
priv_key
Explicit private key to preseed the minion with (optional).
This can be either a filepath or a string representing the key
approve_key
If explicit preseeding is not used;
Attempt to request key approval from the master. Default: ``True``
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
clone_from
Original from which to use a clone operation to create the container.
Default: ``None``
bootstrap_delay
Delay in seconds between end of container creation and bootstrapping.
Useful when waiting for container to obtain a DHCP lease.
.. versionadded:: 2015.5.0
bootstrap_url
See lxc.bootstrap
bootstrap_shell
See lxc.bootstrap
bootstrap_args
See lxc.bootstrap
force_install
Force installation even if salt-minion is detected,
this is the way to run vendor bootstrap scripts even
if a salt minion is already present in the container
unconditional_install
Run the script even if the container seems seeded
CLI Example:
.. code-block:: bash
salt 'minion' lxc.init name [cpuset=cgroups_cpuset] \\
[cpushare=cgroups_cpushare] [memory=cgroups_memory] \\
[nic=nic_profile] [profile=lxc_profile] \\
[nic_opts=nic_opts] [start=(True|False)] \\
[seed=(True|False)] [install=(True|False)] \\
[config=minion_config] [approve_key=(True|False) \\
[clone_from=original] [autostart=True] \\
[priv_key=/path_or_content] [pub_key=/path_or_content] \\
[bridge=lxcbr0] [gateway=10.0.3.1] \\
[dnsservers[dns1,dns2]] \\
[users=[foo]] [password='secret'] \\
[password_encrypted=(True|False)]
'''
ret = {'name': name,
'changes': {}}
profile = get_container_profile(copy.deepcopy(profile))
if not network_profile:
network_profile = profile.get('network_profile')
if not network_profile:
network_profile = DEFAULT_NIC
# Changes is a pointer to changes_dict['init']. This method is used so that
# we can have a list of changes as they are made, providing an ordered list
# of things that were changed.
changes_dict = {'init': []}
changes = changes_dict.get('init')
if users is None:
users = []
dusers = ['root']
for user in dusers:
if user not in users:
users.append(user)
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, _marker)
profile_match = profile.pop(key, default)
# let kwarg overrides be the preferred choice
if kw_overrides_match is _marker:
return profile_match
return kw_overrides_match
path = select('path')
bpath = get_root_path(path)
state_pre = state(name, path=path)
tvg = select('vgname')
vgname = tvg if tvg else __salt__['config.get']('lxc.vgname')
start_ = select('start', True)
autostart = select('autostart', autostart)
seed = select('seed', True)
install = select('install', True)
seed_cmd = select('seed_cmd')
salt_config = _get_salt_config(config, **kwargs)
approve_key = select('approve_key', True)
clone_from = select('clone_from')
# If using a volume group then set up to make snapshot cow clones
if vgname and not clone_from:
try:
kwargs['vgname'] = vgname
clone_from = _get_base(profile=profile, **kwargs)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = exc.strerror
if changes:
ret['changes'] = changes_dict
return ret
if not kwargs.get('snapshot') is False:
kwargs['snapshot'] = True
does_exist = exists(name, path=path)
to_reboot = False
remove_seed_marker = False
if does_exist:
pass
elif clone_from:
remove_seed_marker = True
try:
clone(name, clone_from, profile=profile, **kwargs)
changes.append({'create': 'Container cloned'})
except (SaltInvocationError, CommandExecutionError) as exc:
if 'already exists' in exc.strerror:
changes.append({'create': 'Container already exists'})
else:
ret['result'] = False
ret['comment'] = exc.strerror
if changes:
ret['changes'] = changes_dict
return ret
cfg = _LXCConfig(name=name, network_profile=network_profile,
nic_opts=nic_opts, bridge=bridge, path=path,
gateway=gateway, autostart=autostart,
cpuset=cpuset, cpushare=cpushare, memory=memory)
old_chunks = read_conf(cfg.path, out_format='commented')
cfg.write()
chunks = read_conf(cfg.path, out_format='commented')
if old_chunks != chunks:
to_reboot = True
else:
remove_seed_marker = True
cfg = _LXCConfig(network_profile=network_profile,
nic_opts=nic_opts, cpuset=cpuset, path=path,
bridge=bridge, gateway=gateway,
autostart=autostart,
cpushare=cpushare, memory=memory)
with cfg.tempfile() as cfile:
try:
create(name, config=cfile.name, profile=profile, **kwargs)
changes.append({'create': 'Container created'})
except (SaltInvocationError, CommandExecutionError) as exc:
if 'already exists' in exc.strerror:
changes.append({'create': 'Container already exists'})
else:
ret['comment'] = exc.strerror
if changes:
ret['changes'] = changes_dict
return ret
cpath = os.path.join(bpath, name, 'config')
old_chunks = []
if os.path.exists(cpath):
old_chunks = read_conf(cpath, out_format='commented')
new_cfg = _config_list(conf_tuples=old_chunks,
cpu=cpu,
network_profile=network_profile,
nic_opts=nic_opts, bridge=bridge,
cpuset=cpuset, cpushare=cpushare,
memory=memory)
if new_cfg:
edit_conf(cpath, out_format='commented', lxc_config=new_cfg)
chunks = read_conf(cpath, out_format='commented')
if old_chunks != chunks:
to_reboot = True
# last time to be sure any of our property is correctly applied
cfg = _LXCConfig(name=name, network_profile=network_profile,
nic_opts=nic_opts, bridge=bridge, path=path,
gateway=gateway, autostart=autostart,
cpuset=cpuset, cpushare=cpushare, memory=memory)
old_chunks = []
if os.path.exists(cfg.path):
old_chunks = read_conf(cfg.path, out_format='commented')
cfg.write()
chunks = read_conf(cfg.path, out_format='commented')
if old_chunks != chunks:
changes.append({'config': 'Container configuration updated'})
to_reboot = True
if to_reboot:
try:
stop(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
if changes:
ret['changes'] = changes_dict
return ret
if not does_exist or (does_exist and state(name, path=path) != 'running'):
try:
start(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
if changes:
ret['changes'] = changes_dict
return ret
if remove_seed_marker:
run(name,
'rm -f \'{0}\''.format(SEED_MARKER),
path=path,
chroot_fallback=False,
python_shell=False)
# set the default user/password, only the first time
if ret.get('result', True) and password:
gid = '/.lxc.initial_pass'
gids = [gid,
'/lxc.initial_pass',
'/.lxc.{0}.initial_pass'.format(name)]
if not any(retcode(name,
'test -e "{0}"'.format(x),
chroot_fallback=True,
path=path,
ignore_retcode=True) == 0
for x in gids):
# think to touch the default user generated by default templates
# which has a really unsecure passwords...
# root is defined as a member earlier in the code
for default_user in ['ubuntu']:
if (
default_user not in users and
retcode(name,
'id {0}'.format(default_user),
python_shell=False,
path=path,
chroot_fallback=True,
ignore_retcode=True) == 0
):
users.append(default_user)
for user in users:
try:
cret = set_password(name,
users=[user],
path=path,
password=password,
encrypted=password_encrypted)
except (SaltInvocationError, CommandExecutionError) as exc:
msg = '{0}: Failed to set password'.format(
user) + exc.strerror
# only hardfail in unrecoverable situation:
# root cannot be setted up
if user == 'root':
ret['comment'] = msg
ret['result'] = False
else:
log.debug(msg)
if ret.get('result', True):
changes.append({'password': 'Password(s) updated'})
if retcode(name,
('sh -c \'touch "{0}"; test -e "{0}"\''
.format(gid)),
path=path,
chroot_fallback=True,
ignore_retcode=True) != 0:
ret['comment'] = 'Failed to set password marker'
changes[-1]['password'] += '. ' + ret['comment'] + '.'
ret['result'] = False
# set dns servers if any, only the first time
if ret.get('result', True) and dnsservers:
# retro compatibility, test also old markers
gid = '/.lxc.initial_dns'
gids = [gid,
'/lxc.initial_dns',
'/lxc.{0}.initial_dns'.format(name)]
if not any(retcode(name,
'test -e "{0}"'.format(x),
chroot_fallback=True,
path=path,
ignore_retcode=True) == 0
for x in gids):
try:
set_dns(name,
path=path,
dnsservers=dnsservers,
searchdomains=searchdomains)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Failed to set DNS: ' + exc.strerror
ret['result'] = False
else:
changes.append({'dns': 'DNS updated'})
if retcode(name,
('sh -c \'touch "{0}"; test -e "{0}"\''
.format(gid)),
chroot_fallback=True,
path=path,
ignore_retcode=True) != 0:
ret['comment'] = 'Failed to set DNS marker'
changes[-1]['dns'] += '. ' + ret['comment'] + '.'
ret['result'] = False
# retro compatibility, test also old markers
if remove_seed_marker:
run(name,
'rm -f \'{0}\''.format(SEED_MARKER),
path=path,
python_shell=False)
gid = '/.lxc.initial_seed'
gids = [gid, '/lxc.initial_seed']
if (
any(retcode(name,
'test -e {0}'.format(x),
path=path,
chroot_fallback=True,
ignore_retcode=True) == 0
for x in gids) or not ret.get('result', True)
):
pass
elif seed or seed_cmd:
if seed:
try:
result = bootstrap(
name, config=salt_config, path=path,
approve_key=approve_key,
pub_key=pub_key, priv_key=priv_key,
install=install,
force_install=force_install,
unconditional_install=unconditional_install,
bootstrap_delay=bootstrap_delay,
bootstrap_url=bootstrap_url,
bootstrap_shell=bootstrap_shell,
bootstrap_args=bootstrap_args)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Bootstrap failed: ' + exc.strerror
ret['result'] = False
else:
if not result:
ret['comment'] = ('Bootstrap failed, see minion log for '
'more information')
ret['result'] = False
else:
changes.append(
{'bootstrap': 'Container successfully bootstrapped'}
)
elif seed_cmd:
try:
result = __salt__[seed_cmd](info(name, path=path)['rootfs'],
name,
salt_config)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = ('Bootstrap via seed_cmd \'{0}\' failed: {1}'
.format(seed_cmd, exc.strerror))
ret['result'] = False
else:
if not result:
ret['comment'] = ('Bootstrap via seed_cmd \'{0}\' failed, '
'see minion log for more information '
.format(seed_cmd))
ret['result'] = False
else:
changes.append(
{'bootstrap': 'Container successfully bootstrapped '
'using seed_cmd \'{0}\''
.format(seed_cmd)}
)
if ret.get('result', True) and not start_:
try:
stop(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
ret['result'] = False
state_post = state(name, path=path)
if state_pre != state_post:
changes.append({'state': {'old': state_pre, 'new': state_post}})
if ret.get('result', True):
ret['comment'] = ('Container \'{0}\' successfully initialized'
.format(name))
ret['result'] = True
if changes:
ret['changes'] = changes_dict
return ret
def cloud_init(name, vm_=None, **kwargs):
'''
Thin wrapper to lxc.init to be used from the saltcloud lxc driver
name
Name of the container
may be None and then guessed from saltcloud mapping
`vm_`
saltcloud mapping defaults for the vm
CLI Example:
.. code-block:: bash
salt '*' lxc.cloud_init foo
'''
init_interface = cloud_init_interface(name, vm_, **kwargs)
name = init_interface.pop('name', name)
return init(name, **init_interface)
def images(dist=None):
'''
.. versionadded:: 2015.5.0
List the available images for LXC's ``download`` template.
dist : None
Filter results to a single Linux distribution
CLI Examples:
.. code-block:: bash
salt myminion lxc.images
salt myminion lxc.images dist=centos
'''
out = __salt__['cmd.run_stdout'](
'lxc-create -n __imgcheck -t download -- --list',
ignore_retcode=True
)
if 'DIST' not in out:
raise CommandExecutionError(
'Unable to run the \'download\' template script. Is it installed?'
)
ret = {}
passed_header = False
for line in out.splitlines():
try:
distro, release, arch, variant, build_time = line.split()
except ValueError:
continue
if not passed_header:
if distro == 'DIST':
passed_header = True
continue
dist_list = ret.setdefault(distro, [])
dist_list.append({
'release': release,
'arch': arch,
'variant': variant,
'build_time': build_time,
})
if dist is not None:
return dict([(dist, ret.get(dist, []))])
return ret
def templates():
'''
.. versionadded:: 2015.5.0
List the available LXC template scripts installed on the minion
CLI Examples:
.. code-block:: bash
salt myminion lxc.templates
'''
try:
template_scripts = os.listdir('/usr/share/lxc/templates')
except OSError:
return []
else:
return [x[4:] for x in template_scripts if x.startswith('lxc-')]
def _after_ignition_network_profile(cmd,
ret,
name,
network_profile,
path,
nic_opts):
_clear_context()
if ret['retcode'] == 0 and exists(name, path=path):
if network_profile:
network_changes = apply_network_profile(name,
network_profile,
path=path,
nic_opts=nic_opts)
if network_changes:
log.info(
'Network changes from applying network profile \'%s\' '
'to newly-created container \'%s\':\n%s',
network_profile, name, network_changes
)
c_state = state(name, path=path)
return {'result': True,
'state': {'old': None, 'new': c_state}}
else:
if exists(name, path=path):
# destroy the container if it was partially created
cmd = 'lxc-destroy'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0}'.format(name)
__salt__['cmd.retcode'](cmd, python_shell=False)
raise CommandExecutionError(
'Container could not be created with cmd \'{0}\': {1}'
.format(cmd, ret['stderr'])
)
def create(name,
config=None,
profile=None,
network_profile=None,
nic_opts=None,
**kwargs):
'''
Create a new container.
name
Name of the container
config
The config file to use for the container. Defaults to system-wide
config (usually in /etc/lxc/lxc.conf).
profile
Profile to use in container creation (see
:mod:`lxc.get_container_profile
<salt.modules.lxc.get_container_profile>`). Values in a profile will be
overridden by the **Container Creation Arguments** listed below.
network_profile
Network profile to use for container
.. versionadded:: 2015.5.0
**Container Creation Arguments**
template
The template to use. For example, ``ubuntu`` or ``fedora``.
For a full list of available templates, check out
the :mod:`lxc.templates <salt.modules.lxc.templates>` function.
Conflicts with the ``image`` argument.
.. note::
The ``download`` template requires the following three parameters
to be defined in ``options``:
* **dist** - The name of the distribution
* **release** - Release name/version
* **arch** - Architecture of the container
The available images can be listed using the :mod:`lxc.images
<salt.modules.lxc.images>` function.
options
Template-specific options to pass to the lxc-create command. These
correspond to the long options (ones beginning with two dashes) that
the template script accepts. For example:
.. code-block:: bash
options='{"dist": "centos", "release": "6", "arch": "amd64"}'
For available template options, refer to the lxc template scripts
which are ususally located under ``/usr/share/lxc/templates``,
or run ``lxc-create -t <template> -h``.
image
A tar archive to use as the rootfs for the container. Conflicts with
the ``template`` argument.
backing
The type of storage to use. Set to ``lvm`` to use an LVM group.
Defaults to filesystem within /var/lib/lxc.
fstype
Filesystem type to use on LVM logical volume
size : 1G
Size of the volume to create. Only applicable if ``backing=lvm``.
vgname : lxc
Name of the LVM volume group in which to create the volume for this
container. Only applicable if ``backing=lvm``.
lvname
Name of the LVM logical volume in which to create the volume for this
container. Only applicable if ``backing=lvm``.
thinpool
Name of a pool volume that will be used for thin-provisioning this
container. Only applicable if ``backing=lvm``.
nic_opts
give extra opts overriding network profile values
path
parent path for the container creation (default: /var/lib/lxc)
zfsroot
Name of the ZFS root in which to create the volume for this container.
Only applicable if ``backing=zfs``. (default: tank/lxc)
.. versionadded:: 2015.8.0
'''
# Required params for 'download' template
download_template_deps = ('dist', 'release', 'arch')
cmd = 'lxc-create -n {0}'.format(name)
profile = get_container_profile(copy.deepcopy(profile))
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, None)
profile_match = profile.pop(key, default)
# Return the profile match if the the kwarg match was None, as the
# lxc.present state will pass these kwargs set to None by default.
if kw_overrides_match is None:
return profile_match
return kw_overrides_match
path = select('path')
if exists(name, path=path):
raise CommandExecutionError(
'Container \'{0}\' already exists'.format(name)
)
tvg = select('vgname')
vgname = tvg if tvg else __salt__['config.get']('lxc.vgname')
# The 'template' and 'image' params conflict
template = select('template')
image = select('image')
if template and image:
raise SaltInvocationError(
'Only one of \'template\' and \'image\' is permitted'
)
elif not any((template, image, profile)):
raise SaltInvocationError(
'At least one of \'template\', \'image\', and \'profile\' is '
'required'
)
options = select('options') or {}
backing = select('backing')
if vgname and not backing:
backing = 'lvm'
lvname = select('lvname')
thinpool = select('thinpool')
fstype = select('fstype')
size = select('size', '1G')
zfsroot = select('zfsroot')
if backing in ('dir', 'overlayfs', 'btrfs', 'zfs'):
fstype = None
size = None
# some backends won't support some parameters
if backing in ('aufs', 'dir', 'overlayfs', 'btrfs'):
lvname = vgname = thinpool = None
if image:
img_tar = __salt__['cp.cache_file'](image)
template = os.path.join(
os.path.dirname(salt.__file__),
'templates',
'lxc',
'salt_tarball')
options['imgtar'] = img_tar
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
if not os.path.exists(path):
os.makedirs(path)
if config:
cmd += ' -f {0}'.format(config)
if template:
cmd += ' -t {0}'.format(template)
if backing:
backing = backing.lower()
cmd += ' -B {0}'.format(backing)
if backing in ('zfs',):
if zfsroot:
cmd += ' --zfsroot {0}'.format(zfsroot)
if backing in ('lvm',):
if lvname:
cmd += ' --lvname {0}'.format(lvname)
if vgname:
cmd += ' --vgname {0}'.format(vgname)
if thinpool:
cmd += ' --thinpool {0}'.format(thinpool)
if backing not in ('dir', 'overlayfs'):
if fstype:
cmd += ' --fstype {0}'.format(fstype)
if size:
cmd += ' --fssize {0}'.format(size)
if options:
if template == 'download':
missing_deps = [x for x in download_template_deps
if x not in options]
if missing_deps:
raise SaltInvocationError(
'Missing params in \'options\' dict: {0}'
.format(', '.join(missing_deps))
)
cmd += ' --'
for key, val in six.iteritems(options):
cmd += ' --{0} {1}'.format(key, val)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
# please do not merge extra conflicting stuff
# inside those two line (ret =, return)
return _after_ignition_network_profile(cmd,
ret,
name,
network_profile,
path,
nic_opts)
def clone(name,
orig,
profile=None,
network_profile=None,
nic_opts=None,
**kwargs):
'''
Create a new container as a clone of another container
name
Name of the container
orig
Name of the original container to be cloned
profile
Profile to use in container cloning (see
:mod:`lxc.get_container_profile
<salt.modules.lxc.get_container_profile>`). Values in a profile will be
overridden by the **Container Cloning Arguments** listed below.
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
**Container Cloning Arguments**
snapshot
Use Copy On Write snapshots (LVM)
size : 1G
Size of the volume to create. Only applicable if ``backing=lvm``.
backing
The type of storage to use. Set to ``lvm`` to use an LVM group.
Defaults to filesystem within /var/lib/lxc.
network_profile
Network profile to use for container
.. versionadded:: 2015.8.0
nic_opts
give extra opts overriding network profile values
.. versionadded:: 2015.8.0
CLI Examples:
.. code-block:: bash
salt '*' lxc.clone myclone orig=orig_container
salt '*' lxc.clone myclone orig=orig_container snapshot=True
'''
profile = get_container_profile(copy.deepcopy(profile))
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, None)
profile_match = profile.pop(key, default)
# let kwarg overrides be the preferred choice
if kw_overrides_match is None:
return profile_match
return kw_overrides_match
path = select('path')
if exists(name, path=path):
raise CommandExecutionError(
'Container \'{0}\' already exists'.format(name)
)
_ensure_exists(orig, path=path)
if state(orig, path=path) != 'stopped':
raise CommandExecutionError(
'Container \'{0}\' must be stopped to be cloned'.format(orig)
)
backing = select('backing')
snapshot = select('snapshot')
if backing in ('dir',):
snapshot = False
if not snapshot:
snapshot = ''
else:
snapshot = '-s'
size = select('size', '1G')
if backing in ('dir', 'overlayfs', 'btrfs'):
size = None
# LXC commands and options changed in 2.0 - CF issue #34086 for details
if _LooseVersion(version()) >= _LooseVersion('2.0'):
# https://linuxcontainers.org/lxc/manpages//man1/lxc-copy.1.html
cmd = 'lxc-copy'
cmd += ' {0} -n {1} -N {2}'.format(snapshot, orig, name)
else:
# https://linuxcontainers.org/lxc/manpages//man1/lxc-clone.1.html
cmd = 'lxc-clone'
cmd += ' {0} -o {1} -n {2}'.format(snapshot, orig, name)
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
if not os.path.exists(path):
os.makedirs(path)
if backing:
backing = backing.lower()
cmd += ' -B {0}'.format(backing)
if backing not in ('dir', 'overlayfs'):
if size:
cmd += ' -L {0}'.format(size)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
# please do not merge extra conflicting stuff
# inside those two line (ret =, return)
return _after_ignition_network_profile(cmd,
ret,
name,
network_profile,
path,
nic_opts)
def ls_(active=None, cache=True, path=None):
'''
Return a list of the containers available on the minion
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
active
If ``True``, return only active (i.e. running) containers
.. versionadded:: 2015.5.0
CLI Example:
.. code-block:: bash
salt '*' lxc.ls
salt '*' lxc.ls active=True
'''
contextvar = 'lxc.ls{0}'.format(path)
if active:
contextvar += '.active'
if cache and (contextvar in __context__):
return __context__[contextvar]
else:
ret = []
cmd = 'lxc-ls'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
if active:
cmd += ' --active'
output = __salt__['cmd.run_stdout'](cmd, python_shell=False)
for line in output.splitlines():
ret.extend(line.split())
__context__[contextvar] = ret
return ret
def list_(extra=False, limit=None, path=None):
'''
List containers classified by state
extra
Also get per-container specific info. This will change the return data.
Instead of returning a list of containers, a dictionary of containers
and each container's output from :mod:`lxc.info
<salt.modules.lxc.info>`.
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
limit
Return output matching a specific state (**frozen**, **running**, or
**stopped**).
.. versionadded:: 2015.5.0
CLI Examples:
.. code-block:: bash
salt '*' lxc.list
salt '*' lxc.list extra=True
salt '*' lxc.list limit=running
'''
ctnrs = ls_(path=path)
if extra:
stopped = {}
frozen = {}
running = {}
else:
stopped = []
frozen = []
running = []
ret = {'running': running,
'stopped': stopped,
'frozen': frozen}
for container in ctnrs:
cmd = 'lxc-info'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0}'.format(container)
c_info = __salt__['cmd.run'](
cmd,
python_shell=False,
output_loglevel='debug'
)
c_state = None
for line in c_info.splitlines():
stat = line.split(':')
if stat[0] in ('State', 'state'):
c_state = stat[1].strip()
break
if not c_state or (limit is not None and c_state.lower() != limit):
continue
if extra:
infos = info(container, path=path)
method = 'update'
value = {container: infos}
else:
method = 'append'
value = container
if c_state == 'STOPPED':
getattr(stopped, method)(value)
continue
if c_state == 'FROZEN':
getattr(frozen, method)(value)
continue
if c_state == 'RUNNING':
getattr(running, method)(value)
continue
if limit is not None:
return ret.get(limit, {} if extra else [])
return ret
def _change_state(cmd,
name,
expected,
stdin=_marker,
stdout=_marker,
stderr=_marker,
with_communicate=_marker,
use_vt=_marker,
path=None):
pre = state(name, path=path)
if pre == expected:
return {'result': True,
'state': {'old': expected, 'new': expected},
'comment': 'Container \'{0}\' already {1}'
.format(name, expected)}
if cmd == 'lxc-destroy':
# Kill the container first
scmd = 'lxc-stop'
if path:
scmd += ' -P {0}'.format(pipes.quote(path))
scmd += ' -k -n {0}'.format(name)
__salt__['cmd.run'](scmd,
python_shell=False)
if path and ' -P ' not in cmd:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0}'.format(name)
# certain lxc commands need to be taken with care (lxc-start)
# as te command itself mess with double forks; we must not
# communicate with it, but just wait for the exit status
pkwargs = {'python_shell': False,
'redirect_stderr': True,
'with_communicate': with_communicate,
'use_vt': use_vt,
'stdin': stdin,
'stdout': stdout}
for i in [a for a in pkwargs]:
val = pkwargs[i]
if val is _marker:
pkwargs.pop(i, None)
_cmdout = __salt__['cmd.run_all'](cmd, **pkwargs)
if _cmdout['retcode'] != 0:
raise CommandExecutionError(
'Error changing state for container \'{0}\' using command '
'\'{1}\': {2}'.format(name, cmd, _cmdout['stdout'])
)
if expected is not None:
# some commands do not wait, so we will
rcmd = 'lxc-wait'
if path:
rcmd += ' -P {0}'.format(pipes.quote(path))
rcmd += ' -n {0} -s {1}'.format(name, expected.upper())
__salt__['cmd.run'](rcmd, python_shell=False, timeout=30)
_clear_context()
post = state(name, path=path)
ret = {'result': post == expected,
'state': {'old': pre, 'new': post}}
return ret
def _ensure_exists(name, path=None):
'''
Raise an exception if the container does not exist
'''
if not exists(name, path=path):
raise CommandExecutionError(
'Container \'{0}\' does not exist'.format(name)
)
def _ensure_running(name, no_start=False, path=None):
'''
If the container is not currently running, start it. This function returns
the state that the container was in before changing
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
'''
_ensure_exists(name, path=path)
pre = state(name, path=path)
if pre == 'running':
# This will be a no-op but running the function will give us a pretty
# return dict.
return start(name, path=path)
elif pre == 'stopped':
if no_start:
raise CommandExecutionError(
'Container \'{0}\' is not running'.format(name)
)
return start(name, path=path)
elif pre == 'frozen':
if no_start:
raise CommandExecutionError(
'Container \'{0}\' is not running'.format(name)
)
return unfreeze(name, path=path)
def restart(name, path=None, lxc_config=None, force=False):
'''
.. versionadded:: 2015.5.0
Restart the named container. If the container was not running, the
container will merely be started.
name
The name of the container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
lxc_config
path to a lxc config file
config file will be guessed from container name otherwise
.. versionadded:: 2015.8.0
force : False
If ``True``, the container will be force-stopped instead of gracefully
shut down
CLI Example:
.. code-block:: bash
salt myminion lxc.restart name
'''
_ensure_exists(name, path=path)
orig_state = state(name, path=path)
if orig_state != 'stopped':
stop(name, kill=force, path=path)
ret = start(name, path=path, lxc_config=lxc_config)
ret['state']['old'] = orig_state
if orig_state != 'stopped':
ret['restarted'] = True
return ret
def start(name, **kwargs):
'''
Start the named container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
lxc_config
path to a lxc config file
config file will be guessed from container name otherwise
.. versionadded:: 2015.8.0
use_vt
run the command through VT
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.start name
'''
path = kwargs.get('path', None)
cpath = get_root_path(path)
lxc_config = kwargs.get('lxc_config', None)
cmd = 'lxc-start'
if not lxc_config:
lxc_config = os.path.join(cpath, name, 'config')
# we try to start, even without config, if global opts are there
if os.path.exists(lxc_config):
cmd += ' -f {0}'.format(pipes.quote(lxc_config))
cmd += ' -d'
_ensure_exists(name, path=path)
if state(name, path=path) == 'frozen':
raise CommandExecutionError(
'Container \'{0}\' is frozen, use lxc.unfreeze'.format(name)
)
# lxc-start daemonize itself violently, we must not communicate with it
use_vt = kwargs.get('use_vt', None)
with_communicate = kwargs.get('with_communicate', False)
return _change_state(cmd, name, 'running',
stdout=None,
stderr=None,
stdin=None,
with_communicate=with_communicate,
path=path,
use_vt=use_vt)
def stop(name, kill=False, path=None, use_vt=None):
'''
Stop the named container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
kill: False
Do not wait for the container to stop, kill all tasks in the container.
Older LXC versions will stop containers like this irrespective of this
argument.
.. versionchanged:: 2015.5.0
Default value changed to ``False``
use_vt
run the command through VT
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.stop name
'''
_ensure_exists(name, path=path)
orig_state = state(name, path=path)
if orig_state == 'frozen' and not kill:
# Gracefully stopping a frozen container is slower than unfreezing and
# then stopping it (at least in my testing), so if we're not
# force-stopping the container, unfreeze it first.
unfreeze(name, path=path)
cmd = 'lxc-stop'
if kill:
cmd += ' -k'
ret = _change_state(cmd, name, 'stopped', use_vt=use_vt, path=path)
ret['state']['old'] = orig_state
return ret
def unfreeze(name, path=None, use_vt=None):
'''
Unfreeze the named container.
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
use_vt
run the command through VT
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.unfreeze name
'''
_ensure_exists(name, path=path)
if state(name, path=path) == 'stopped':
raise CommandExecutionError(
'Container \'{0}\' is stopped'.format(name)
)
cmd = 'lxc-unfreeze'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
return _change_state(cmd, name, 'running', path=path, use_vt=use_vt)
def destroy(name, stop=False, path=None):
'''
Destroy the named container.
.. warning::
Destroys all data associated with the container.
path
path to the container parent directory (default: /var/lib/lxc)
.. versionadded:: 2015.8.0
stop : False
If ``True``, the container will be destroyed even if it is
running/frozen.
.. versionchanged:: 2015.5.0
Default value changed to ``False``. This more closely matches the
behavior of ``lxc-destroy(1)``, and also makes it less likely that
an accidental command will destroy a running container that was
being used for important things.
CLI Examples:
.. code-block:: bash
salt '*' lxc.destroy foo
salt '*' lxc.destroy foo stop=True
'''
_ensure_exists(name, path=path)
if not stop and state(name, path=path) != 'stopped':
raise CommandExecutionError(
'Container \'{0}\' is not stopped'.format(name)
)
return _change_state('lxc-destroy', name, None, path=path)
# Compatibility between LXC and nspawn
remove = salt.utils.functools.alias_function(destroy, 'remove')
def exists(name, path=None):
'''
Returns whether the named container exists.
path
path to the container parent directory (default: /var/lib/lxc)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.exists name
'''
_exists = name in ls_(path=path)
# container may be just created but we did cached earlier the
# lxc-ls results
if not _exists:
_exists = name in ls_(cache=False, path=path)
return _exists
def state(name, path=None):
'''
Returns the state of a container.
path
path to the container parent directory (default: /var/lib/lxc)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.state name
'''
# Don't use _ensure_exists() here, it will mess with _change_state()
cachekey = 'lxc.state.{0}{1}'.format(name, path)
try:
return __context__[cachekey]
except KeyError:
if not exists(name, path=path):
__context__[cachekey] = None
else:
cmd = 'lxc-info'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0}'.format(name)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
if ret['retcode'] != 0:
_clear_context()
raise CommandExecutionError(
'Unable to get state of container \'{0}\''.format(name)
)
c_infos = ret['stdout'].splitlines()
c_state = None
for c_info in c_infos:
stat = c_info.split(':')
if stat[0].lower() == 'state':
c_state = stat[1].strip().lower()
break
__context__[cachekey] = c_state
return __context__[cachekey]
def get_parameter(name, parameter, path=None):
'''
Returns the value of a cgroup parameter for a container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.get_parameter container_name memory.limit_in_bytes
'''
_ensure_exists(name, path=path)
cmd = 'lxc-cgroup'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0} {1}'.format(name, parameter)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
if ret['retcode'] != 0:
raise CommandExecutionError(
'Unable to retrieve value for \'{0}\''.format(parameter)
)
return ret['stdout'].strip()
def set_parameter(name, parameter, value, path=None):
'''
Set the value of a cgroup parameter for a container.
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.set_parameter name parameter value
'''
if not exists(name, path=path):
return None
cmd = 'lxc-cgroup'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0} {1} {2}'.format(name, parameter, value)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
if ret['retcode'] != 0:
return False
else:
return True
def info(name, path=None):
'''
Returns information about a container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.info name
'''
cachekey = 'lxc.info.{0}{1}'.format(name, path)
try:
return __context__[cachekey]
except KeyError:
_ensure_exists(name, path=path)
cpath = get_root_path(path)
try:
conf_file = os.path.join(cpath, name, 'config')
except AttributeError:
conf_file = os.path.join(cpath, six.text_type(name), 'config')
if not os.path.isfile(conf_file):
raise CommandExecutionError(
'LXC config file {0} does not exist'.format(conf_file)
)
ret = {}
config = []
with salt.utils.files.fopen(conf_file) as fp_:
for line in fp_:
line = salt.utils.stringutils.to_unicode(line)
comps = [x.strip() for x in
line.split('#', 1)[0].strip().split('=', 1)]
if len(comps) == 2:
config.append(tuple(comps))
ifaces = []
current = None
for key, val in config:
if key == 'lxc.network.type':
current = {'type': val}
ifaces.append(current)
elif not current:
continue
elif key.startswith('lxc.network.'):
current[key.replace('lxc.network.', '', 1)] = val
if ifaces:
ret['nics'] = ifaces
ret['rootfs'] = next(
(x[1] for x in config if x[0] == 'lxc.rootfs'),
None
)
ret['state'] = state(name, path=path)
ret['ips'] = []
ret['public_ips'] = []
ret['private_ips'] = []
ret['public_ipv4_ips'] = []
ret['public_ipv6_ips'] = []
ret['private_ipv4_ips'] = []
ret['private_ipv6_ips'] = []
ret['ipv4_ips'] = []
ret['ipv6_ips'] = []
ret['size'] = None
ret['config'] = conf_file
if ret['state'] == 'running':
try:
limit = int(get_parameter(name, 'memory.limit_in_bytes'))
except (CommandExecutionError, TypeError, ValueError):
limit = 0
try:
usage = int(get_parameter(name, 'memory.usage_in_bytes'))
except (CommandExecutionError, TypeError, ValueError):
usage = 0
free = limit - usage
ret['memory_limit'] = limit
ret['memory_free'] = free
size = run_stdout(name, 'df /', path=path, python_shell=False)
# The size is the 2nd column of the last line
ret['size'] = size.splitlines()[-1].split()[1]
# First try iproute2
ip_cmd = run_all(
name, 'ip link show', path=path, python_shell=False)
if ip_cmd['retcode'] == 0:
ip_data = ip_cmd['stdout']
ip_cmd = run_all(
name, 'ip addr show', path=path, python_shell=False)
ip_data += '\n' + ip_cmd['stdout']
ip_data = salt.utils.network._interfaces_ip(ip_data)
else:
# That didn't work, try ifconfig
ip_cmd = run_all(
name, 'ifconfig', path=path, python_shell=False)
if ip_cmd['retcode'] == 0:
ip_data = \
salt.utils.network._interfaces_ifconfig(
ip_cmd['stdout'])
else:
# Neither was successful, give up
log.warning(
'Unable to run ip or ifconfig in container \'%s\'', name
)
ip_data = {}
ret['ipv4_ips'] = salt.utils.network.ip_addrs(
include_loopback=True,
interface_data=ip_data
)
ret['ipv6_ips'] = salt.utils.network.ip_addrs6(
include_loopback=True,
interface_data=ip_data
)
ret['ips'] = ret['ipv4_ips'] + ret['ipv6_ips']
for address in ret['ipv4_ips']:
if address == '127.0.0.1':
ret['private_ips'].append(address)
ret['private_ipv4_ips'].append(address)
elif salt.utils.cloud.is_public_ip(address):
ret['public_ips'].append(address)
ret['public_ipv4_ips'].append(address)
else:
ret['private_ips'].append(address)
ret['private_ipv4_ips'].append(address)
for address in ret['ipv6_ips']:
if address == '::1' or address.startswith('fe80'):
ret['private_ips'].append(address)
ret['private_ipv6_ips'].append(address)
else:
ret['public_ips'].append(address)
ret['public_ipv6_ips'].append(address)
for key in [x for x in ret if x == 'ips' or x.endswith('ips')]:
ret[key].sort(key=_ip_sort)
__context__[cachekey] = ret
return __context__[cachekey]
def set_password(name, users, password, encrypted=True, path=None):
'''
.. versionchanged:: 2015.5.0
Function renamed from ``set_pass`` to ``set_password``. Additionally,
this function now supports (and defaults to using) a password hash
instead of a plaintext password.
Set the password of one or more system users inside containers
users
Comma-separated list (or python list) of users to change password
password
Password to set for the specified user(s)
encrypted : True
If true, ``password`` must be a password hash. Set to ``False`` to set
a plaintext password (not recommended).
.. versionadded:: 2015.5.0
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.set_pass container-name root '$6$uJ2uAyLU$KoI67t8As/0fXtJOPcHKGXmUpcoYUcVR2K6x93walnShTCQvjRwq25yIkiCBOqgbfdKQSFnAo28/ek6716vEV1'
salt '*' lxc.set_pass container-name root foo encrypted=False
'''
def _bad_user_input():
raise SaltInvocationError('Invalid input for \'users\' parameter')
if not isinstance(users, list):
try:
users = users.split(',')
except AttributeError:
_bad_user_input()
if not users:
_bad_user_input()
failed_users = []
for user in users:
result = retcode(name,
'chpasswd{0}'.format(' -e' if encrypted else ''),
stdin=':'.join((user, password)),
python_shell=False,
path=path,
chroot_fallback=True,
output_loglevel='quiet')
if result != 0:
failed_users.append(user)
if failed_users:
raise CommandExecutionError(
'Password change failed for the following user(s): {0}'
.format(', '.join(failed_users))
)
return True
set_pass = salt.utils.functools.alias_function(set_password, 'set_pass')
def update_lxc_conf(name, lxc_conf, lxc_conf_unset, path=None):
'''
Edit LXC configuration options
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.update_lxc_conf ubuntu \\
lxc_conf="[{'network.ipv4.ip':'10.0.3.5'}]" \\
lxc_conf_unset="['lxc.utsname']"
'''
_ensure_exists(name, path=path)
cpath = get_root_path(path)
lxc_conf_p = os.path.join(cpath, name, 'config')
if not os.path.exists(lxc_conf_p):
raise SaltInvocationError(
'Configuration file {0} does not exist'.format(lxc_conf_p)
)
changes = {'edited': [], 'added': [], 'removed': []}
ret = {'changes': changes, 'result': True, 'comment': ''}
# do not use salt.utils.files.fopen !
with salt.utils.files.fopen(lxc_conf_p, 'r') as fic:
filtered_lxc_conf = []
for row in lxc_conf:
if not row:
continue
for conf in row:
filtered_lxc_conf.append((conf.strip(),
row[conf].strip()))
ret['comment'] = 'lxc.conf is up to date'
lines = []
orig_config = salt.utils.stringutils.to_unicode(fic.read())
for line in orig_config.splitlines():
if line.startswith('#') or not line.strip():
lines.append([line, ''])
else:
line = line.split('=')
index = line.pop(0)
val = (index.strip(), '='.join(line).strip())
if val not in lines:
lines.append(val)
for key, item in filtered_lxc_conf:
matched = False
for idx, line in enumerate(lines[:]):
if line[0] == key:
matched = True
lines[idx] = (key, item)
if '='.join(line[1:]).strip() != item.strip():
changes['edited'].append(
({line[0]: line[1:]}, {key: item}))
break
if not matched:
if (key, item) not in lines:
lines.append((key, item))
changes['added'].append({key: item})
dest_lxc_conf = []
# filter unset
if lxc_conf_unset:
for line in lines:
for opt in lxc_conf_unset:
if (
not line[0].startswith(opt) and
line not in dest_lxc_conf
):
dest_lxc_conf.append(line)
else:
changes['removed'].append(opt)
else:
dest_lxc_conf = lines
conf = ''
for key, val in dest_lxc_conf:
if not val:
conf += '{0}\n'.format(key)
else:
conf += '{0} = {1}\n'.format(key.strip(), val.strip())
conf_changed = conf != orig_config
chrono = datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S')
if conf_changed:
# DO NOT USE salt.utils.files.fopen here, i got (kiorky)
# problems with lxc configs which were wiped !
with salt.utils.files.fopen('{0}.{1}'.format(lxc_conf_p, chrono), 'w') as wfic:
wfic.write(salt.utils.stringutils.to_str(conf))
with salt.utils.files.fopen(lxc_conf_p, 'w') as wfic:
wfic.write(salt.utils.stringutils.to_str(conf))
ret['comment'] = 'Updated'
ret['result'] = True
if not any(changes[x] for x in changes):
# Ensure an empty changes dict if nothing was modified
ret['changes'] = {}
return ret
def set_dns(name, dnsservers=None, searchdomains=None, path=None):
'''
.. versionchanged:: 2015.5.0
The ``dnsservers`` and ``searchdomains`` parameters can now be passed
as a comma-separated list.
Update /etc/resolv.confo
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.set_dns ubuntu "['8.8.8.8', '4.4.4.4']"
'''
if dnsservers is None:
dnsservers = ['8.8.8.8', '4.4.4.4']
elif not isinstance(dnsservers, list):
try:
dnsservers = dnsservers.split(',')
except AttributeError:
raise SaltInvocationError(
'Invalid input for \'dnsservers\' parameter'
)
if searchdomains is None:
searchdomains = []
elif not isinstance(searchdomains, list):
try:
searchdomains = searchdomains.split(',')
except AttributeError:
raise SaltInvocationError(
'Invalid input for \'searchdomains\' parameter'
)
dns = ['nameserver {0}'.format(x) for x in dnsservers]
dns.extend(['search {0}'.format(x) for x in searchdomains])
dns = '\n'.join(dns) + '\n'
# we may be using resolvconf in the container
# We need to handle that case with care:
# - we create the resolv.conf runtime directory (the
# linked directory) as anyway it will be shadowed when the real
# runned tmpfs mountpoint will be mounted.
# ( /etc/resolv.conf -> ../run/resolvconf/resolv.conf)
# Indeed, it can save us in any other case (running, eg, in a
# bare chroot when repairing or preparing the container for
# operation.
# - We also teach resolvconf to use the aforementioned dns.
# - We finally also set /etc/resolv.conf in all cases
rstr = __salt__['test.random_hash']()
# no tmp here, apparmor won't let us execute !
script = '/sbin/{0}_dns.sh'.format(rstr)
DNS_SCRIPT = "\n".join([
# 'set -x',
'#!/usr/bin/env bash',
'if [ -h /etc/resolv.conf ];then',
' if [ "x$(readlink /etc/resolv.conf)"'
' = "x../run/resolvconf/resolv.conf" ];then',
' if [ ! -d /run/resolvconf/ ];then',
' mkdir -p /run/resolvconf',
' fi',
' cat > /etc/resolvconf/resolv.conf.d/head <<EOF',
dns,
'EOF',
'',
' fi',
'fi',
'cat > /etc/resolv.conf <<EOF',
dns,
'EOF',
''])
result = run_all(
name, 'tee {0}'.format(script), path=path,
stdin=DNS_SCRIPT, python_shell=True)
if result['retcode'] == 0:
result = run_all(
name, 'sh -c "chmod +x {0};{0}"'.format(script),
path=path, python_shell=True)
# blindly delete the setter file
run_all(name,
'sh -c \'if [ -f "{0}" ];then rm -f "{0}";fi\''.format(script),
path=path, python_shell=True)
if result['retcode'] != 0:
error = ('Unable to write to /etc/resolv.conf in container \'{0}\''
.format(name))
if result['stderr']:
error += ': {0}'.format(result['stderr'])
raise CommandExecutionError(error)
return True
def running_systemd(name, cache=True, path=None):
'''
Determine if systemD is running
path
path to the container parent
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.running_systemd ubuntu
'''
k = 'lxc.systemd.test.{0}{1}'.format(name, path)
ret = __context__.get(k, None)
if ret is None or not cache:
rstr = __salt__['test.random_hash']()
# no tmp here, apparmor won't let us execute !
script = '/sbin/{0}_testsystemd.sh'.format(rstr)
# ubuntu already had since trusty some bits of systemd but was
# still using upstart ...
# we need to be a bit more careful that just testing that systemd
# is present
_script = textwrap.dedent(
'''\
#!/usr/bin/env bash
set -x
if ! command -v systemctl 1>/dev/null 2>/dev/null;then exit 2;fi
for i in \\
/run/systemd/journal/dev-log\\
/run/systemd/journal/flushed\\
/run/systemd/journal/kernel-seqnum\\
/run/systemd/journal/socket\\
/run/systemd/journal/stdout\\
/var/run/systemd/journal/dev-log\\
/var/run/systemd/journal/flushed\\
/var/run/systemd/journal/kernel-seqnum\\
/var/run/systemd/journal/socket\\
/var/run/systemd/journal/stdout\\
;do\\
if test -e ${i};then exit 0;fi
done
if test -d /var/systemd/system;then exit 0;fi
exit 2
''')
result = run_all(
name, 'tee {0}'.format(script), path=path,
stdin=_script, python_shell=True)
if result['retcode'] == 0:
result = run_all(name,
'sh -c "chmod +x {0};{0}"'''.format(script),
path=path,
python_shell=True)
else:
raise CommandExecutionError(
'lxc {0} failed to copy initd tester'.format(name))
run_all(name,
'sh -c \'if [ -f "{0}" ];then rm -f "{0}";fi\''
''.format(script),
path=path,
ignore_retcode=True,
python_shell=True)
if result['retcode'] != 0:
error = ('Unable to determine if the container \'{0}\''
' was running systemd, assmuming it is not.'
''.format(name))
if result['stderr']:
error += ': {0}'.format(result['stderr'])
# only cache result if we got a known exit code
if result['retcode'] in (0, 2):
__context__[k] = ret = not result['retcode']
return ret
def systemd_running_state(name, path=None):
'''
Get the operational state of a systemd based container
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.systemd_running_state ubuntu
'''
try:
ret = run_all(name,
'systemctl is-system-running',
path=path,
ignore_retcode=True)['stdout']
except CommandExecutionError:
ret = ''
return ret
def test_sd_started_state(name, path=None):
'''
Test if a systemd container is fully started
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.test_sd_started_state ubuntu
'''
qstate = systemd_running_state(name, path=path)
if qstate in ('initializing', 'starting'):
return False
elif qstate == '':
return None
else:
return True
def test_bare_started_state(name, path=None):
'''
Test if a non systemd container is fully started
For now, it consists only to test if the container is attachable
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.test_bare_started_state ubuntu
'''
try:
ret = run_all(
name, 'ls', path=path, ignore_retcode=True
)['retcode'] == 0
except (CommandExecutionError,):
ret = None
return ret
def wait_started(name, path=None, timeout=300):
'''
Check that the system has fully inited
This is actually very important for systemD based containers
see https://github.com/saltstack/salt/issues/23847
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.wait_started ubuntu
'''
if not exists(name, path=path):
raise CommandExecutionError(
'Container {0} does does exists'.format(name))
if not state(name, path=path) == 'running':
raise CommandExecutionError(
'Container {0} is not running'.format(name))
ret = False
if running_systemd(name, path=path):
test_started = test_sd_started_state
logger = log.error
else:
test_started = test_bare_started_state
logger = log.debug
now = time.time()
expire = now + timeout
now = time.time()
started = test_started(name, path=path)
while time.time() < expire and not started:
time.sleep(0.3)
started = test_started(name, path=path)
if started is None:
logger(
'Assuming %s is started, although we failed to detect that'
' is fully started correctly', name)
ret = True
else:
ret = started
return ret
def _needs_install(name, path=None):
ret = 0
has_minion = retcode(name,
'which salt-minion',
path=path,
ignore_retcode=True)
# we assume that installing is when no minion is running
# but testing the executable presence is not enougth for custom
# installs where the bootstrap can do much more than installing
# the bare salt binaries.
if has_minion:
processes = run_stdout(name, "ps aux", path=path)
if 'salt-minion' not in processes:
ret = 1
else:
retcode(name, 'salt-call --local service.stop salt-minion')
else:
ret = 1
return ret
def bootstrap(name,
config=None,
approve_key=True,
install=True,
pub_key=None,
priv_key=None,
bootstrap_url=None,
force_install=False,
unconditional_install=False,
path=None,
bootstrap_delay=None,
bootstrap_args=None,
bootstrap_shell=None):
'''
Install and configure salt in a container.
config
Minion configuration options. By default, the ``master`` option is set
to the target host's master.
approve_key
Request a pre-approval of the generated minion key. Requires
that the salt-master be configured to either auto-accept all keys or
expect a signing request from the target host. Default: ``True``
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
pub_key
Explicit public key to pressed the minion with (optional).
This can be either a filepath or a string representing the key
priv_key
Explicit private key to pressed the minion with (optional).
This can be either a filepath or a string representing the key
bootstrap_delay
Delay in seconds between end of container creation and bootstrapping.
Useful when waiting for container to obtain a DHCP lease.
.. versionadded:: 2015.5.0
bootstrap_url
url, content or filepath to the salt bootstrap script
bootstrap_args
salt bootstrap script arguments
bootstrap_shell
shell to execute the script into
install
Whether to attempt a full installation of salt-minion if needed.
force_install
Force installation even if salt-minion is detected,
this is the way to run vendor bootstrap scripts even
if a salt minion is already present in the container
unconditional_install
Run the script even if the container seems seeded
CLI Examples:
.. code-block:: bash
salt 'minion' lxc.bootstrap container_name [config=config_data] \\
[approve_key=(True|False)] [install=(True|False)]
'''
wait_started(name, path=path)
if bootstrap_delay is not None:
try:
log.info('LXC %s: bootstrap_delay: %s', name, bootstrap_delay)
time.sleep(bootstrap_delay)
except TypeError:
# Bad input, but assume since a value was passed that
# a delay was desired, and sleep for 5 seconds
time.sleep(5)
c_info = info(name, path=path)
if not c_info:
return None
# default set here as we cannot set them
# in def as it can come from a chain of procedures.
if bootstrap_args:
# custom bootstrap args can be totally customized, and user could
# have inserted the placeholder for the config directory.
# For example, some salt bootstrap script do not use at all -c
if '{0}' not in bootstrap_args:
bootstrap_args += ' -c {0}'
else:
bootstrap_args = '-c {0}'
if not bootstrap_shell:
bootstrap_shell = 'sh'
orig_state = _ensure_running(name, path=path)
if not orig_state:
return orig_state
if not force_install:
needs_install = _needs_install(name, path=path)
else:
needs_install = True
seeded = retcode(name,
'test -e \'{0}\''.format(SEED_MARKER),
path=path,
chroot_fallback=True,
ignore_retcode=True) == 0
tmp = tempfile.mkdtemp()
if seeded and not unconditional_install:
ret = True
else:
ret = False
cfg_files = __salt__['seed.mkconfig'](
config, tmp=tmp, id_=name, approve_key=approve_key,
pub_key=pub_key, priv_key=priv_key)
if needs_install or force_install or unconditional_install:
if install:
rstr = __salt__['test.random_hash']()
configdir = '/var/tmp/.c_{0}'.format(rstr)
cmd = 'install -m 0700 -d {0}'.format(configdir)
if run_all(
name, cmd, path=path, python_shell=False
)['retcode'] != 0:
log.error('tmpdir %s creation failed %s', configdir, cmd)
return False
bs_ = __salt__['config.gather_bootstrap_script'](
bootstrap=bootstrap_url)
script = '/sbin/{0}_bootstrap.sh'.format(rstr)
copy_to(name, bs_, script, path=path)
result = run_all(name,
'sh -c "chmod +x {0}"'.format(script),
path=path,
python_shell=True)
copy_to(name, cfg_files['config'],
os.path.join(configdir, 'minion'),
path=path)
copy_to(name, cfg_files['privkey'],
os.path.join(configdir, 'minion.pem'),
path=path)
copy_to(name, cfg_files['pubkey'],
os.path.join(configdir, 'minion.pub'),
path=path)
bootstrap_args = bootstrap_args.format(configdir)
cmd = ('{0} {2} {1}'
.format(bootstrap_shell,
bootstrap_args.replace("'", "''"),
script))
# log ASAP the forged bootstrap command which can be wrapped
# out of the output in case of unexpected problem
log.info('Running %s in LXC container \'%s\'', cmd, name)
ret = retcode(name, cmd, output_loglevel='info',
path=path, use_vt=True) == 0
run_all(name,
'sh -c \'if [ -f "{0}" ];then rm -f "{0}";fi\''
''.format(script),
path=path,
ignore_retcode=True,
python_shell=True)
else:
ret = False
else:
minion_config = salt.config.minion_config(cfg_files['config'])
pki_dir = minion_config['pki_dir']
copy_to(name,
cfg_files['config'],
'/etc/salt/minion',
path=path)
copy_to(name,
cfg_files['privkey'],
os.path.join(pki_dir, 'minion.pem'),
path=path)
copy_to(name,
cfg_files['pubkey'],
os.path.join(pki_dir, 'minion.pub'),
path=path)
run(name,
'salt-call --local service.enable salt-minion',
path=path,
python_shell=False)
ret = True
shutil.rmtree(tmp)
if orig_state == 'stopped':
stop(name, path=path)
elif orig_state == 'frozen':
freeze(name, path=path)
# mark seeded upon successful install
if ret:
run(name,
'touch \'{0}\''.format(SEED_MARKER),
path=path,
python_shell=False)
return ret
def attachable(name, path=None):
'''
Return True if the named container can be attached to via the lxc-attach
command
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt 'minion' lxc.attachable ubuntu
'''
cachekey = 'lxc.attachable{0}{1}'.format(name, path)
try:
return __context__[cachekey]
except KeyError:
_ensure_exists(name, path=path)
# Can't use run() here because it uses attachable() and would
# endlessly recurse, resulting in a traceback
log.debug('Checking if LXC container %s is attachable', name)
cmd = 'lxc-attach'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' --clear-env -n {0} -- /usr/bin/env'.format(name)
result = __salt__['cmd.retcode'](cmd,
python_shell=False,
output_loglevel='quiet',
ignore_retcode=True) == 0
__context__[cachekey] = result
return __context__[cachekey]
def _run(name,
cmd,
output=None,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=None,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
Common logic for lxc.run functions
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
'''
orig_state = state(name, path=path)
try:
if attachable(name, path=path):
ret = __salt__['container_resource.run'](
name,
cmd,
path=path,
container_type=__virtualname__,
exec_driver=EXEC_DRIVER,
output=output,
no_start=no_start,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
ignore_retcode=ignore_retcode,
use_vt=use_vt,
keep_env=keep_env)
else:
if not chroot_fallback:
raise CommandExecutionError(
'{0} is not attachable.'.format(name))
rootfs = info(name, path=path).get('rootfs')
# Set context var to make cmd.run_chroot run cmd.run instead of
# cmd.run_all.
__context__['cmd.run_chroot.func'] = __salt__['cmd.run']
ret = __salt__['cmd.run_chroot'](rootfs,
cmd,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
ignore_retcode=ignore_retcode)
except Exception:
raise
finally:
# Make sure we honor preserve_state, even if there was an exception
new_state = state(name, path=path)
if preserve_state:
if orig_state == 'stopped' and new_state != 'stopped':
stop(name, path=path)
elif orig_state == 'frozen' and new_state != 'frozen':
freeze(name, start=True, path=path)
if output in (None, 'all'):
return ret
else:
return ret[output]
def run(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.8.0
Run :mod:`cmd.run <salt.modules.cmdmod.run>` within a container
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed in stderr if the command being run
does not exist. If no output is returned using this function, try using
:mod:`lxc.run_stderr <salt.modules.lxc.run_stderr>` or
:mod:`lxc.run_all <salt.modules.lxc.run_all>`.
name
Name of the container in which to run the command
cmd
Command to run
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console. Assumes
``output=all``.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
CLI Example:
.. code-block:: bash
salt myminion lxc.run mycontainer 'ifconfig -a'
'''
return _run(name,
cmd,
path=path,
output=None,
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def run_stdout(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.5.0
Run :mod:`cmd.run_stdout <salt.modules.cmdmod.run_stdout>` within a container
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed in stderr if the command being run
does not exist. If no output is returned using this function, try using
:mod:`lxc.run_stderr <salt.modules.lxc.run_stderr>` or
:mod:`lxc.run_all <salt.modules.lxc.run_all>`.
name
Name of the container in which to run the command
cmd
Command to run
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console
``output=all``.
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
CLI Example:
.. code-block:: bash
salt myminion lxc.run_stdout mycontainer 'ifconfig -a'
'''
return _run(name,
cmd,
path=path,
output='stdout',
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def run_stderr(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.5.0
Run :mod:`cmd.run_stderr <salt.modules.cmdmod.run_stderr>` within a container
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed if the command being run does not
exist.
name
Name of the container in which to run the command
cmd
Command to run
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console
``output=all``.
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
CLI Example:
.. code-block:: bash
salt myminion lxc.run_stderr mycontainer 'ip addr show'
'''
return _run(name,
cmd,
path=path,
output='stderr',
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def retcode(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.5.0
Run :mod:`cmd.retcode <salt.modules.cmdmod.retcode>` within a container
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed in stderr if the command being run
does not exist. If the retcode is nonzero and not what was expected,
try using :mod:`lxc.run_stderr <salt.modules.lxc.run_stderr>`
or :mod:`lxc.run_all <salt.modules.lxc.run_all>`.
name
Name of the container in which to run the command
cmd
Command to run
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console
``output=all``.
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
CLI Example:
.. code-block:: bash
salt myminion lxc.retcode mycontainer 'ip addr show'
'''
return _run(name,
cmd,
output='retcode',
path=path,
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def run_all(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.5.0
Run :mod:`cmd.run_all <salt.modules.cmdmod.run_all>` within a container
.. note::
While the command is run within the container, it is initiated from the
host. Therefore, the PID in the return dict is from the host, not from
the container.
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed in stderr if the command being run
does not exist.
name
Name of the container in which to run the command
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
cmd
Command to run
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console
``output=all``.
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
CLI Example:
.. code-block:: bash
salt myminion lxc.run_all mycontainer 'ip addr show'
'''
return _run(name,
cmd,
output='all',
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
path=path,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def _get_md5(name, path):
'''
Get the MD5 checksum of a file from a container
'''
output = run_stdout(name, 'md5sum "{0}"'.format(path),
chroot_fallback=True,
ignore_retcode=True)
try:
return output.split()[0]
except IndexError:
# Destination file does not exist or could not be accessed
return None
def copy_to(name, source, dest, overwrite=False, makedirs=False, path=None):
'''
.. versionchanged:: 2015.8.0
Function renamed from ``lxc.cp`` to ``lxc.copy_to`` for consistency
with other container types. ``lxc.cp`` will continue to work, however.
For versions 2015.2.x and earlier, use ``lxc.cp``.
Copy a file or directory from the host into a container
name
Container name
source
File to be copied to the container
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
dest
Destination on the container. Must be an absolute path.
.. versionchanged:: 2015.5.0
If the destination is a directory, the file will be copied into
that directory.
overwrite : False
Unless this option is set to ``True``, then if a file exists at the
location specified by the ``dest`` argument, an error will be raised.
.. versionadded:: 2015.8.0
makedirs : False
Create the parent directory on the container if it does not already
exist.
.. versionadded:: 2015.5.0
CLI Example:
.. code-block:: bash
salt 'minion' lxc.copy_to /tmp/foo /root/foo
salt 'minion' lxc.cp /tmp/foo /root/foo
'''
_ensure_running(name, no_start=True, path=path)
return __salt__['container_resource.copy_to'](
name,
source,
dest,
container_type=__virtualname__,
path=path,
exec_driver=EXEC_DRIVER,
overwrite=overwrite,
makedirs=makedirs)
cp = salt.utils.functools.alias_function(copy_to, 'cp')
def read_conf(conf_file, out_format='simple'):
'''
Read in an LXC configuration file. By default returns a simple, unsorted
dict, but can also return a more detailed structure including blank lines
and comments.
out_format:
set to 'simple' if you need the old and unsupported behavior.
This won't support the multiple lxc values (eg: multiple network nics)
CLI Examples:
.. code-block:: bash
salt 'minion' lxc.read_conf /etc/lxc/mycontainer.conf
salt 'minion' lxc.read_conf /etc/lxc/mycontainer.conf out_format=commented
'''
ret_commented = []
ret_simple = {}
with salt.utils.files.fopen(conf_file, 'r') as fp_:
for line in salt.utils.data.decode(fp_.readlines()):
if '=' not in line:
ret_commented.append(line)
continue
comps = line.split('=')
value = '='.join(comps[1:]).strip()
comment = None
if value.strip().startswith('#'):
vcomps = value.strip().split('#')
value = vcomps[1].strip()
comment = '#'.join(vcomps[1:]).strip()
ret_commented.append({comps[0].strip(): {
'value': value,
'comment': comment,
}})
else:
ret_commented.append({comps[0].strip(): value})
ret_simple[comps[0].strip()] = value
if out_format == 'simple':
return ret_simple
return ret_commented
def write_conf(conf_file, conf):
'''
Write out an LXC configuration file
This is normally only used internally. The format of the data structure
must match that which is returned from ``lxc.read_conf()``, with
``out_format`` set to ``commented``.
An example might look like:
.. code-block:: python
[
{'lxc.utsname': '$CONTAINER_NAME'},
'# This is a commented line\\n',
'\\n',
{'lxc.mount': '$CONTAINER_FSTAB'},
{'lxc.rootfs': {'comment': 'This is another test',
'value': 'This is another test'}},
'\\n',
{'lxc.network.type': 'veth'},
{'lxc.network.flags': 'up'},
{'lxc.network.link': 'br0'},
{'lxc.network.mac': '$CONTAINER_MACADDR'},
{'lxc.network.ipv4': '$CONTAINER_IPADDR'},
{'lxc.network.name': '$CONTAINER_DEVICENAME'},
]
CLI Example:
.. code-block:: bash
salt 'minion' lxc.write_conf /etc/lxc/mycontainer.conf \\
out_format=commented
'''
if not isinstance(conf, list):
raise SaltInvocationError('Configuration must be passed as a list')
# construct the content prior to write to the file
# to avoid half written configs
content = ''
for line in conf:
if isinstance(line, (six.text_type, six.string_types)):
content += line
elif isinstance(line, dict):
for key in list(line.keys()):
out_line = None
if isinstance(
line[key],
(six.text_type, six.string_types, six.integer_types, float)
):
out_line = ' = '.join((key, "{0}".format(line[key])))
elif isinstance(line[key], dict):
out_line = ' = '.join((key, line[key]['value']))
if 'comment' in line[key]:
out_line = ' # '.join((out_line, line[key]['comment']))
if out_line:
content += out_line
content += '\n'
with salt.utils.files.fopen(conf_file, 'w') as fp_:
fp_.write(salt.utils.stringutils.to_str(content))
return {}
def edit_conf(conf_file,
out_format='simple',
read_only=False,
lxc_config=None,
**kwargs):
'''
Edit an LXC configuration file. If a setting is already present inside the
file, its value will be replaced. If it does not exist, it will be appended
to the end of the file. Comments and blank lines will be kept in-tact if
they already exist in the file.
out_format:
Set to simple if you need backward compatibility (multiple items for a
simple key is not supported)
read_only:
return only the edited configuration without applying it
to the underlying lxc configuration file
lxc_config:
List of dict containning lxc configuration items
For network configuration, you also need to add the device it belongs
to, otherwise it will default to eth0.
Also, any change to a network parameter will result in the whole
network reconfiguration to avoid mismatchs, be aware of that !
After the file is edited, its contents will be returned. By default, it
will be returned in ``simple`` format, meaning an unordered dict (which
may not represent the actual file order). Passing in an ``out_format`` of
``commented`` will return a data structure which accurately represents the
order and content of the file.
CLI Example:
.. code-block:: bash
salt 'minion' lxc.edit_conf /etc/lxc/mycontainer.conf \\
out_format=commented lxc.network.type=veth
salt 'minion' lxc.edit_conf /etc/lxc/mycontainer.conf \\
out_format=commented \\
lxc_config="[{'lxc.network.name': 'eth0', \\
'lxc.network.ipv4': '1.2.3.4'},
{'lxc.network.name': 'eth2', \\
'lxc.network.ipv4': '1.2.3.5',\\
'lxc.network.gateway': '1.2.3.1'}]"
'''
data = []
try:
conf = read_conf(conf_file, out_format=out_format)
except Exception:
conf = []
if not lxc_config:
lxc_config = []
lxc_config = copy.deepcopy(lxc_config)
# search if we want to access net config
# in that case, we will replace all the net configuration
net_config = []
for lxc_kws in lxc_config + [kwargs]:
net_params = {}
for kwarg in [a for a in lxc_kws]:
if kwarg.startswith('__'):
continue
if kwarg.startswith('lxc.network.'):
net_params[kwarg] = lxc_kws[kwarg]
lxc_kws.pop(kwarg, None)
if net_params:
net_config.append(net_params)
nic_opts = salt.utils.odict.OrderedDict()
for params in net_config:
dev = params.get('lxc.network.name', DEFAULT_NIC)
dev_opts = nic_opts.setdefault(dev, salt.utils.odict.OrderedDict())
for param in params:
opt = param.replace('lxc.network.', '')
opt = {'hwaddr': 'mac'}.get(opt, opt)
dev_opts[opt] = params[param]
net_changes = []
if nic_opts:
net_changes = _config_list(conf, only_net=True,
**{'network_profile': DEFAULT_NIC,
'nic_opts': nic_opts})
if net_changes:
lxc_config.extend(net_changes)
for line in conf:
if not isinstance(line, dict):
data.append(line)
continue
else:
for key in list(line.keys()):
val = line[key]
if net_changes and key.startswith('lxc.network.'):
continue
found = False
for ix in range(len(lxc_config)):
kw = lxc_config[ix]
if key in kw:
found = True
data.append({key: kw[key]})
del kw[key]
if not found:
data.append({key: val})
for lxc_kws in lxc_config:
for kwarg in lxc_kws:
data.append({kwarg: lxc_kws[kwarg]})
if read_only:
return data
write_conf(conf_file, data)
return read_conf(conf_file, out_format)
def reboot(name, path=None):
'''
Reboot a container.
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Examples:
.. code-block:: bash
salt 'minion' lxc.reboot myvm
'''
ret = {'result': True,
'changes': {},
'comment': '{0} rebooted'.format(name)}
does_exist = exists(name, path=path)
if does_exist and (state(name, path=path) == 'running'):
try:
stop(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
ret['result'] = False
return ret
if does_exist and (state(name, path=path) != 'running'):
try:
start(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
ret['result'] = False
return ret
ret['changes'][name] = 'rebooted'
return ret
def reconfigure(name,
cpu=None,
cpuset=None,
cpushare=None,
memory=None,
profile=None,
network_profile=None,
nic_opts=None,
bridge=None,
gateway=None,
autostart=None,
utsname=None,
rootfs=None,
path=None,
**kwargs):
'''
Reconfigure a container.
This only applies to a few property
name
Name of the container.
utsname
utsname of the container.
.. versionadded:: 2016.3.0
rootfs
rootfs of the container.
.. versionadded:: 2016.3.0
cpu
Select a random number of cpu cores and assign it to the cpuset, if the
cpuset option is set then this option will be ignored
cpuset
Explicitly define the cpus this container will be bound to
cpushare
cgroups cpu shares.
autostart
autostart container on reboot
memory
cgroups memory limit, in MB.
(0 for nolimit, None for old default 1024MB)
gateway
the ipv4 gateway to use
the default does nothing more than lxcutils does
bridge
the bridge to use
the default does nothing more than lxcutils does
nic
Network interfaces profile (defined in config or pillar).
nic_opts
Extra options for network interfaces, will override
``{"eth0": {"mac": "aa:bb:cc:dd:ee:ff", "ipv4": "10.1.1.1", "ipv6": "2001:db8::ff00:42:8329"}}``
or
``{"eth0": {"mac": "aa:bb:cc:dd:ee:ff", "ipv4": "10.1.1.1/24", "ipv6": "2001:db8::ff00:42:8329"}}``
path
path to the container parent
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt-call -lall mc_lxc_fork.reconfigure foobar nic_opts="{'eth1': {'mac': '00:16:3e:dd:ee:44'}}" memory=4
'''
changes = {}
cpath = get_root_path(path)
path = os.path.join(cpath, name, 'config')
ret = {'name': name,
'comment': 'config for {0} up to date'.format(name),
'result': True,
'changes': changes}
profile = get_container_profile(copy.deepcopy(profile))
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, _marker)
profile_match = profile.pop(key, default)
# let kwarg overrides be the preferred choice
if kw_overrides_match is _marker:
return profile_match
return kw_overrides_match
if nic_opts is not None and not network_profile:
network_profile = DEFAULT_NIC
if autostart is not None:
autostart = select('autostart', autostart)
else:
autostart = 'keep'
if not utsname:
utsname = select('utsname', utsname)
if os.path.exists(path):
old_chunks = read_conf(path, out_format='commented')
make_kw = salt.utils.odict.OrderedDict([
('utsname', utsname),
('rootfs', rootfs),
('autostart', autostart),
('cpu', cpu),
('gateway', gateway),
('cpuset', cpuset),
('cpushare', cpushare),
('network_profile', network_profile),
('nic_opts', nic_opts),
('bridge', bridge)])
# match 0 and none as memory = 0 in lxc config is harmful
if memory:
make_kw['memory'] = memory
kw = salt.utils.odict.OrderedDict()
for key, val in six.iteritems(make_kw):
if val is not None:
kw[key] = val
new_cfg = _config_list(conf_tuples=old_chunks, **kw)
if new_cfg:
edit_conf(path, out_format='commented', lxc_config=new_cfg)
chunks = read_conf(path, out_format='commented')
if old_chunks != chunks:
ret['comment'] = '{0} lxc config updated'.format(name)
if state(name, path=path) == 'running':
cret = reboot(name, path=path)
ret['result'] = cret['result']
return ret
def apply_network_profile(name, network_profile, nic_opts=None, path=None):
'''
.. versionadded:: 2015.5.0
Apply a network profile to a container
network_profile
profile name or default values (dict)
nic_opts
values to override in defaults (dict)
indexed by nic card names
path
path to the container parent
.. versionadded:: 2015.8.0
CLI Examples:
.. code-block:: bash
salt 'minion' lxc.apply_network_profile web1 centos
salt 'minion' lxc.apply_network_profile web1 centos \\
nic_opts="{'eth0': {'mac': 'xx:xx:xx:xx:xx:xx'}}"
salt 'minion' lxc.apply_network_profile web1 \\
"{'eth0': {'mac': 'xx:xx:xx:xx:xx:yy'}}"
nic_opts="{'eth0': {'mac': 'xx:xx:xx:xx:xx:xx'}}"
The special case to disable use of ethernet nics:
.. code-block:: bash
salt 'minion' lxc.apply_network_profile web1 centos \\
"{eth0: {disable: true}}"
'''
cpath = get_root_path(path)
cfgpath = os.path.join(cpath, name, 'config')
before = []
with salt.utils.files.fopen(cfgpath, 'r') as fp_:
for line in fp_:
before.append(line)
lxcconfig = _LXCConfig(name=name, path=path)
old_net = lxcconfig._filter_data('lxc.network')
network_params = {}
for param in _network_conf(
conf_tuples=old_net,
network_profile=network_profile, nic_opts=nic_opts
):
network_params.update(param)
if network_params:
edit_conf(cfgpath, out_format='commented', **network_params)
after = []
with salt.utils.files.fopen(cfgpath, 'r') as fp_:
for line in fp_:
after.append(line)
diff = ''
for line in difflib.unified_diff(before,
after,
fromfile='before',
tofile='after'):
diff += line
return diff
def get_pid(name, path=None):
'''
Returns a container pid.
Throw an exception if the container isn't running.
CLI Example:
.. code-block:: bash
salt '*' lxc.get_pid name
'''
if name not in list_(limit='running', path=path):
raise CommandExecutionError('Container {0} is not running, can\'t determine PID'.format(name))
info = __salt__['cmd.run']('lxc-info -n {0}'.format(name)).split("\n")
pid = [line.split(':')[1].strip() for line in info if re.match(r'\s*PID', line)][0]
return pid
def add_veth(name, interface_name, bridge=None, path=None):
'''
Add a veth to a container.
Note : this function doesn't update the container config, just add the interface at runtime
name
Name of the container
interface_name
Name of the interface in the container
bridge
Name of the bridge to attach the interface to (facultative)
CLI Examples:
.. code-block:: bash
salt '*' lxc.add_veth container_name eth1 br1
salt '*' lxc.add_veth container_name eth1
'''
# Get container init PID
pid = get_pid(name, path=path)
# Generate a ramdom string for veth and ensure that is isn't present on the system
while True:
random_veth = 'veth'+''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(6))
if random_veth not in __salt__['network.interfaces']().keys():
break
# Check prerequisites
if not __salt__['file.directory_exists']('/var/run/'):
raise CommandExecutionError('Directory /var/run required for lxc.add_veth doesn\'t exists')
if not __salt__['file.file_exists']('/proc/{0}/ns/net'.format(pid)):
raise CommandExecutionError('Proc file for container {0} network namespace doesn\'t exists'.format(name))
if not __salt__['file.directory_exists']('/var/run/netns'):
__salt__['file.mkdir']('/var/run/netns')
# Ensure that the symlink is up to date (change on container restart)
if __salt__['file.is_link']('/var/run/netns/{0}'.format(name)):
__salt__['file.remove']('/var/run/netns/{0}'.format(name))
__salt__['file.symlink']('/proc/{0}/ns/net'.format(pid), '/var/run/netns/{0}'.format(name))
# Ensure that interface doesn't exists
interface_exists = 0 == __salt__['cmd.retcode']('ip netns exec {netns} ip address list {interface}'.format(
netns=name,
interface=interface_name
))
if interface_exists:
raise CommandExecutionError('Interface {interface} already exists in {container}'.format(
interface=interface_name,
container=name
))
# Create veth and bring it up
if __salt__['cmd.retcode']('ip link add name {veth} type veth peer name {veth}_c'.format(veth=random_veth)) != 0:
raise CommandExecutionError('Error while creating the veth pair {0}'.format(random_veth))
if __salt__['cmd.retcode']('ip link set dev {0} up'.format(random_veth)) != 0:
raise CommandExecutionError('Error while bringing up host-side veth {0}'.format(random_veth))
# Attach it to the container
attached = 0 == __salt__['cmd.retcode']('ip link set dev {veth}_c netns {container} name {interface_name}'.format(
veth=random_veth,
container=name,
interface_name=interface_name
))
if not attached:
raise CommandExecutionError('Error while attaching the veth {veth} to container {container}'.format(
veth=random_veth,
container=name
))
__salt__['file.remove']('/var/run/netns/{0}'.format(name))
if bridge is not None:
__salt__['bridge.addif'](bridge, random_veth)
|
saltstack/salt
|
salt/modules/lxc.py
|
unfreeze
|
python
|
def unfreeze(name, path=None, use_vt=None):
'''
Unfreeze the named container.
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
use_vt
run the command through VT
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.unfreeze name
'''
_ensure_exists(name, path=path)
if state(name, path=path) == 'stopped':
raise CommandExecutionError(
'Container \'{0}\' is stopped'.format(name)
)
cmd = 'lxc-unfreeze'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
return _change_state(cmd, name, 'running', path=path, use_vt=use_vt)
|
Unfreeze the named container.
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
use_vt
run the command through VT
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.unfreeze name
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/lxc.py#L2533-L2562
|
[
"def state(name, path=None):\n '''\n Returns the state of a container.\n\n path\n path to the container parent directory (default: /var/lib/lxc)\n\n .. versionadded:: 2015.8.0\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' lxc.state name\n '''\n # Don't use _ensure_exists() here, it will mess with _change_state()\n\n cachekey = 'lxc.state.{0}{1}'.format(name, path)\n try:\n return __context__[cachekey]\n except KeyError:\n if not exists(name, path=path):\n __context__[cachekey] = None\n else:\n cmd = 'lxc-info'\n if path:\n cmd += ' -P {0}'.format(pipes.quote(path))\n cmd += ' -n {0}'.format(name)\n ret = __salt__['cmd.run_all'](cmd, python_shell=False)\n if ret['retcode'] != 0:\n _clear_context()\n raise CommandExecutionError(\n 'Unable to get state of container \\'{0}\\''.format(name)\n )\n c_infos = ret['stdout'].splitlines()\n c_state = None\n for c_info in c_infos:\n stat = c_info.split(':')\n if stat[0].lower() == 'state':\n c_state = stat[1].strip().lower()\n break\n __context__[cachekey] = c_state\n return __context__[cachekey]\n",
"def _change_state(cmd,\n name,\n expected,\n stdin=_marker,\n stdout=_marker,\n stderr=_marker,\n with_communicate=_marker,\n use_vt=_marker,\n path=None):\n pre = state(name, path=path)\n if pre == expected:\n return {'result': True,\n 'state': {'old': expected, 'new': expected},\n 'comment': 'Container \\'{0}\\' already {1}'\n .format(name, expected)}\n\n if cmd == 'lxc-destroy':\n # Kill the container first\n scmd = 'lxc-stop'\n if path:\n scmd += ' -P {0}'.format(pipes.quote(path))\n scmd += ' -k -n {0}'.format(name)\n __salt__['cmd.run'](scmd,\n python_shell=False)\n\n if path and ' -P ' not in cmd:\n cmd += ' -P {0}'.format(pipes.quote(path))\n cmd += ' -n {0}'.format(name)\n\n # certain lxc commands need to be taken with care (lxc-start)\n # as te command itself mess with double forks; we must not\n # communicate with it, but just wait for the exit status\n pkwargs = {'python_shell': False,\n 'redirect_stderr': True,\n 'with_communicate': with_communicate,\n 'use_vt': use_vt,\n 'stdin': stdin,\n 'stdout': stdout}\n for i in [a for a in pkwargs]:\n val = pkwargs[i]\n if val is _marker:\n pkwargs.pop(i, None)\n\n _cmdout = __salt__['cmd.run_all'](cmd, **pkwargs)\n\n if _cmdout['retcode'] != 0:\n raise CommandExecutionError(\n 'Error changing state for container \\'{0}\\' using command '\n '\\'{1}\\': {2}'.format(name, cmd, _cmdout['stdout'])\n )\n if expected is not None:\n # some commands do not wait, so we will\n rcmd = 'lxc-wait'\n if path:\n rcmd += ' -P {0}'.format(pipes.quote(path))\n rcmd += ' -n {0} -s {1}'.format(name, expected.upper())\n __salt__['cmd.run'](rcmd, python_shell=False, timeout=30)\n _clear_context()\n post = state(name, path=path)\n ret = {'result': post == expected,\n 'state': {'old': pre, 'new': post}}\n return ret\n",
"def _ensure_exists(name, path=None):\n '''\n Raise an exception if the container does not exist\n '''\n if not exists(name, path=path):\n raise CommandExecutionError(\n 'Container \\'{0}\\' does not exist'.format(name)\n )\n"
] |
# -*- coding: utf-8 -*-
'''
Control Linux Containers via Salt
:depends: lxc package for distribution
lxc >= 1.0 (even beta alpha) is required
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import datetime
import copy
import string
import textwrap
import difflib
import logging
import tempfile
import os
import pipes
import time
import shutil
import re
import random
# Import salt libs
import salt.utils.args
import salt.utils.cloud
import salt.utils.data
import salt.utils.dictupdate
import salt.utils.files
import salt.utils.functools
import salt.utils.hashutils
import salt.utils.network
import salt.utils.odict
import salt.utils.path
import salt.utils.stringutils
from salt.exceptions import CommandExecutionError, SaltInvocationError
import salt.config
from salt.utils.versions import LooseVersion as _LooseVersion
# Import 3rd-party libs
from salt.ext import six
# pylint: disable=import-error,no-name-in-module
from salt.ext.six.moves import range # pylint: disable=redefined-builtin
from salt.ext.six.moves.urllib.parse import urlparse as _urlparse
# pylint: enable=import-error,no-name-in-module
# Set up logging
log = logging.getLogger(__name__)
# Don't shadow built-in's.
__func_alias__ = {
'list_': 'list',
'ls_': 'ls'
}
__virtualname__ = 'lxc'
DEFAULT_NIC = 'eth0'
DEFAULT_BR = 'br0'
SEED_MARKER = '/lxc.initial_seed'
EXEC_DRIVER = 'lxc-attach'
DEFAULT_PATH = '/var/lib/lxc'
_marker = object()
def __virtual__():
if salt.utils.path.which('lxc-start'):
return __virtualname__
# To speed up the whole thing, we decided to not use the
# subshell way and assume things are in place for lxc
# Discussion made by @kiorky and @thatch45
# lxc-version presence is not sufficient, in lxc1.0 alpha
# (precise backports), we have it and it is sufficient
# for the module to execute.
# elif salt.utils.path.which('lxc-version'):
# passed = False
# try:
# passed = subprocess.check_output(
# 'lxc-version').split(':')[1].strip() >= '1.0'
# except Exception:
# pass
# if not passed:
# log.warning('Support for lxc < 1.0 may be incomplete.')
# return 'lxc'
# return False
#
return (False, 'The lxc execution module cannot be loaded: the lxc-start binary is not in the path.')
def get_root_path(path):
'''
Get the configured lxc root for containers
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.get_root_path
'''
if not path:
path = __opts__.get('lxc.root_path', DEFAULT_PATH)
return path
def version():
'''
Return the actual lxc client version
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.version
'''
k = 'lxc.version'
if not __context__.get(k, None):
cversion = __salt__['cmd.run_all']('lxc-info --version')
if not cversion['retcode']:
ver = _LooseVersion(cversion['stdout'])
if ver < _LooseVersion('1.0'):
raise CommandExecutionError('LXC should be at least 1.0')
__context__[k] = "{0}".format(ver)
return __context__.get(k, None)
def _clear_context():
'''
Clear any lxc variables set in __context__
'''
for var in [x for x in __context__ if x.startswith('lxc.')]:
log.trace('Clearing __context__[\'%s\']', var)
__context__.pop(var, None)
def _ip_sort(ip):
'''Ip sorting'''
idx = '001'
if ip == '127.0.0.1':
idx = '200'
if ip == '::1':
idx = '201'
elif '::' in ip:
idx = '100'
return '{0}___{1}'.format(idx, ip)
def search_lxc_bridges():
'''
Search which bridges are potentially available as LXC bridges
CLI Example:
.. code-block:: bash
salt '*' lxc.search_lxc_bridges
'''
bridges = __context__.get('lxc.bridges', None)
# either match not yet called or no bridges were found
# to handle the case where lxc was not installed on the first
# call
if not bridges:
bridges = set()
running_bridges = set()
bridges.add(DEFAULT_BR)
try:
output = __salt__['cmd.run_all']('brctl show')
for line in output['stdout'].splitlines()[1:]:
if not line.startswith(' '):
running_bridges.add(line.split()[0].strip())
except (SaltInvocationError, CommandExecutionError):
pass
for ifc, ip in six.iteritems(
__grains__.get('ip_interfaces', {})
):
if ifc in running_bridges:
bridges.add(ifc)
elif os.path.exists(
'/sys/devices/virtual/net/{0}/bridge'.format(ifc)
):
bridges.add(ifc)
bridges = list(bridges)
# if we found interfaces that have lxc in their names
# we filter them as being the potential lxc bridges
# we also try to default on br0 on other cases
def sort_bridges(a):
pref = 'z'
if 'lxc' in a:
pref = 'a'
elif 'br0' == a:
pref = 'c'
return '{0}_{1}'.format(pref, a)
bridges.sort(key=sort_bridges)
__context__['lxc.bridges'] = bridges
return bridges
def search_lxc_bridge():
'''
Search the first bridge which is potentially available as LXC bridge
CLI Example:
.. code-block:: bash
salt '*' lxc.search_lxc_bridge
'''
return search_lxc_bridges()[0]
def _get_salt_config(config, **kwargs):
if not config:
config = kwargs.get('minion', {})
if not config:
config = {}
config.setdefault('master',
kwargs.get('master',
__opts__.get('master',
__opts__['id'])))
config.setdefault(
'master_port',
kwargs.get('master_port',
__opts__.get('master_port',
__opts__.get('ret_port',
__opts__.get('4506')))))
if not config['master']:
config = {}
return config
def cloud_init_interface(name, vm_=None, **kwargs):
'''
Interface between salt.cloud.lxc driver and lxc.init
``vm_`` is a mapping of vm opts in the salt.cloud format
as documented for the lxc driver.
This can be used either:
- from the salt cloud driver
- because you find the argument to give easier here
than using directly lxc.init
.. warning::
BE REALLY CAREFUL CHANGING DEFAULTS !!!
IT'S A RETRO COMPATIBLE INTERFACE WITH
THE SALT CLOUD DRIVER (ask kiorky).
name
name of the lxc container to create
pub_key
public key to preseed the minion with.
Can be the keycontent or a filepath
priv_key
private key to preseed the minion with.
Can be the keycontent or a filepath
path
path to the container parent directory (default: /var/lib/lxc)
.. versionadded:: 2015.8.0
profile
:ref:`profile <tutorial-lxc-profiles-container>` selection
network_profile
:ref:`network profile <tutorial-lxc-profiles-network>` selection
nic_opts
per interface settings compatibles with
network profile (ipv4/ipv6/link/gateway/mac/netmask)
eg::
- {'eth0': {'mac': '00:16:3e:01:29:40',
'gateway': None, (default)
'link': 'br0', (default)
'gateway': None, (default)
'netmask': '', (default)
'ip': '22.1.4.25'}}
unconditional_install
given to lxc.bootstrap (see relative doc)
force_install
given to lxc.bootstrap (see relative doc)
config
any extra argument for the salt minion config
dnsservers
list of DNS servers to set inside the container
dns_via_dhcp
do not set the dns servers, let them be set by the dhcp.
autostart
autostart the container at boot time
password
administrative password for the container
bootstrap_delay
delay before launching bootstrap script at Container init
.. warning::
Legacy but still supported options:
from_container
which container we use as a template
when running lxc.clone
image
which template do we use when we
are using lxc.create. This is the default
mode unless you specify something in from_container
backing
which backing store to use.
Values can be: overlayfs, dir(default), lvm, zfs, brtfs
fstype
When using a blockdevice level backing store,
which filesystem to use on
size
When using a blockdevice level backing store,
which size for the filesystem to use on
snapshot
Use snapshot when cloning the container source
vgname
if using LVM: vgname
lvname
if using LVM: lvname
thinpool:
if using LVM: thinpool
ip
ip for the primary nic
mac
mac address for the primary nic
netmask
netmask for the primary nic (24)
= ``vm_.get('netmask', '24')``
bridge
bridge for the primary nic (lxcbr0)
gateway
network gateway for the container
additional_ips
additional ips which will be wired on the main bridge (br0)
which is connected to internet.
Be aware that you may use manual virtual mac addresses
providen by you provider (online, ovh, etc).
This is a list of mappings {ip: '', mac: '', netmask:''}
Set gateway to None and an interface with a gateway
to escape from another interface that eth0.
eg::
- {'mac': '00:16:3e:01:29:40',
'gateway': None, (default)
'link': 'br0', (default)
'netmask': '', (default)
'ip': '22.1.4.25'}
users
administrative users for the container
default: [root] and [root, ubuntu] on ubuntu
default_nic
name of the first interface, you should
really not override this
CLI Example:
.. code-block:: bash
salt '*' lxc.cloud_init_interface foo
'''
if vm_ is None:
vm_ = {}
vm_ = copy.deepcopy(vm_)
vm_ = salt.utils.dictupdate.update(vm_, kwargs)
profile_data = copy.deepcopy(
vm_.get('lxc_profile',
vm_.get('profile', {})))
if not isinstance(profile_data, (dict, six.string_types)):
profile_data = {}
profile = get_container_profile(profile_data)
def _cloud_get(k, default=None):
return vm_.get(k, profile.get(k, default))
if name is None:
name = vm_['name']
# if we are on ubuntu, default to ubuntu
default_template = ''
if __grains__.get('os', '') in ['Ubuntu']:
default_template = 'ubuntu'
image = _cloud_get('image')
if not image:
_cloud_get('template', default_template)
backing = _cloud_get('backing', 'dir')
if image:
profile['template'] = image
vgname = _cloud_get('vgname', None)
if vgname:
profile['vgname'] = vgname
if backing:
profile['backing'] = backing
snapshot = _cloud_get('snapshot', False)
autostart = bool(_cloud_get('autostart', True))
dnsservers = _cloud_get('dnsservers', [])
dns_via_dhcp = _cloud_get('dns_via_dhcp', True)
password = _cloud_get('password', 's3cr3t')
password_encrypted = _cloud_get('password_encrypted', False)
fstype = _cloud_get('fstype', None)
lvname = _cloud_get('lvname', None)
thinpool = _cloud_get('thinpool', None)
pub_key = _cloud_get('pub_key', None)
priv_key = _cloud_get('priv_key', None)
size = _cloud_get('size', '20G')
script = _cloud_get('script', None)
script_args = _cloud_get('script_args', None)
users = _cloud_get('users', None)
if users is None:
users = []
ssh_username = _cloud_get('ssh_username', None)
if ssh_username and (ssh_username not in users):
users.append(ssh_username)
network_profile = _cloud_get('network_profile', None)
nic_opts = kwargs.get('nic_opts', None)
netmask = _cloud_get('netmask', '24')
path = _cloud_get('path', None)
bridge = _cloud_get('bridge', None)
gateway = _cloud_get('gateway', None)
unconditional_install = _cloud_get('unconditional_install', False)
force_install = _cloud_get('force_install', True)
config = _get_salt_config(_cloud_get('config', {}), **vm_)
default_nic = _cloud_get('default_nic', DEFAULT_NIC)
# do the interface with lxc.init mainly via nic_opts
# to avoid extra and confusing extra use cases.
if not isinstance(nic_opts, dict):
nic_opts = salt.utils.odict.OrderedDict()
# have a reference to the default nic
eth0 = nic_opts.setdefault(default_nic,
salt.utils.odict.OrderedDict())
# lxc config is based of ifc order, be sure to use odicts.
if not isinstance(nic_opts, salt.utils.odict.OrderedDict):
bnic_opts = salt.utils.odict.OrderedDict()
bnic_opts.update(nic_opts)
nic_opts = bnic_opts
gw = None
# legacy salt.cloud scheme for network interfaces settings support
bridge = _cloud_get('bridge', None)
ip = _cloud_get('ip', None)
mac = _cloud_get('mac', None)
if ip:
fullip = ip
if netmask:
fullip += '/{0}'.format(netmask)
eth0['ipv4'] = fullip
if mac is not None:
eth0['mac'] = mac
for ix, iopts in enumerate(_cloud_get("additional_ips", [])):
ifh = "eth{0}".format(ix+1)
ethx = nic_opts.setdefault(ifh, {})
if gw is None:
gw = iopts.get('gateway', ethx.get('gateway', None))
if gw:
# only one and only one default gateway is allowed !
eth0.pop('gateway', None)
gateway = None
# even if the gateway if on default "eth0" nic
# and we popped it will work
# as we reinject or set it here.
ethx['gateway'] = gw
elink = iopts.get('link', ethx.get('link', None))
if elink:
ethx['link'] = elink
# allow dhcp
aip = iopts.get('ipv4', iopts.get('ip', None))
if aip:
ethx['ipv4'] = aip
nm = iopts.get('netmask', '')
if nm:
ethx['ipv4'] += '/{0}'.format(nm)
for i in ('mac', 'hwaddr'):
if i in iopts:
ethx['mac'] = iopts[i]
break
if 'mac' not in ethx:
ethx['mac'] = salt.utils.network.gen_mac()
# last round checking for unique gateway and such
gw = None
for ethx in [a for a in nic_opts]:
ndata = nic_opts[ethx]
if gw:
ndata.pop('gateway', None)
if 'gateway' in ndata:
gw = ndata['gateway']
gateway = None
# only use a default bridge / gateway if we configured them
# via the legacy salt cloud configuration style.
# On other cases, we should rely on settings provided by the new
# salt lxc network profile style configuration which can
# be also be overridden or a per interface basis via the nic_opts dict.
if bridge:
eth0['link'] = bridge
if gateway:
eth0['gateway'] = gateway
#
lxc_init_interface = {}
lxc_init_interface['name'] = name
lxc_init_interface['config'] = config
lxc_init_interface['memory'] = _cloud_get('memory', 0) # nolimit
lxc_init_interface['pub_key'] = pub_key
lxc_init_interface['priv_key'] = priv_key
lxc_init_interface['nic_opts'] = nic_opts
for clone_from in ['clone_from', 'clone', 'from_container']:
# clone_from should default to None if not available
lxc_init_interface['clone_from'] = _cloud_get(clone_from, None)
if lxc_init_interface['clone_from'] is not None:
break
lxc_init_interface['profile'] = profile
lxc_init_interface['snapshot'] = snapshot
lxc_init_interface['dnsservers'] = dnsservers
lxc_init_interface['fstype'] = fstype
lxc_init_interface['path'] = path
lxc_init_interface['vgname'] = vgname
lxc_init_interface['size'] = size
lxc_init_interface['lvname'] = lvname
lxc_init_interface['thinpool'] = thinpool
lxc_init_interface['force_install'] = force_install
lxc_init_interface['unconditional_install'] = (
unconditional_install
)
lxc_init_interface['bootstrap_url'] = script
lxc_init_interface['bootstrap_args'] = script_args
lxc_init_interface['bootstrap_shell'] = _cloud_get('bootstrap_shell', 'sh')
lxc_init_interface['bootstrap_delay'] = _cloud_get('bootstrap_delay', None)
lxc_init_interface['autostart'] = autostart
lxc_init_interface['users'] = users
lxc_init_interface['password'] = password
lxc_init_interface['password_encrypted'] = password_encrypted
# be sure not to let objects goes inside the return
# as this return will be msgpacked for use in the runner !
lxc_init_interface['network_profile'] = network_profile
for i in ['cpu', 'cpuset', 'cpushare']:
if _cloud_get(i, None):
try:
lxc_init_interface[i] = vm_[i]
except KeyError:
lxc_init_interface[i] = profile[i]
return lxc_init_interface
def _get_profile(key, name, **kwargs):
if isinstance(name, dict):
profilename = name.pop('name', None)
return _get_profile(key, profilename, **name)
if name is None:
profile_match = {}
else:
profile_match = \
__salt__['config.get'](
'lxc.{1}:{0}'.format(name, key),
default=None,
merge='recurse'
)
if profile_match is None:
# No matching profile, make the profile an empty dict so that
# overrides can be applied below.
profile_match = {}
if not isinstance(profile_match, dict):
raise CommandExecutionError('lxc.{0} must be a dictionary'.format(key))
# Overlay the kwargs to override matched profile data
overrides = salt.utils.args.clean_kwargs(**copy.deepcopy(kwargs))
profile_match = salt.utils.dictupdate.update(
copy.deepcopy(profile_match),
overrides
)
return profile_match
def get_container_profile(name=None, **kwargs):
'''
.. versionadded:: 2015.5.0
Gather a pre-configured set of container configuration parameters. If no
arguments are passed, an empty profile is returned.
Profiles can be defined in the minion or master config files, or in pillar
or grains, and are loaded using :mod:`config.get
<salt.modules.config.get>`. The key under which LXC profiles must be
configured is ``lxc.container_profile.profile_name``. An example container
profile would be as follows:
.. code-block:: yaml
lxc.container_profile:
ubuntu:
template: ubuntu
backing: lvm
vgname: lxc
size: 1G
Parameters set in a profile can be overridden by passing additional
container creation arguments (such as the ones passed to :mod:`lxc.create
<salt.modules.lxc.create>`) to this function.
A profile can be defined either as the name of the profile, or a dictionary
of variable names and values. See the :ref:`LXC Tutorial
<tutorial-lxc-profiles>` for more information on how to use LXC profiles.
CLI Example:
.. code-block:: bash
salt-call lxc.get_container_profile centos
salt-call lxc.get_container_profile ubuntu template=ubuntu backing=overlayfs
'''
profile = _get_profile('container_profile', name, **kwargs)
return profile
def get_network_profile(name=None, **kwargs):
'''
.. versionadded:: 2015.5.0
Gather a pre-configured set of network configuration parameters. If no
arguments are passed, the following default profile is returned:
.. code-block:: python
{'eth0': {'link': 'br0', 'type': 'veth', 'flags': 'up'}}
Profiles can be defined in the minion or master config files, or in pillar
or grains, and are loaded using :mod:`config.get
<salt.modules.config.get>`. The key under which LXC profiles must be
configured is ``lxc.network_profile``. An example network profile would be
as follows:
.. code-block:: yaml
lxc.network_profile.centos:
eth0:
link: br0
type: veth
flags: up
To disable networking entirely:
.. code-block:: yaml
lxc.network_profile.centos:
eth0:
disable: true
Parameters set in a profile can be overridden by passing additional
arguments to this function.
A profile can be passed either as the name of the profile, or a
dictionary of variable names and values. See the :ref:`LXC Tutorial
<tutorial-lxc-profiles>` for more information on how to use network
profiles.
.. warning::
The ``ipv4``, ``ipv6``, ``gateway``, and ``link`` (bridge) settings in
network profiles will only work if the container doesn't redefine the
network configuration (for example in
``/etc/sysconfig/network-scripts/ifcfg-<interface_name>`` on
RHEL/CentOS, or ``/etc/network/interfaces`` on Debian/Ubuntu/etc.)
CLI Example:
.. code-block:: bash
salt-call lxc.get_network_profile default
'''
profile = _get_profile('network_profile', name, **kwargs)
return profile
def _rand_cpu_str(cpu):
'''
Return a random subset of cpus for the cpuset config
'''
cpu = int(cpu)
avail = __salt__['status.nproc']()
if cpu < avail:
return '0-{0}'.format(avail)
to_set = set()
while len(to_set) < cpu:
choice = random.randint(0, avail - 1)
if choice not in to_set:
to_set.add(six.text_type(choice))
return ','.join(sorted(to_set))
def _network_conf(conf_tuples=None, **kwargs):
'''
Network configuration defaults
network_profile
as for containers, we can either call this function
either with a network_profile dict or network profile name
in the kwargs
nic_opts
overrides or extra nics in the form {nic_name: {set: tings}
'''
nic = kwargs.get('network_profile', None)
ret = []
nic_opts = kwargs.get('nic_opts', {})
if nic_opts is None:
# coming from elsewhere
nic_opts = {}
if not conf_tuples:
conf_tuples = []
old = _get_veths(conf_tuples)
if not old:
old = {}
# if we have a profile name, get the profile and load the network settings
# this will obviously by default look for a profile called "eth0"
# or by what is defined in nic_opts
# and complete each nic settings by sane defaults
if nic and isinstance(nic, (six.string_types, dict)):
nicp = get_network_profile(nic)
else:
nicp = {}
if DEFAULT_NIC not in nicp:
nicp[DEFAULT_NIC] = {}
kwargs = copy.deepcopy(kwargs)
gateway = kwargs.pop('gateway', None)
bridge = kwargs.get('bridge', None)
if nic_opts:
for dev, args in six.iteritems(nic_opts):
ethx = nicp.setdefault(dev, {})
try:
ethx = salt.utils.dictupdate.update(ethx, args)
except AttributeError:
raise SaltInvocationError('Invalid nic_opts configuration')
ifs = [a for a in nicp]
ifs += [a for a in old if a not in nicp]
ifs.sort()
gateway_set = False
for dev in ifs:
args = nicp.get(dev, {})
opts = nic_opts.get(dev, {}) if nic_opts else {}
old_if = old.get(dev, {})
disable = opts.get('disable', args.get('disable', False))
if disable:
continue
mac = opts.get('mac',
opts.get('hwaddr',
args.get('mac',
args.get('hwaddr', ''))))
type_ = opts.get('type', args.get('type', ''))
flags = opts.get('flags', args.get('flags', ''))
link = opts.get('link', args.get('link', ''))
ipv4 = opts.get('ipv4', args.get('ipv4', ''))
ipv6 = opts.get('ipv6', args.get('ipv6', ''))
infos = salt.utils.odict.OrderedDict([
('lxc.network.type', {
'test': not type_,
'value': type_,
'old': old_if.get('lxc.network.type'),
'default': 'veth'}),
('lxc.network.name', {
'test': False,
'value': dev,
'old': dev,
'default': dev}),
('lxc.network.flags', {
'test': not flags,
'value': flags,
'old': old_if.get('lxc.network.flags'),
'default': 'up'}),
('lxc.network.link', {
'test': not link,
'value': link,
'old': old_if.get('lxc.network.link'),
'default': search_lxc_bridge()}),
('lxc.network.hwaddr', {
'test': not mac,
'value': mac,
'old': old_if.get('lxc.network.hwaddr'),
'default': salt.utils.network.gen_mac()}),
('lxc.network.ipv4', {
'test': not ipv4,
'value': ipv4,
'old': old_if.get('lxc.network.ipv4', ''),
'default': None}),
('lxc.network.ipv6', {
'test': not ipv6,
'value': ipv6,
'old': old_if.get('lxc.network.ipv6', ''),
'default': None})])
# for each parameter, if not explicitly set, the
# config value present in the LXC configuration should
# take precedence over the profile configuration
for info in list(infos.keys()):
bundle = infos[info]
if bundle['test']:
if bundle['old']:
bundle['value'] = bundle['old']
elif bundle['default']:
bundle['value'] = bundle['default']
for info, data in six.iteritems(infos):
if data['value']:
ret.append({info: data['value']})
for key, val in six.iteritems(args):
if key == 'link' and bridge:
val = bridge
val = opts.get(key, val)
if key in [
'type', 'flags', 'name',
'gateway', 'mac', 'link', 'ipv4', 'ipv6'
]:
continue
ret.append({'lxc.network.{0}'.format(key): val})
# gateway (in automode) must be appended following network conf !
if not gateway:
gateway = args.get('gateway', None)
if gateway is not None and not gateway_set:
ret.append({'lxc.network.ipv4.gateway': gateway})
# only one network gateway ;)
gateway_set = True
# normally, this won't happen
# set the gateway if specified even if we did
# not managed the network underlying
if gateway is not None and not gateway_set:
ret.append({'lxc.network.ipv4.gateway': gateway})
# only one network gateway ;)
gateway_set = True
new = _get_veths(ret)
# verify that we did not loose the mac settings
for iface in [a for a in new]:
ndata = new[iface]
nmac = ndata.get('lxc.network.hwaddr', '')
ntype = ndata.get('lxc.network.type', '')
omac, otype = '', ''
if iface in old:
odata = old[iface]
omac = odata.get('lxc.network.hwaddr', '')
otype = odata.get('lxc.network.type', '')
# default for network type is setted here
# attention not to change the network type
# without a good and explicit reason to.
if otype and not ntype:
ntype = otype
if not ntype:
ntype = 'veth'
new[iface]['lxc.network.type'] = ntype
if omac and not nmac:
new[iface]['lxc.network.hwaddr'] = omac
ret = []
for val in six.itervalues(new):
for row in val:
ret.append(salt.utils.odict.OrderedDict([(row, val[row])]))
# on old versions of lxc, still support the gateway auto mode
# if we didn't explicitly say no to
# (lxc.network.ipv4.gateway: auto)
if _LooseVersion(version()) <= _LooseVersion('1.0.7') and \
True not in ['lxc.network.ipv4.gateway' in a for a in ret] and \
True in ['lxc.network.ipv4' in a for a in ret]:
ret.append({'lxc.network.ipv4.gateway': 'auto'})
return ret
def _get_lxc_default_data(**kwargs):
kwargs = copy.deepcopy(kwargs)
ret = {}
for k in ['utsname', 'rootfs']:
val = kwargs.get(k, None)
if val is not None:
ret['lxc.{0}'.format(k)] = val
autostart = kwargs.get('autostart')
# autostart can have made in kwargs, but with the None
# value which is invalid, we need an explicit boolean
# autostart = on is the default.
if autostart is None:
autostart = True
# we will set the regular lxc marker to restart container at
# machine (re)boot only if we did not explicitly ask
# not to touch to the autostart settings via
# autostart == 'keep'
if autostart != 'keep':
if autostart:
ret['lxc.start.auto'] = '1'
else:
ret['lxc.start.auto'] = '0'
memory = kwargs.get('memory')
if memory is not None:
# converting the config value from MB to bytes
ret['lxc.cgroup.memory.limit_in_bytes'] = memory * 1024 * 1024
cpuset = kwargs.get('cpuset')
if cpuset:
ret['lxc.cgroup.cpuset.cpus'] = cpuset
cpushare = kwargs.get('cpushare')
cpu = kwargs.get('cpu')
if cpushare:
ret['lxc.cgroup.cpu.shares'] = cpushare
if cpu and not cpuset:
ret['lxc.cgroup.cpuset.cpus'] = _rand_cpu_str(cpu)
return ret
def _config_list(conf_tuples=None, only_net=False, **kwargs):
'''
Return a list of dicts from the salt level configurations
conf_tuples
_LXCConfig compatible list of entries which can contain
- string line
- tuple (lxc config param,value)
- dict of one entry: {lxc config param: value)
only_net
by default we add to the tuples a reflection of both
the real config if avalaible and a certain amount of
default values like the cpu parameters, the memory
and etc.
On the other hand, we also no matter the case reflect
the network configuration computed from the actual config if
available and given values.
if no_default_loads is set, we will only
reflect the network configuration back to the conf tuples
list
'''
# explicit cast
only_net = bool(only_net)
if not conf_tuples:
conf_tuples = []
kwargs = copy.deepcopy(kwargs)
ret = []
if not only_net:
default_data = _get_lxc_default_data(**kwargs)
for k, val in six.iteritems(default_data):
ret.append({k: val})
net_datas = _network_conf(conf_tuples=conf_tuples, **kwargs)
ret.extend(net_datas)
return ret
def _get_veths(net_data):
'''
Parse the nic setup inside lxc conf tuples back to a dictionary indexed by
network interface
'''
if isinstance(net_data, dict):
net_data = list(net_data.items())
nics = salt.utils.odict.OrderedDict()
current_nic = salt.utils.odict.OrderedDict()
no_names = True
for item in net_data:
if item and isinstance(item, dict):
item = list(item.items())[0]
# skip LXC configuration comment lines, and play only with tuples conf
elif isinstance(item, six.string_types):
# deal with reflection of commented lxc configs
sitem = item.strip()
if sitem.startswith('#') or not sitem:
continue
elif '=' in item:
item = tuple([a.strip() for a in item.split('=', 1)])
if item[0] == 'lxc.network.type':
current_nic = salt.utils.odict.OrderedDict()
if item[0] == 'lxc.network.name':
no_names = False
nics[item[1].strip()] = current_nic
current_nic[item[0].strip()] = item[1].strip()
# if not ethernet card name has been collected, assuming we collected
# data for eth0
if no_names and current_nic:
nics[DEFAULT_NIC] = current_nic
return nics
class _LXCConfig(object):
'''
LXC configuration data
'''
pattern = re.compile(r'^(\S+)(\s*)(=)(\s*)(.*)')
non_interpretable_pattern = re.compile(r'^((#.*)|(\s*))$')
def __init__(self, **kwargs):
kwargs = copy.deepcopy(kwargs)
self.name = kwargs.pop('name', None)
path = get_root_path(kwargs.get('path', None))
self.data = []
if self.name:
self.path = os.path.join(path, self.name, 'config')
if os.path.isfile(self.path):
with salt.utils.files.fopen(self.path) as fhr:
for line in salt.utils.data.decode(fhr.readlines()):
match = self.pattern.findall((line.strip()))
if match:
self.data.append((match[0][0], match[0][-1]))
match = self.non_interpretable_pattern.findall(
(line.strip()))
if match:
self.data.append(('', match[0][0]))
else:
self.path = None
def _replace(key, val):
if val:
self._filter_data(key)
self.data.append((key, val))
default_data = _get_lxc_default_data(**kwargs)
for key, val in six.iteritems(default_data):
_replace(key, val)
old_net = self._filter_data('lxc.network')
net_datas = _network_conf(conf_tuples=old_net, **kwargs)
if net_datas:
for row in net_datas:
self.data.extend(list(row.items()))
# be sure to reset harmful settings
for idx in ['lxc.cgroup.memory.limit_in_bytes']:
if not default_data.get(idx):
self._filter_data(idx)
def as_string(self):
chunks = ('{0[0]}{1}{0[1]}'.format(item, (' = ' if item[0] else '')) for item in self.data)
return '\n'.join(chunks) + '\n'
def write(self):
if self.path:
content = self.as_string()
# 2 step rendering to be sure not to open/wipe the config
# before as_string succeeds.
with salt.utils.files.fopen(self.path, 'w') as fic:
fic.write(salt.utils.stringutils.to_str(content))
fic.flush()
def tempfile(self):
# this might look like the function name is shadowing the
# module, but it's not since the method belongs to the class
ntf = tempfile.NamedTemporaryFile()
ntf.write(self.as_string())
ntf.flush()
return ntf
def _filter_data(self, pattern):
'''
Removes parameters which match the pattern from the config data
'''
removed = []
filtered = []
for param in self.data:
if not param[0].startswith(pattern):
filtered.append(param)
else:
removed.append(param)
self.data = filtered
return removed
def _get_base(**kwargs):
'''
If the needed base does not exist, then create it, if it does exist
create nothing and return the name of the base lxc container so
it can be cloned.
'''
profile = get_container_profile(copy.deepcopy(kwargs.get('profile')))
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, _marker)
profile_match = profile.pop(key, default)
# let kwarg overrides be the preferred choice
if kw_overrides_match is _marker:
return profile_match
return kw_overrides_match
template = select('template')
image = select('image')
vgname = select('vgname')
path = kwargs.get('path', None)
# remove the above three variables from kwargs, if they exist, to avoid
# duplicates if create() is invoked below.
for param in ('path', 'image', 'vgname', 'template'):
kwargs.pop(param, None)
if image:
proto = _urlparse(image).scheme
img_tar = __salt__['cp.cache_file'](image)
img_name = os.path.basename(img_tar)
hash_ = salt.utils.hashutils.get_hash(
img_tar,
__salt__['config.get']('hash_type'))
name = '__base_{0}_{1}_{2}'.format(proto, img_name, hash_)
if not exists(name, path=path):
create(name, template=template, image=image,
path=path, vgname=vgname, **kwargs)
if vgname:
rootfs = os.path.join('/dev', vgname, name)
edit_conf(info(name, path=path)['config'],
out_format='commented', **{'lxc.rootfs': rootfs})
return name
elif template:
name = '__base_{0}'.format(template)
if not exists(name, path=path):
create(name, template=template, image=image, path=path,
vgname=vgname, **kwargs)
if vgname:
rootfs = os.path.join('/dev', vgname, name)
edit_conf(info(name, path=path)['config'],
out_format='commented', **{'lxc.rootfs': rootfs})
return name
return ''
def init(name,
config=None,
cpuset=None,
cpushare=None,
memory=None,
profile=None,
network_profile=None,
nic_opts=None,
cpu=None,
autostart=True,
password=None,
password_encrypted=None,
users=None,
dnsservers=None,
searchdomains=None,
bridge=None,
gateway=None,
pub_key=None,
priv_key=None,
force_install=False,
unconditional_install=False,
bootstrap_delay=None,
bootstrap_args=None,
bootstrap_shell=None,
bootstrap_url=None,
**kwargs):
'''
Initialize a new container.
This is a partial idempotent function as if it is already provisioned, we
will reset a bit the lxc configuration file but much of the hard work will
be escaped as markers will prevent re-execution of harmful tasks.
name
Name of the container
image
A tar archive to use as the rootfs for the container. Conflicts with
the ``template`` argument.
cpus
Select a random number of cpu cores and assign it to the cpuset, if the
cpuset option is set then this option will be ignored
cpuset
Explicitly define the cpus this container will be bound to
cpushare
cgroups cpu shares
autostart
autostart container on reboot
memory
cgroups memory limit, in MB
.. versionchanged:: 2015.5.0
If no value is passed, no limit is set. In earlier Salt versions,
not passing this value causes a 1024MB memory limit to be set, and
it was necessary to pass ``memory=0`` to set no limit.
gateway
the ipv4 gateway to use
the default does nothing more than lxcutils does
bridge
the bridge to use
the default does nothing more than lxcutils does
network_profile
Network profile to use for the container
.. versionadded:: 2015.5.0
nic_opts
Extra options for network interfaces, will override
``{"eth0": {"hwaddr": "aa:bb:cc:dd:ee:ff", "ipv4": "10.1.1.1", "ipv6": "2001:db8::ff00:42:8329"}}``
or
``{"eth0": {"hwaddr": "aa:bb:cc:dd:ee:ff", "ipv4": "10.1.1.1/24", "ipv6": "2001:db8::ff00:42:8329"}}``
users
Users for which the password defined in the ``password`` param should
be set. Can be passed as a comma separated list or a python list.
Defaults to just the ``root`` user.
password
Set the initial password for the users defined in the ``users``
parameter
password_encrypted : False
Set to ``True`` to denote a password hash instead of a plaintext
password
.. versionadded:: 2015.5.0
profile
A LXC profile (defined in config or pillar).
This can be either a real profile mapping or a string
to retrieve it in configuration
start
Start the newly-created container
dnsservers
list of dns servers to set in the container, default [] (no setting)
seed
Seed the container with the minion config. Default: ``True``
install
If salt-minion is not already installed, install it. Default: ``True``
config
Optional config parameters. By default, the id is set to
the name of the container.
master
salt master (default to minion's master)
master_port
salt master port (default to minion's master port)
pub_key
Explicit public key to preseed the minion with (optional).
This can be either a filepath or a string representing the key
priv_key
Explicit private key to preseed the minion with (optional).
This can be either a filepath or a string representing the key
approve_key
If explicit preseeding is not used;
Attempt to request key approval from the master. Default: ``True``
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
clone_from
Original from which to use a clone operation to create the container.
Default: ``None``
bootstrap_delay
Delay in seconds between end of container creation and bootstrapping.
Useful when waiting for container to obtain a DHCP lease.
.. versionadded:: 2015.5.0
bootstrap_url
See lxc.bootstrap
bootstrap_shell
See lxc.bootstrap
bootstrap_args
See lxc.bootstrap
force_install
Force installation even if salt-minion is detected,
this is the way to run vendor bootstrap scripts even
if a salt minion is already present in the container
unconditional_install
Run the script even if the container seems seeded
CLI Example:
.. code-block:: bash
salt 'minion' lxc.init name [cpuset=cgroups_cpuset] \\
[cpushare=cgroups_cpushare] [memory=cgroups_memory] \\
[nic=nic_profile] [profile=lxc_profile] \\
[nic_opts=nic_opts] [start=(True|False)] \\
[seed=(True|False)] [install=(True|False)] \\
[config=minion_config] [approve_key=(True|False) \\
[clone_from=original] [autostart=True] \\
[priv_key=/path_or_content] [pub_key=/path_or_content] \\
[bridge=lxcbr0] [gateway=10.0.3.1] \\
[dnsservers[dns1,dns2]] \\
[users=[foo]] [password='secret'] \\
[password_encrypted=(True|False)]
'''
ret = {'name': name,
'changes': {}}
profile = get_container_profile(copy.deepcopy(profile))
if not network_profile:
network_profile = profile.get('network_profile')
if not network_profile:
network_profile = DEFAULT_NIC
# Changes is a pointer to changes_dict['init']. This method is used so that
# we can have a list of changes as they are made, providing an ordered list
# of things that were changed.
changes_dict = {'init': []}
changes = changes_dict.get('init')
if users is None:
users = []
dusers = ['root']
for user in dusers:
if user not in users:
users.append(user)
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, _marker)
profile_match = profile.pop(key, default)
# let kwarg overrides be the preferred choice
if kw_overrides_match is _marker:
return profile_match
return kw_overrides_match
path = select('path')
bpath = get_root_path(path)
state_pre = state(name, path=path)
tvg = select('vgname')
vgname = tvg if tvg else __salt__['config.get']('lxc.vgname')
start_ = select('start', True)
autostart = select('autostart', autostart)
seed = select('seed', True)
install = select('install', True)
seed_cmd = select('seed_cmd')
salt_config = _get_salt_config(config, **kwargs)
approve_key = select('approve_key', True)
clone_from = select('clone_from')
# If using a volume group then set up to make snapshot cow clones
if vgname and not clone_from:
try:
kwargs['vgname'] = vgname
clone_from = _get_base(profile=profile, **kwargs)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = exc.strerror
if changes:
ret['changes'] = changes_dict
return ret
if not kwargs.get('snapshot') is False:
kwargs['snapshot'] = True
does_exist = exists(name, path=path)
to_reboot = False
remove_seed_marker = False
if does_exist:
pass
elif clone_from:
remove_seed_marker = True
try:
clone(name, clone_from, profile=profile, **kwargs)
changes.append({'create': 'Container cloned'})
except (SaltInvocationError, CommandExecutionError) as exc:
if 'already exists' in exc.strerror:
changes.append({'create': 'Container already exists'})
else:
ret['result'] = False
ret['comment'] = exc.strerror
if changes:
ret['changes'] = changes_dict
return ret
cfg = _LXCConfig(name=name, network_profile=network_profile,
nic_opts=nic_opts, bridge=bridge, path=path,
gateway=gateway, autostart=autostart,
cpuset=cpuset, cpushare=cpushare, memory=memory)
old_chunks = read_conf(cfg.path, out_format='commented')
cfg.write()
chunks = read_conf(cfg.path, out_format='commented')
if old_chunks != chunks:
to_reboot = True
else:
remove_seed_marker = True
cfg = _LXCConfig(network_profile=network_profile,
nic_opts=nic_opts, cpuset=cpuset, path=path,
bridge=bridge, gateway=gateway,
autostart=autostart,
cpushare=cpushare, memory=memory)
with cfg.tempfile() as cfile:
try:
create(name, config=cfile.name, profile=profile, **kwargs)
changes.append({'create': 'Container created'})
except (SaltInvocationError, CommandExecutionError) as exc:
if 'already exists' in exc.strerror:
changes.append({'create': 'Container already exists'})
else:
ret['comment'] = exc.strerror
if changes:
ret['changes'] = changes_dict
return ret
cpath = os.path.join(bpath, name, 'config')
old_chunks = []
if os.path.exists(cpath):
old_chunks = read_conf(cpath, out_format='commented')
new_cfg = _config_list(conf_tuples=old_chunks,
cpu=cpu,
network_profile=network_profile,
nic_opts=nic_opts, bridge=bridge,
cpuset=cpuset, cpushare=cpushare,
memory=memory)
if new_cfg:
edit_conf(cpath, out_format='commented', lxc_config=new_cfg)
chunks = read_conf(cpath, out_format='commented')
if old_chunks != chunks:
to_reboot = True
# last time to be sure any of our property is correctly applied
cfg = _LXCConfig(name=name, network_profile=network_profile,
nic_opts=nic_opts, bridge=bridge, path=path,
gateway=gateway, autostart=autostart,
cpuset=cpuset, cpushare=cpushare, memory=memory)
old_chunks = []
if os.path.exists(cfg.path):
old_chunks = read_conf(cfg.path, out_format='commented')
cfg.write()
chunks = read_conf(cfg.path, out_format='commented')
if old_chunks != chunks:
changes.append({'config': 'Container configuration updated'})
to_reboot = True
if to_reboot:
try:
stop(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
if changes:
ret['changes'] = changes_dict
return ret
if not does_exist or (does_exist and state(name, path=path) != 'running'):
try:
start(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
if changes:
ret['changes'] = changes_dict
return ret
if remove_seed_marker:
run(name,
'rm -f \'{0}\''.format(SEED_MARKER),
path=path,
chroot_fallback=False,
python_shell=False)
# set the default user/password, only the first time
if ret.get('result', True) and password:
gid = '/.lxc.initial_pass'
gids = [gid,
'/lxc.initial_pass',
'/.lxc.{0}.initial_pass'.format(name)]
if not any(retcode(name,
'test -e "{0}"'.format(x),
chroot_fallback=True,
path=path,
ignore_retcode=True) == 0
for x in gids):
# think to touch the default user generated by default templates
# which has a really unsecure passwords...
# root is defined as a member earlier in the code
for default_user in ['ubuntu']:
if (
default_user not in users and
retcode(name,
'id {0}'.format(default_user),
python_shell=False,
path=path,
chroot_fallback=True,
ignore_retcode=True) == 0
):
users.append(default_user)
for user in users:
try:
cret = set_password(name,
users=[user],
path=path,
password=password,
encrypted=password_encrypted)
except (SaltInvocationError, CommandExecutionError) as exc:
msg = '{0}: Failed to set password'.format(
user) + exc.strerror
# only hardfail in unrecoverable situation:
# root cannot be setted up
if user == 'root':
ret['comment'] = msg
ret['result'] = False
else:
log.debug(msg)
if ret.get('result', True):
changes.append({'password': 'Password(s) updated'})
if retcode(name,
('sh -c \'touch "{0}"; test -e "{0}"\''
.format(gid)),
path=path,
chroot_fallback=True,
ignore_retcode=True) != 0:
ret['comment'] = 'Failed to set password marker'
changes[-1]['password'] += '. ' + ret['comment'] + '.'
ret['result'] = False
# set dns servers if any, only the first time
if ret.get('result', True) and dnsservers:
# retro compatibility, test also old markers
gid = '/.lxc.initial_dns'
gids = [gid,
'/lxc.initial_dns',
'/lxc.{0}.initial_dns'.format(name)]
if not any(retcode(name,
'test -e "{0}"'.format(x),
chroot_fallback=True,
path=path,
ignore_retcode=True) == 0
for x in gids):
try:
set_dns(name,
path=path,
dnsservers=dnsservers,
searchdomains=searchdomains)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Failed to set DNS: ' + exc.strerror
ret['result'] = False
else:
changes.append({'dns': 'DNS updated'})
if retcode(name,
('sh -c \'touch "{0}"; test -e "{0}"\''
.format(gid)),
chroot_fallback=True,
path=path,
ignore_retcode=True) != 0:
ret['comment'] = 'Failed to set DNS marker'
changes[-1]['dns'] += '. ' + ret['comment'] + '.'
ret['result'] = False
# retro compatibility, test also old markers
if remove_seed_marker:
run(name,
'rm -f \'{0}\''.format(SEED_MARKER),
path=path,
python_shell=False)
gid = '/.lxc.initial_seed'
gids = [gid, '/lxc.initial_seed']
if (
any(retcode(name,
'test -e {0}'.format(x),
path=path,
chroot_fallback=True,
ignore_retcode=True) == 0
for x in gids) or not ret.get('result', True)
):
pass
elif seed or seed_cmd:
if seed:
try:
result = bootstrap(
name, config=salt_config, path=path,
approve_key=approve_key,
pub_key=pub_key, priv_key=priv_key,
install=install,
force_install=force_install,
unconditional_install=unconditional_install,
bootstrap_delay=bootstrap_delay,
bootstrap_url=bootstrap_url,
bootstrap_shell=bootstrap_shell,
bootstrap_args=bootstrap_args)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Bootstrap failed: ' + exc.strerror
ret['result'] = False
else:
if not result:
ret['comment'] = ('Bootstrap failed, see minion log for '
'more information')
ret['result'] = False
else:
changes.append(
{'bootstrap': 'Container successfully bootstrapped'}
)
elif seed_cmd:
try:
result = __salt__[seed_cmd](info(name, path=path)['rootfs'],
name,
salt_config)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = ('Bootstrap via seed_cmd \'{0}\' failed: {1}'
.format(seed_cmd, exc.strerror))
ret['result'] = False
else:
if not result:
ret['comment'] = ('Bootstrap via seed_cmd \'{0}\' failed, '
'see minion log for more information '
.format(seed_cmd))
ret['result'] = False
else:
changes.append(
{'bootstrap': 'Container successfully bootstrapped '
'using seed_cmd \'{0}\''
.format(seed_cmd)}
)
if ret.get('result', True) and not start_:
try:
stop(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
ret['result'] = False
state_post = state(name, path=path)
if state_pre != state_post:
changes.append({'state': {'old': state_pre, 'new': state_post}})
if ret.get('result', True):
ret['comment'] = ('Container \'{0}\' successfully initialized'
.format(name))
ret['result'] = True
if changes:
ret['changes'] = changes_dict
return ret
def cloud_init(name, vm_=None, **kwargs):
'''
Thin wrapper to lxc.init to be used from the saltcloud lxc driver
name
Name of the container
may be None and then guessed from saltcloud mapping
`vm_`
saltcloud mapping defaults for the vm
CLI Example:
.. code-block:: bash
salt '*' lxc.cloud_init foo
'''
init_interface = cloud_init_interface(name, vm_, **kwargs)
name = init_interface.pop('name', name)
return init(name, **init_interface)
def images(dist=None):
'''
.. versionadded:: 2015.5.0
List the available images for LXC's ``download`` template.
dist : None
Filter results to a single Linux distribution
CLI Examples:
.. code-block:: bash
salt myminion lxc.images
salt myminion lxc.images dist=centos
'''
out = __salt__['cmd.run_stdout'](
'lxc-create -n __imgcheck -t download -- --list',
ignore_retcode=True
)
if 'DIST' not in out:
raise CommandExecutionError(
'Unable to run the \'download\' template script. Is it installed?'
)
ret = {}
passed_header = False
for line in out.splitlines():
try:
distro, release, arch, variant, build_time = line.split()
except ValueError:
continue
if not passed_header:
if distro == 'DIST':
passed_header = True
continue
dist_list = ret.setdefault(distro, [])
dist_list.append({
'release': release,
'arch': arch,
'variant': variant,
'build_time': build_time,
})
if dist is not None:
return dict([(dist, ret.get(dist, []))])
return ret
def templates():
'''
.. versionadded:: 2015.5.0
List the available LXC template scripts installed on the minion
CLI Examples:
.. code-block:: bash
salt myminion lxc.templates
'''
try:
template_scripts = os.listdir('/usr/share/lxc/templates')
except OSError:
return []
else:
return [x[4:] for x in template_scripts if x.startswith('lxc-')]
def _after_ignition_network_profile(cmd,
ret,
name,
network_profile,
path,
nic_opts):
_clear_context()
if ret['retcode'] == 0 and exists(name, path=path):
if network_profile:
network_changes = apply_network_profile(name,
network_profile,
path=path,
nic_opts=nic_opts)
if network_changes:
log.info(
'Network changes from applying network profile \'%s\' '
'to newly-created container \'%s\':\n%s',
network_profile, name, network_changes
)
c_state = state(name, path=path)
return {'result': True,
'state': {'old': None, 'new': c_state}}
else:
if exists(name, path=path):
# destroy the container if it was partially created
cmd = 'lxc-destroy'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0}'.format(name)
__salt__['cmd.retcode'](cmd, python_shell=False)
raise CommandExecutionError(
'Container could not be created with cmd \'{0}\': {1}'
.format(cmd, ret['stderr'])
)
def create(name,
config=None,
profile=None,
network_profile=None,
nic_opts=None,
**kwargs):
'''
Create a new container.
name
Name of the container
config
The config file to use for the container. Defaults to system-wide
config (usually in /etc/lxc/lxc.conf).
profile
Profile to use in container creation (see
:mod:`lxc.get_container_profile
<salt.modules.lxc.get_container_profile>`). Values in a profile will be
overridden by the **Container Creation Arguments** listed below.
network_profile
Network profile to use for container
.. versionadded:: 2015.5.0
**Container Creation Arguments**
template
The template to use. For example, ``ubuntu`` or ``fedora``.
For a full list of available templates, check out
the :mod:`lxc.templates <salt.modules.lxc.templates>` function.
Conflicts with the ``image`` argument.
.. note::
The ``download`` template requires the following three parameters
to be defined in ``options``:
* **dist** - The name of the distribution
* **release** - Release name/version
* **arch** - Architecture of the container
The available images can be listed using the :mod:`lxc.images
<salt.modules.lxc.images>` function.
options
Template-specific options to pass to the lxc-create command. These
correspond to the long options (ones beginning with two dashes) that
the template script accepts. For example:
.. code-block:: bash
options='{"dist": "centos", "release": "6", "arch": "amd64"}'
For available template options, refer to the lxc template scripts
which are ususally located under ``/usr/share/lxc/templates``,
or run ``lxc-create -t <template> -h``.
image
A tar archive to use as the rootfs for the container. Conflicts with
the ``template`` argument.
backing
The type of storage to use. Set to ``lvm`` to use an LVM group.
Defaults to filesystem within /var/lib/lxc.
fstype
Filesystem type to use on LVM logical volume
size : 1G
Size of the volume to create. Only applicable if ``backing=lvm``.
vgname : lxc
Name of the LVM volume group in which to create the volume for this
container. Only applicable if ``backing=lvm``.
lvname
Name of the LVM logical volume in which to create the volume for this
container. Only applicable if ``backing=lvm``.
thinpool
Name of a pool volume that will be used for thin-provisioning this
container. Only applicable if ``backing=lvm``.
nic_opts
give extra opts overriding network profile values
path
parent path for the container creation (default: /var/lib/lxc)
zfsroot
Name of the ZFS root in which to create the volume for this container.
Only applicable if ``backing=zfs``. (default: tank/lxc)
.. versionadded:: 2015.8.0
'''
# Required params for 'download' template
download_template_deps = ('dist', 'release', 'arch')
cmd = 'lxc-create -n {0}'.format(name)
profile = get_container_profile(copy.deepcopy(profile))
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, None)
profile_match = profile.pop(key, default)
# Return the profile match if the the kwarg match was None, as the
# lxc.present state will pass these kwargs set to None by default.
if kw_overrides_match is None:
return profile_match
return kw_overrides_match
path = select('path')
if exists(name, path=path):
raise CommandExecutionError(
'Container \'{0}\' already exists'.format(name)
)
tvg = select('vgname')
vgname = tvg if tvg else __salt__['config.get']('lxc.vgname')
# The 'template' and 'image' params conflict
template = select('template')
image = select('image')
if template and image:
raise SaltInvocationError(
'Only one of \'template\' and \'image\' is permitted'
)
elif not any((template, image, profile)):
raise SaltInvocationError(
'At least one of \'template\', \'image\', and \'profile\' is '
'required'
)
options = select('options') or {}
backing = select('backing')
if vgname and not backing:
backing = 'lvm'
lvname = select('lvname')
thinpool = select('thinpool')
fstype = select('fstype')
size = select('size', '1G')
zfsroot = select('zfsroot')
if backing in ('dir', 'overlayfs', 'btrfs', 'zfs'):
fstype = None
size = None
# some backends won't support some parameters
if backing in ('aufs', 'dir', 'overlayfs', 'btrfs'):
lvname = vgname = thinpool = None
if image:
img_tar = __salt__['cp.cache_file'](image)
template = os.path.join(
os.path.dirname(salt.__file__),
'templates',
'lxc',
'salt_tarball')
options['imgtar'] = img_tar
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
if not os.path.exists(path):
os.makedirs(path)
if config:
cmd += ' -f {0}'.format(config)
if template:
cmd += ' -t {0}'.format(template)
if backing:
backing = backing.lower()
cmd += ' -B {0}'.format(backing)
if backing in ('zfs',):
if zfsroot:
cmd += ' --zfsroot {0}'.format(zfsroot)
if backing in ('lvm',):
if lvname:
cmd += ' --lvname {0}'.format(lvname)
if vgname:
cmd += ' --vgname {0}'.format(vgname)
if thinpool:
cmd += ' --thinpool {0}'.format(thinpool)
if backing not in ('dir', 'overlayfs'):
if fstype:
cmd += ' --fstype {0}'.format(fstype)
if size:
cmd += ' --fssize {0}'.format(size)
if options:
if template == 'download':
missing_deps = [x for x in download_template_deps
if x not in options]
if missing_deps:
raise SaltInvocationError(
'Missing params in \'options\' dict: {0}'
.format(', '.join(missing_deps))
)
cmd += ' --'
for key, val in six.iteritems(options):
cmd += ' --{0} {1}'.format(key, val)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
# please do not merge extra conflicting stuff
# inside those two line (ret =, return)
return _after_ignition_network_profile(cmd,
ret,
name,
network_profile,
path,
nic_opts)
def clone(name,
orig,
profile=None,
network_profile=None,
nic_opts=None,
**kwargs):
'''
Create a new container as a clone of another container
name
Name of the container
orig
Name of the original container to be cloned
profile
Profile to use in container cloning (see
:mod:`lxc.get_container_profile
<salt.modules.lxc.get_container_profile>`). Values in a profile will be
overridden by the **Container Cloning Arguments** listed below.
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
**Container Cloning Arguments**
snapshot
Use Copy On Write snapshots (LVM)
size : 1G
Size of the volume to create. Only applicable if ``backing=lvm``.
backing
The type of storage to use. Set to ``lvm`` to use an LVM group.
Defaults to filesystem within /var/lib/lxc.
network_profile
Network profile to use for container
.. versionadded:: 2015.8.0
nic_opts
give extra opts overriding network profile values
.. versionadded:: 2015.8.0
CLI Examples:
.. code-block:: bash
salt '*' lxc.clone myclone orig=orig_container
salt '*' lxc.clone myclone orig=orig_container snapshot=True
'''
profile = get_container_profile(copy.deepcopy(profile))
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, None)
profile_match = profile.pop(key, default)
# let kwarg overrides be the preferred choice
if kw_overrides_match is None:
return profile_match
return kw_overrides_match
path = select('path')
if exists(name, path=path):
raise CommandExecutionError(
'Container \'{0}\' already exists'.format(name)
)
_ensure_exists(orig, path=path)
if state(orig, path=path) != 'stopped':
raise CommandExecutionError(
'Container \'{0}\' must be stopped to be cloned'.format(orig)
)
backing = select('backing')
snapshot = select('snapshot')
if backing in ('dir',):
snapshot = False
if not snapshot:
snapshot = ''
else:
snapshot = '-s'
size = select('size', '1G')
if backing in ('dir', 'overlayfs', 'btrfs'):
size = None
# LXC commands and options changed in 2.0 - CF issue #34086 for details
if _LooseVersion(version()) >= _LooseVersion('2.0'):
# https://linuxcontainers.org/lxc/manpages//man1/lxc-copy.1.html
cmd = 'lxc-copy'
cmd += ' {0} -n {1} -N {2}'.format(snapshot, orig, name)
else:
# https://linuxcontainers.org/lxc/manpages//man1/lxc-clone.1.html
cmd = 'lxc-clone'
cmd += ' {0} -o {1} -n {2}'.format(snapshot, orig, name)
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
if not os.path.exists(path):
os.makedirs(path)
if backing:
backing = backing.lower()
cmd += ' -B {0}'.format(backing)
if backing not in ('dir', 'overlayfs'):
if size:
cmd += ' -L {0}'.format(size)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
# please do not merge extra conflicting stuff
# inside those two line (ret =, return)
return _after_ignition_network_profile(cmd,
ret,
name,
network_profile,
path,
nic_opts)
def ls_(active=None, cache=True, path=None):
'''
Return a list of the containers available on the minion
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
active
If ``True``, return only active (i.e. running) containers
.. versionadded:: 2015.5.0
CLI Example:
.. code-block:: bash
salt '*' lxc.ls
salt '*' lxc.ls active=True
'''
contextvar = 'lxc.ls{0}'.format(path)
if active:
contextvar += '.active'
if cache and (contextvar in __context__):
return __context__[contextvar]
else:
ret = []
cmd = 'lxc-ls'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
if active:
cmd += ' --active'
output = __salt__['cmd.run_stdout'](cmd, python_shell=False)
for line in output.splitlines():
ret.extend(line.split())
__context__[contextvar] = ret
return ret
def list_(extra=False, limit=None, path=None):
'''
List containers classified by state
extra
Also get per-container specific info. This will change the return data.
Instead of returning a list of containers, a dictionary of containers
and each container's output from :mod:`lxc.info
<salt.modules.lxc.info>`.
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
limit
Return output matching a specific state (**frozen**, **running**, or
**stopped**).
.. versionadded:: 2015.5.0
CLI Examples:
.. code-block:: bash
salt '*' lxc.list
salt '*' lxc.list extra=True
salt '*' lxc.list limit=running
'''
ctnrs = ls_(path=path)
if extra:
stopped = {}
frozen = {}
running = {}
else:
stopped = []
frozen = []
running = []
ret = {'running': running,
'stopped': stopped,
'frozen': frozen}
for container in ctnrs:
cmd = 'lxc-info'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0}'.format(container)
c_info = __salt__['cmd.run'](
cmd,
python_shell=False,
output_loglevel='debug'
)
c_state = None
for line in c_info.splitlines():
stat = line.split(':')
if stat[0] in ('State', 'state'):
c_state = stat[1].strip()
break
if not c_state or (limit is not None and c_state.lower() != limit):
continue
if extra:
infos = info(container, path=path)
method = 'update'
value = {container: infos}
else:
method = 'append'
value = container
if c_state == 'STOPPED':
getattr(stopped, method)(value)
continue
if c_state == 'FROZEN':
getattr(frozen, method)(value)
continue
if c_state == 'RUNNING':
getattr(running, method)(value)
continue
if limit is not None:
return ret.get(limit, {} if extra else [])
return ret
def _change_state(cmd,
name,
expected,
stdin=_marker,
stdout=_marker,
stderr=_marker,
with_communicate=_marker,
use_vt=_marker,
path=None):
pre = state(name, path=path)
if pre == expected:
return {'result': True,
'state': {'old': expected, 'new': expected},
'comment': 'Container \'{0}\' already {1}'
.format(name, expected)}
if cmd == 'lxc-destroy':
# Kill the container first
scmd = 'lxc-stop'
if path:
scmd += ' -P {0}'.format(pipes.quote(path))
scmd += ' -k -n {0}'.format(name)
__salt__['cmd.run'](scmd,
python_shell=False)
if path and ' -P ' not in cmd:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0}'.format(name)
# certain lxc commands need to be taken with care (lxc-start)
# as te command itself mess with double forks; we must not
# communicate with it, but just wait for the exit status
pkwargs = {'python_shell': False,
'redirect_stderr': True,
'with_communicate': with_communicate,
'use_vt': use_vt,
'stdin': stdin,
'stdout': stdout}
for i in [a for a in pkwargs]:
val = pkwargs[i]
if val is _marker:
pkwargs.pop(i, None)
_cmdout = __salt__['cmd.run_all'](cmd, **pkwargs)
if _cmdout['retcode'] != 0:
raise CommandExecutionError(
'Error changing state for container \'{0}\' using command '
'\'{1}\': {2}'.format(name, cmd, _cmdout['stdout'])
)
if expected is not None:
# some commands do not wait, so we will
rcmd = 'lxc-wait'
if path:
rcmd += ' -P {0}'.format(pipes.quote(path))
rcmd += ' -n {0} -s {1}'.format(name, expected.upper())
__salt__['cmd.run'](rcmd, python_shell=False, timeout=30)
_clear_context()
post = state(name, path=path)
ret = {'result': post == expected,
'state': {'old': pre, 'new': post}}
return ret
def _ensure_exists(name, path=None):
'''
Raise an exception if the container does not exist
'''
if not exists(name, path=path):
raise CommandExecutionError(
'Container \'{0}\' does not exist'.format(name)
)
def _ensure_running(name, no_start=False, path=None):
'''
If the container is not currently running, start it. This function returns
the state that the container was in before changing
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
'''
_ensure_exists(name, path=path)
pre = state(name, path=path)
if pre == 'running':
# This will be a no-op but running the function will give us a pretty
# return dict.
return start(name, path=path)
elif pre == 'stopped':
if no_start:
raise CommandExecutionError(
'Container \'{0}\' is not running'.format(name)
)
return start(name, path=path)
elif pre == 'frozen':
if no_start:
raise CommandExecutionError(
'Container \'{0}\' is not running'.format(name)
)
return unfreeze(name, path=path)
def restart(name, path=None, lxc_config=None, force=False):
'''
.. versionadded:: 2015.5.0
Restart the named container. If the container was not running, the
container will merely be started.
name
The name of the container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
lxc_config
path to a lxc config file
config file will be guessed from container name otherwise
.. versionadded:: 2015.8.0
force : False
If ``True``, the container will be force-stopped instead of gracefully
shut down
CLI Example:
.. code-block:: bash
salt myminion lxc.restart name
'''
_ensure_exists(name, path=path)
orig_state = state(name, path=path)
if orig_state != 'stopped':
stop(name, kill=force, path=path)
ret = start(name, path=path, lxc_config=lxc_config)
ret['state']['old'] = orig_state
if orig_state != 'stopped':
ret['restarted'] = True
return ret
def start(name, **kwargs):
'''
Start the named container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
lxc_config
path to a lxc config file
config file will be guessed from container name otherwise
.. versionadded:: 2015.8.0
use_vt
run the command through VT
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.start name
'''
path = kwargs.get('path', None)
cpath = get_root_path(path)
lxc_config = kwargs.get('lxc_config', None)
cmd = 'lxc-start'
if not lxc_config:
lxc_config = os.path.join(cpath, name, 'config')
# we try to start, even without config, if global opts are there
if os.path.exists(lxc_config):
cmd += ' -f {0}'.format(pipes.quote(lxc_config))
cmd += ' -d'
_ensure_exists(name, path=path)
if state(name, path=path) == 'frozen':
raise CommandExecutionError(
'Container \'{0}\' is frozen, use lxc.unfreeze'.format(name)
)
# lxc-start daemonize itself violently, we must not communicate with it
use_vt = kwargs.get('use_vt', None)
with_communicate = kwargs.get('with_communicate', False)
return _change_state(cmd, name, 'running',
stdout=None,
stderr=None,
stdin=None,
with_communicate=with_communicate,
path=path,
use_vt=use_vt)
def stop(name, kill=False, path=None, use_vt=None):
'''
Stop the named container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
kill: False
Do not wait for the container to stop, kill all tasks in the container.
Older LXC versions will stop containers like this irrespective of this
argument.
.. versionchanged:: 2015.5.0
Default value changed to ``False``
use_vt
run the command through VT
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.stop name
'''
_ensure_exists(name, path=path)
orig_state = state(name, path=path)
if orig_state == 'frozen' and not kill:
# Gracefully stopping a frozen container is slower than unfreezing and
# then stopping it (at least in my testing), so if we're not
# force-stopping the container, unfreeze it first.
unfreeze(name, path=path)
cmd = 'lxc-stop'
if kill:
cmd += ' -k'
ret = _change_state(cmd, name, 'stopped', use_vt=use_vt, path=path)
ret['state']['old'] = orig_state
return ret
def freeze(name, **kwargs):
'''
Freeze the named container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
start : False
If ``True`` and the container is stopped, the container will be started
before attempting to freeze.
.. versionadded:: 2015.5.0
use_vt
run the command through VT
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.freeze name
'''
use_vt = kwargs.get('use_vt', None)
path = kwargs.get('path', None)
_ensure_exists(name, path=path)
orig_state = state(name, path=path)
start_ = kwargs.get('start', False)
if orig_state == 'stopped':
if not start_:
raise CommandExecutionError(
'Container \'{0}\' is stopped'.format(name)
)
start(name, path=path)
cmd = 'lxc-freeze'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
ret = _change_state(cmd, name, 'frozen', use_vt=use_vt, path=path)
if orig_state == 'stopped' and start_:
ret['state']['old'] = orig_state
ret['started'] = True
ret['state']['new'] = state(name, path=path)
return ret
def destroy(name, stop=False, path=None):
'''
Destroy the named container.
.. warning::
Destroys all data associated with the container.
path
path to the container parent directory (default: /var/lib/lxc)
.. versionadded:: 2015.8.0
stop : False
If ``True``, the container will be destroyed even if it is
running/frozen.
.. versionchanged:: 2015.5.0
Default value changed to ``False``. This more closely matches the
behavior of ``lxc-destroy(1)``, and also makes it less likely that
an accidental command will destroy a running container that was
being used for important things.
CLI Examples:
.. code-block:: bash
salt '*' lxc.destroy foo
salt '*' lxc.destroy foo stop=True
'''
_ensure_exists(name, path=path)
if not stop and state(name, path=path) != 'stopped':
raise CommandExecutionError(
'Container \'{0}\' is not stopped'.format(name)
)
return _change_state('lxc-destroy', name, None, path=path)
# Compatibility between LXC and nspawn
remove = salt.utils.functools.alias_function(destroy, 'remove')
def exists(name, path=None):
'''
Returns whether the named container exists.
path
path to the container parent directory (default: /var/lib/lxc)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.exists name
'''
_exists = name in ls_(path=path)
# container may be just created but we did cached earlier the
# lxc-ls results
if not _exists:
_exists = name in ls_(cache=False, path=path)
return _exists
def state(name, path=None):
'''
Returns the state of a container.
path
path to the container parent directory (default: /var/lib/lxc)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.state name
'''
# Don't use _ensure_exists() here, it will mess with _change_state()
cachekey = 'lxc.state.{0}{1}'.format(name, path)
try:
return __context__[cachekey]
except KeyError:
if not exists(name, path=path):
__context__[cachekey] = None
else:
cmd = 'lxc-info'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0}'.format(name)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
if ret['retcode'] != 0:
_clear_context()
raise CommandExecutionError(
'Unable to get state of container \'{0}\''.format(name)
)
c_infos = ret['stdout'].splitlines()
c_state = None
for c_info in c_infos:
stat = c_info.split(':')
if stat[0].lower() == 'state':
c_state = stat[1].strip().lower()
break
__context__[cachekey] = c_state
return __context__[cachekey]
def get_parameter(name, parameter, path=None):
'''
Returns the value of a cgroup parameter for a container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.get_parameter container_name memory.limit_in_bytes
'''
_ensure_exists(name, path=path)
cmd = 'lxc-cgroup'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0} {1}'.format(name, parameter)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
if ret['retcode'] != 0:
raise CommandExecutionError(
'Unable to retrieve value for \'{0}\''.format(parameter)
)
return ret['stdout'].strip()
def set_parameter(name, parameter, value, path=None):
'''
Set the value of a cgroup parameter for a container.
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.set_parameter name parameter value
'''
if not exists(name, path=path):
return None
cmd = 'lxc-cgroup'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0} {1} {2}'.format(name, parameter, value)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
if ret['retcode'] != 0:
return False
else:
return True
def info(name, path=None):
'''
Returns information about a container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.info name
'''
cachekey = 'lxc.info.{0}{1}'.format(name, path)
try:
return __context__[cachekey]
except KeyError:
_ensure_exists(name, path=path)
cpath = get_root_path(path)
try:
conf_file = os.path.join(cpath, name, 'config')
except AttributeError:
conf_file = os.path.join(cpath, six.text_type(name), 'config')
if not os.path.isfile(conf_file):
raise CommandExecutionError(
'LXC config file {0} does not exist'.format(conf_file)
)
ret = {}
config = []
with salt.utils.files.fopen(conf_file) as fp_:
for line in fp_:
line = salt.utils.stringutils.to_unicode(line)
comps = [x.strip() for x in
line.split('#', 1)[0].strip().split('=', 1)]
if len(comps) == 2:
config.append(tuple(comps))
ifaces = []
current = None
for key, val in config:
if key == 'lxc.network.type':
current = {'type': val}
ifaces.append(current)
elif not current:
continue
elif key.startswith('lxc.network.'):
current[key.replace('lxc.network.', '', 1)] = val
if ifaces:
ret['nics'] = ifaces
ret['rootfs'] = next(
(x[1] for x in config if x[0] == 'lxc.rootfs'),
None
)
ret['state'] = state(name, path=path)
ret['ips'] = []
ret['public_ips'] = []
ret['private_ips'] = []
ret['public_ipv4_ips'] = []
ret['public_ipv6_ips'] = []
ret['private_ipv4_ips'] = []
ret['private_ipv6_ips'] = []
ret['ipv4_ips'] = []
ret['ipv6_ips'] = []
ret['size'] = None
ret['config'] = conf_file
if ret['state'] == 'running':
try:
limit = int(get_parameter(name, 'memory.limit_in_bytes'))
except (CommandExecutionError, TypeError, ValueError):
limit = 0
try:
usage = int(get_parameter(name, 'memory.usage_in_bytes'))
except (CommandExecutionError, TypeError, ValueError):
usage = 0
free = limit - usage
ret['memory_limit'] = limit
ret['memory_free'] = free
size = run_stdout(name, 'df /', path=path, python_shell=False)
# The size is the 2nd column of the last line
ret['size'] = size.splitlines()[-1].split()[1]
# First try iproute2
ip_cmd = run_all(
name, 'ip link show', path=path, python_shell=False)
if ip_cmd['retcode'] == 0:
ip_data = ip_cmd['stdout']
ip_cmd = run_all(
name, 'ip addr show', path=path, python_shell=False)
ip_data += '\n' + ip_cmd['stdout']
ip_data = salt.utils.network._interfaces_ip(ip_data)
else:
# That didn't work, try ifconfig
ip_cmd = run_all(
name, 'ifconfig', path=path, python_shell=False)
if ip_cmd['retcode'] == 0:
ip_data = \
salt.utils.network._interfaces_ifconfig(
ip_cmd['stdout'])
else:
# Neither was successful, give up
log.warning(
'Unable to run ip or ifconfig in container \'%s\'', name
)
ip_data = {}
ret['ipv4_ips'] = salt.utils.network.ip_addrs(
include_loopback=True,
interface_data=ip_data
)
ret['ipv6_ips'] = salt.utils.network.ip_addrs6(
include_loopback=True,
interface_data=ip_data
)
ret['ips'] = ret['ipv4_ips'] + ret['ipv6_ips']
for address in ret['ipv4_ips']:
if address == '127.0.0.1':
ret['private_ips'].append(address)
ret['private_ipv4_ips'].append(address)
elif salt.utils.cloud.is_public_ip(address):
ret['public_ips'].append(address)
ret['public_ipv4_ips'].append(address)
else:
ret['private_ips'].append(address)
ret['private_ipv4_ips'].append(address)
for address in ret['ipv6_ips']:
if address == '::1' or address.startswith('fe80'):
ret['private_ips'].append(address)
ret['private_ipv6_ips'].append(address)
else:
ret['public_ips'].append(address)
ret['public_ipv6_ips'].append(address)
for key in [x for x in ret if x == 'ips' or x.endswith('ips')]:
ret[key].sort(key=_ip_sort)
__context__[cachekey] = ret
return __context__[cachekey]
def set_password(name, users, password, encrypted=True, path=None):
'''
.. versionchanged:: 2015.5.0
Function renamed from ``set_pass`` to ``set_password``. Additionally,
this function now supports (and defaults to using) a password hash
instead of a plaintext password.
Set the password of one or more system users inside containers
users
Comma-separated list (or python list) of users to change password
password
Password to set for the specified user(s)
encrypted : True
If true, ``password`` must be a password hash. Set to ``False`` to set
a plaintext password (not recommended).
.. versionadded:: 2015.5.0
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.set_pass container-name root '$6$uJ2uAyLU$KoI67t8As/0fXtJOPcHKGXmUpcoYUcVR2K6x93walnShTCQvjRwq25yIkiCBOqgbfdKQSFnAo28/ek6716vEV1'
salt '*' lxc.set_pass container-name root foo encrypted=False
'''
def _bad_user_input():
raise SaltInvocationError('Invalid input for \'users\' parameter')
if not isinstance(users, list):
try:
users = users.split(',')
except AttributeError:
_bad_user_input()
if not users:
_bad_user_input()
failed_users = []
for user in users:
result = retcode(name,
'chpasswd{0}'.format(' -e' if encrypted else ''),
stdin=':'.join((user, password)),
python_shell=False,
path=path,
chroot_fallback=True,
output_loglevel='quiet')
if result != 0:
failed_users.append(user)
if failed_users:
raise CommandExecutionError(
'Password change failed for the following user(s): {0}'
.format(', '.join(failed_users))
)
return True
set_pass = salt.utils.functools.alias_function(set_password, 'set_pass')
def update_lxc_conf(name, lxc_conf, lxc_conf_unset, path=None):
'''
Edit LXC configuration options
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.update_lxc_conf ubuntu \\
lxc_conf="[{'network.ipv4.ip':'10.0.3.5'}]" \\
lxc_conf_unset="['lxc.utsname']"
'''
_ensure_exists(name, path=path)
cpath = get_root_path(path)
lxc_conf_p = os.path.join(cpath, name, 'config')
if not os.path.exists(lxc_conf_p):
raise SaltInvocationError(
'Configuration file {0} does not exist'.format(lxc_conf_p)
)
changes = {'edited': [], 'added': [], 'removed': []}
ret = {'changes': changes, 'result': True, 'comment': ''}
# do not use salt.utils.files.fopen !
with salt.utils.files.fopen(lxc_conf_p, 'r') as fic:
filtered_lxc_conf = []
for row in lxc_conf:
if not row:
continue
for conf in row:
filtered_lxc_conf.append((conf.strip(),
row[conf].strip()))
ret['comment'] = 'lxc.conf is up to date'
lines = []
orig_config = salt.utils.stringutils.to_unicode(fic.read())
for line in orig_config.splitlines():
if line.startswith('#') or not line.strip():
lines.append([line, ''])
else:
line = line.split('=')
index = line.pop(0)
val = (index.strip(), '='.join(line).strip())
if val not in lines:
lines.append(val)
for key, item in filtered_lxc_conf:
matched = False
for idx, line in enumerate(lines[:]):
if line[0] == key:
matched = True
lines[idx] = (key, item)
if '='.join(line[1:]).strip() != item.strip():
changes['edited'].append(
({line[0]: line[1:]}, {key: item}))
break
if not matched:
if (key, item) not in lines:
lines.append((key, item))
changes['added'].append({key: item})
dest_lxc_conf = []
# filter unset
if lxc_conf_unset:
for line in lines:
for opt in lxc_conf_unset:
if (
not line[0].startswith(opt) and
line not in dest_lxc_conf
):
dest_lxc_conf.append(line)
else:
changes['removed'].append(opt)
else:
dest_lxc_conf = lines
conf = ''
for key, val in dest_lxc_conf:
if not val:
conf += '{0}\n'.format(key)
else:
conf += '{0} = {1}\n'.format(key.strip(), val.strip())
conf_changed = conf != orig_config
chrono = datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S')
if conf_changed:
# DO NOT USE salt.utils.files.fopen here, i got (kiorky)
# problems with lxc configs which were wiped !
with salt.utils.files.fopen('{0}.{1}'.format(lxc_conf_p, chrono), 'w') as wfic:
wfic.write(salt.utils.stringutils.to_str(conf))
with salt.utils.files.fopen(lxc_conf_p, 'w') as wfic:
wfic.write(salt.utils.stringutils.to_str(conf))
ret['comment'] = 'Updated'
ret['result'] = True
if not any(changes[x] for x in changes):
# Ensure an empty changes dict if nothing was modified
ret['changes'] = {}
return ret
def set_dns(name, dnsservers=None, searchdomains=None, path=None):
'''
.. versionchanged:: 2015.5.0
The ``dnsservers`` and ``searchdomains`` parameters can now be passed
as a comma-separated list.
Update /etc/resolv.confo
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.set_dns ubuntu "['8.8.8.8', '4.4.4.4']"
'''
if dnsservers is None:
dnsservers = ['8.8.8.8', '4.4.4.4']
elif not isinstance(dnsservers, list):
try:
dnsservers = dnsservers.split(',')
except AttributeError:
raise SaltInvocationError(
'Invalid input for \'dnsservers\' parameter'
)
if searchdomains is None:
searchdomains = []
elif not isinstance(searchdomains, list):
try:
searchdomains = searchdomains.split(',')
except AttributeError:
raise SaltInvocationError(
'Invalid input for \'searchdomains\' parameter'
)
dns = ['nameserver {0}'.format(x) for x in dnsservers]
dns.extend(['search {0}'.format(x) for x in searchdomains])
dns = '\n'.join(dns) + '\n'
# we may be using resolvconf in the container
# We need to handle that case with care:
# - we create the resolv.conf runtime directory (the
# linked directory) as anyway it will be shadowed when the real
# runned tmpfs mountpoint will be mounted.
# ( /etc/resolv.conf -> ../run/resolvconf/resolv.conf)
# Indeed, it can save us in any other case (running, eg, in a
# bare chroot when repairing or preparing the container for
# operation.
# - We also teach resolvconf to use the aforementioned dns.
# - We finally also set /etc/resolv.conf in all cases
rstr = __salt__['test.random_hash']()
# no tmp here, apparmor won't let us execute !
script = '/sbin/{0}_dns.sh'.format(rstr)
DNS_SCRIPT = "\n".join([
# 'set -x',
'#!/usr/bin/env bash',
'if [ -h /etc/resolv.conf ];then',
' if [ "x$(readlink /etc/resolv.conf)"'
' = "x../run/resolvconf/resolv.conf" ];then',
' if [ ! -d /run/resolvconf/ ];then',
' mkdir -p /run/resolvconf',
' fi',
' cat > /etc/resolvconf/resolv.conf.d/head <<EOF',
dns,
'EOF',
'',
' fi',
'fi',
'cat > /etc/resolv.conf <<EOF',
dns,
'EOF',
''])
result = run_all(
name, 'tee {0}'.format(script), path=path,
stdin=DNS_SCRIPT, python_shell=True)
if result['retcode'] == 0:
result = run_all(
name, 'sh -c "chmod +x {0};{0}"'.format(script),
path=path, python_shell=True)
# blindly delete the setter file
run_all(name,
'sh -c \'if [ -f "{0}" ];then rm -f "{0}";fi\''.format(script),
path=path, python_shell=True)
if result['retcode'] != 0:
error = ('Unable to write to /etc/resolv.conf in container \'{0}\''
.format(name))
if result['stderr']:
error += ': {0}'.format(result['stderr'])
raise CommandExecutionError(error)
return True
def running_systemd(name, cache=True, path=None):
'''
Determine if systemD is running
path
path to the container parent
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.running_systemd ubuntu
'''
k = 'lxc.systemd.test.{0}{1}'.format(name, path)
ret = __context__.get(k, None)
if ret is None or not cache:
rstr = __salt__['test.random_hash']()
# no tmp here, apparmor won't let us execute !
script = '/sbin/{0}_testsystemd.sh'.format(rstr)
# ubuntu already had since trusty some bits of systemd but was
# still using upstart ...
# we need to be a bit more careful that just testing that systemd
# is present
_script = textwrap.dedent(
'''\
#!/usr/bin/env bash
set -x
if ! command -v systemctl 1>/dev/null 2>/dev/null;then exit 2;fi
for i in \\
/run/systemd/journal/dev-log\\
/run/systemd/journal/flushed\\
/run/systemd/journal/kernel-seqnum\\
/run/systemd/journal/socket\\
/run/systemd/journal/stdout\\
/var/run/systemd/journal/dev-log\\
/var/run/systemd/journal/flushed\\
/var/run/systemd/journal/kernel-seqnum\\
/var/run/systemd/journal/socket\\
/var/run/systemd/journal/stdout\\
;do\\
if test -e ${i};then exit 0;fi
done
if test -d /var/systemd/system;then exit 0;fi
exit 2
''')
result = run_all(
name, 'tee {0}'.format(script), path=path,
stdin=_script, python_shell=True)
if result['retcode'] == 0:
result = run_all(name,
'sh -c "chmod +x {0};{0}"'''.format(script),
path=path,
python_shell=True)
else:
raise CommandExecutionError(
'lxc {0} failed to copy initd tester'.format(name))
run_all(name,
'sh -c \'if [ -f "{0}" ];then rm -f "{0}";fi\''
''.format(script),
path=path,
ignore_retcode=True,
python_shell=True)
if result['retcode'] != 0:
error = ('Unable to determine if the container \'{0}\''
' was running systemd, assmuming it is not.'
''.format(name))
if result['stderr']:
error += ': {0}'.format(result['stderr'])
# only cache result if we got a known exit code
if result['retcode'] in (0, 2):
__context__[k] = ret = not result['retcode']
return ret
def systemd_running_state(name, path=None):
'''
Get the operational state of a systemd based container
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.systemd_running_state ubuntu
'''
try:
ret = run_all(name,
'systemctl is-system-running',
path=path,
ignore_retcode=True)['stdout']
except CommandExecutionError:
ret = ''
return ret
def test_sd_started_state(name, path=None):
'''
Test if a systemd container is fully started
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.test_sd_started_state ubuntu
'''
qstate = systemd_running_state(name, path=path)
if qstate in ('initializing', 'starting'):
return False
elif qstate == '':
return None
else:
return True
def test_bare_started_state(name, path=None):
'''
Test if a non systemd container is fully started
For now, it consists only to test if the container is attachable
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.test_bare_started_state ubuntu
'''
try:
ret = run_all(
name, 'ls', path=path, ignore_retcode=True
)['retcode'] == 0
except (CommandExecutionError,):
ret = None
return ret
def wait_started(name, path=None, timeout=300):
'''
Check that the system has fully inited
This is actually very important for systemD based containers
see https://github.com/saltstack/salt/issues/23847
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.wait_started ubuntu
'''
if not exists(name, path=path):
raise CommandExecutionError(
'Container {0} does does exists'.format(name))
if not state(name, path=path) == 'running':
raise CommandExecutionError(
'Container {0} is not running'.format(name))
ret = False
if running_systemd(name, path=path):
test_started = test_sd_started_state
logger = log.error
else:
test_started = test_bare_started_state
logger = log.debug
now = time.time()
expire = now + timeout
now = time.time()
started = test_started(name, path=path)
while time.time() < expire and not started:
time.sleep(0.3)
started = test_started(name, path=path)
if started is None:
logger(
'Assuming %s is started, although we failed to detect that'
' is fully started correctly', name)
ret = True
else:
ret = started
return ret
def _needs_install(name, path=None):
ret = 0
has_minion = retcode(name,
'which salt-minion',
path=path,
ignore_retcode=True)
# we assume that installing is when no minion is running
# but testing the executable presence is not enougth for custom
# installs where the bootstrap can do much more than installing
# the bare salt binaries.
if has_minion:
processes = run_stdout(name, "ps aux", path=path)
if 'salt-minion' not in processes:
ret = 1
else:
retcode(name, 'salt-call --local service.stop salt-minion')
else:
ret = 1
return ret
def bootstrap(name,
config=None,
approve_key=True,
install=True,
pub_key=None,
priv_key=None,
bootstrap_url=None,
force_install=False,
unconditional_install=False,
path=None,
bootstrap_delay=None,
bootstrap_args=None,
bootstrap_shell=None):
'''
Install and configure salt in a container.
config
Minion configuration options. By default, the ``master`` option is set
to the target host's master.
approve_key
Request a pre-approval of the generated minion key. Requires
that the salt-master be configured to either auto-accept all keys or
expect a signing request from the target host. Default: ``True``
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
pub_key
Explicit public key to pressed the minion with (optional).
This can be either a filepath or a string representing the key
priv_key
Explicit private key to pressed the minion with (optional).
This can be either a filepath or a string representing the key
bootstrap_delay
Delay in seconds between end of container creation and bootstrapping.
Useful when waiting for container to obtain a DHCP lease.
.. versionadded:: 2015.5.0
bootstrap_url
url, content or filepath to the salt bootstrap script
bootstrap_args
salt bootstrap script arguments
bootstrap_shell
shell to execute the script into
install
Whether to attempt a full installation of salt-minion if needed.
force_install
Force installation even if salt-minion is detected,
this is the way to run vendor bootstrap scripts even
if a salt minion is already present in the container
unconditional_install
Run the script even if the container seems seeded
CLI Examples:
.. code-block:: bash
salt 'minion' lxc.bootstrap container_name [config=config_data] \\
[approve_key=(True|False)] [install=(True|False)]
'''
wait_started(name, path=path)
if bootstrap_delay is not None:
try:
log.info('LXC %s: bootstrap_delay: %s', name, bootstrap_delay)
time.sleep(bootstrap_delay)
except TypeError:
# Bad input, but assume since a value was passed that
# a delay was desired, and sleep for 5 seconds
time.sleep(5)
c_info = info(name, path=path)
if not c_info:
return None
# default set here as we cannot set them
# in def as it can come from a chain of procedures.
if bootstrap_args:
# custom bootstrap args can be totally customized, and user could
# have inserted the placeholder for the config directory.
# For example, some salt bootstrap script do not use at all -c
if '{0}' not in bootstrap_args:
bootstrap_args += ' -c {0}'
else:
bootstrap_args = '-c {0}'
if not bootstrap_shell:
bootstrap_shell = 'sh'
orig_state = _ensure_running(name, path=path)
if not orig_state:
return orig_state
if not force_install:
needs_install = _needs_install(name, path=path)
else:
needs_install = True
seeded = retcode(name,
'test -e \'{0}\''.format(SEED_MARKER),
path=path,
chroot_fallback=True,
ignore_retcode=True) == 0
tmp = tempfile.mkdtemp()
if seeded and not unconditional_install:
ret = True
else:
ret = False
cfg_files = __salt__['seed.mkconfig'](
config, tmp=tmp, id_=name, approve_key=approve_key,
pub_key=pub_key, priv_key=priv_key)
if needs_install or force_install or unconditional_install:
if install:
rstr = __salt__['test.random_hash']()
configdir = '/var/tmp/.c_{0}'.format(rstr)
cmd = 'install -m 0700 -d {0}'.format(configdir)
if run_all(
name, cmd, path=path, python_shell=False
)['retcode'] != 0:
log.error('tmpdir %s creation failed %s', configdir, cmd)
return False
bs_ = __salt__['config.gather_bootstrap_script'](
bootstrap=bootstrap_url)
script = '/sbin/{0}_bootstrap.sh'.format(rstr)
copy_to(name, bs_, script, path=path)
result = run_all(name,
'sh -c "chmod +x {0}"'.format(script),
path=path,
python_shell=True)
copy_to(name, cfg_files['config'],
os.path.join(configdir, 'minion'),
path=path)
copy_to(name, cfg_files['privkey'],
os.path.join(configdir, 'minion.pem'),
path=path)
copy_to(name, cfg_files['pubkey'],
os.path.join(configdir, 'minion.pub'),
path=path)
bootstrap_args = bootstrap_args.format(configdir)
cmd = ('{0} {2} {1}'
.format(bootstrap_shell,
bootstrap_args.replace("'", "''"),
script))
# log ASAP the forged bootstrap command which can be wrapped
# out of the output in case of unexpected problem
log.info('Running %s in LXC container \'%s\'', cmd, name)
ret = retcode(name, cmd, output_loglevel='info',
path=path, use_vt=True) == 0
run_all(name,
'sh -c \'if [ -f "{0}" ];then rm -f "{0}";fi\''
''.format(script),
path=path,
ignore_retcode=True,
python_shell=True)
else:
ret = False
else:
minion_config = salt.config.minion_config(cfg_files['config'])
pki_dir = minion_config['pki_dir']
copy_to(name,
cfg_files['config'],
'/etc/salt/minion',
path=path)
copy_to(name,
cfg_files['privkey'],
os.path.join(pki_dir, 'minion.pem'),
path=path)
copy_to(name,
cfg_files['pubkey'],
os.path.join(pki_dir, 'minion.pub'),
path=path)
run(name,
'salt-call --local service.enable salt-minion',
path=path,
python_shell=False)
ret = True
shutil.rmtree(tmp)
if orig_state == 'stopped':
stop(name, path=path)
elif orig_state == 'frozen':
freeze(name, path=path)
# mark seeded upon successful install
if ret:
run(name,
'touch \'{0}\''.format(SEED_MARKER),
path=path,
python_shell=False)
return ret
def attachable(name, path=None):
'''
Return True if the named container can be attached to via the lxc-attach
command
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt 'minion' lxc.attachable ubuntu
'''
cachekey = 'lxc.attachable{0}{1}'.format(name, path)
try:
return __context__[cachekey]
except KeyError:
_ensure_exists(name, path=path)
# Can't use run() here because it uses attachable() and would
# endlessly recurse, resulting in a traceback
log.debug('Checking if LXC container %s is attachable', name)
cmd = 'lxc-attach'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' --clear-env -n {0} -- /usr/bin/env'.format(name)
result = __salt__['cmd.retcode'](cmd,
python_shell=False,
output_loglevel='quiet',
ignore_retcode=True) == 0
__context__[cachekey] = result
return __context__[cachekey]
def _run(name,
cmd,
output=None,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=None,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
Common logic for lxc.run functions
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
'''
orig_state = state(name, path=path)
try:
if attachable(name, path=path):
ret = __salt__['container_resource.run'](
name,
cmd,
path=path,
container_type=__virtualname__,
exec_driver=EXEC_DRIVER,
output=output,
no_start=no_start,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
ignore_retcode=ignore_retcode,
use_vt=use_vt,
keep_env=keep_env)
else:
if not chroot_fallback:
raise CommandExecutionError(
'{0} is not attachable.'.format(name))
rootfs = info(name, path=path).get('rootfs')
# Set context var to make cmd.run_chroot run cmd.run instead of
# cmd.run_all.
__context__['cmd.run_chroot.func'] = __salt__['cmd.run']
ret = __salt__['cmd.run_chroot'](rootfs,
cmd,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
ignore_retcode=ignore_retcode)
except Exception:
raise
finally:
# Make sure we honor preserve_state, even if there was an exception
new_state = state(name, path=path)
if preserve_state:
if orig_state == 'stopped' and new_state != 'stopped':
stop(name, path=path)
elif orig_state == 'frozen' and new_state != 'frozen':
freeze(name, start=True, path=path)
if output in (None, 'all'):
return ret
else:
return ret[output]
def run(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.8.0
Run :mod:`cmd.run <salt.modules.cmdmod.run>` within a container
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed in stderr if the command being run
does not exist. If no output is returned using this function, try using
:mod:`lxc.run_stderr <salt.modules.lxc.run_stderr>` or
:mod:`lxc.run_all <salt.modules.lxc.run_all>`.
name
Name of the container in which to run the command
cmd
Command to run
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console. Assumes
``output=all``.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
CLI Example:
.. code-block:: bash
salt myminion lxc.run mycontainer 'ifconfig -a'
'''
return _run(name,
cmd,
path=path,
output=None,
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def run_stdout(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.5.0
Run :mod:`cmd.run_stdout <salt.modules.cmdmod.run_stdout>` within a container
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed in stderr if the command being run
does not exist. If no output is returned using this function, try using
:mod:`lxc.run_stderr <salt.modules.lxc.run_stderr>` or
:mod:`lxc.run_all <salt.modules.lxc.run_all>`.
name
Name of the container in which to run the command
cmd
Command to run
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console
``output=all``.
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
CLI Example:
.. code-block:: bash
salt myminion lxc.run_stdout mycontainer 'ifconfig -a'
'''
return _run(name,
cmd,
path=path,
output='stdout',
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def run_stderr(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.5.0
Run :mod:`cmd.run_stderr <salt.modules.cmdmod.run_stderr>` within a container
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed if the command being run does not
exist.
name
Name of the container in which to run the command
cmd
Command to run
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console
``output=all``.
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
CLI Example:
.. code-block:: bash
salt myminion lxc.run_stderr mycontainer 'ip addr show'
'''
return _run(name,
cmd,
path=path,
output='stderr',
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def retcode(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.5.0
Run :mod:`cmd.retcode <salt.modules.cmdmod.retcode>` within a container
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed in stderr if the command being run
does not exist. If the retcode is nonzero and not what was expected,
try using :mod:`lxc.run_stderr <salt.modules.lxc.run_stderr>`
or :mod:`lxc.run_all <salt.modules.lxc.run_all>`.
name
Name of the container in which to run the command
cmd
Command to run
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console
``output=all``.
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
CLI Example:
.. code-block:: bash
salt myminion lxc.retcode mycontainer 'ip addr show'
'''
return _run(name,
cmd,
output='retcode',
path=path,
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def run_all(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.5.0
Run :mod:`cmd.run_all <salt.modules.cmdmod.run_all>` within a container
.. note::
While the command is run within the container, it is initiated from the
host. Therefore, the PID in the return dict is from the host, not from
the container.
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed in stderr if the command being run
does not exist.
name
Name of the container in which to run the command
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
cmd
Command to run
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console
``output=all``.
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
CLI Example:
.. code-block:: bash
salt myminion lxc.run_all mycontainer 'ip addr show'
'''
return _run(name,
cmd,
output='all',
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
path=path,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def _get_md5(name, path):
'''
Get the MD5 checksum of a file from a container
'''
output = run_stdout(name, 'md5sum "{0}"'.format(path),
chroot_fallback=True,
ignore_retcode=True)
try:
return output.split()[0]
except IndexError:
# Destination file does not exist or could not be accessed
return None
def copy_to(name, source, dest, overwrite=False, makedirs=False, path=None):
'''
.. versionchanged:: 2015.8.0
Function renamed from ``lxc.cp`` to ``lxc.copy_to`` for consistency
with other container types. ``lxc.cp`` will continue to work, however.
For versions 2015.2.x and earlier, use ``lxc.cp``.
Copy a file or directory from the host into a container
name
Container name
source
File to be copied to the container
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
dest
Destination on the container. Must be an absolute path.
.. versionchanged:: 2015.5.0
If the destination is a directory, the file will be copied into
that directory.
overwrite : False
Unless this option is set to ``True``, then if a file exists at the
location specified by the ``dest`` argument, an error will be raised.
.. versionadded:: 2015.8.0
makedirs : False
Create the parent directory on the container if it does not already
exist.
.. versionadded:: 2015.5.0
CLI Example:
.. code-block:: bash
salt 'minion' lxc.copy_to /tmp/foo /root/foo
salt 'minion' lxc.cp /tmp/foo /root/foo
'''
_ensure_running(name, no_start=True, path=path)
return __salt__['container_resource.copy_to'](
name,
source,
dest,
container_type=__virtualname__,
path=path,
exec_driver=EXEC_DRIVER,
overwrite=overwrite,
makedirs=makedirs)
cp = salt.utils.functools.alias_function(copy_to, 'cp')
def read_conf(conf_file, out_format='simple'):
'''
Read in an LXC configuration file. By default returns a simple, unsorted
dict, but can also return a more detailed structure including blank lines
and comments.
out_format:
set to 'simple' if you need the old and unsupported behavior.
This won't support the multiple lxc values (eg: multiple network nics)
CLI Examples:
.. code-block:: bash
salt 'minion' lxc.read_conf /etc/lxc/mycontainer.conf
salt 'minion' lxc.read_conf /etc/lxc/mycontainer.conf out_format=commented
'''
ret_commented = []
ret_simple = {}
with salt.utils.files.fopen(conf_file, 'r') as fp_:
for line in salt.utils.data.decode(fp_.readlines()):
if '=' not in line:
ret_commented.append(line)
continue
comps = line.split('=')
value = '='.join(comps[1:]).strip()
comment = None
if value.strip().startswith('#'):
vcomps = value.strip().split('#')
value = vcomps[1].strip()
comment = '#'.join(vcomps[1:]).strip()
ret_commented.append({comps[0].strip(): {
'value': value,
'comment': comment,
}})
else:
ret_commented.append({comps[0].strip(): value})
ret_simple[comps[0].strip()] = value
if out_format == 'simple':
return ret_simple
return ret_commented
def write_conf(conf_file, conf):
'''
Write out an LXC configuration file
This is normally only used internally. The format of the data structure
must match that which is returned from ``lxc.read_conf()``, with
``out_format`` set to ``commented``.
An example might look like:
.. code-block:: python
[
{'lxc.utsname': '$CONTAINER_NAME'},
'# This is a commented line\\n',
'\\n',
{'lxc.mount': '$CONTAINER_FSTAB'},
{'lxc.rootfs': {'comment': 'This is another test',
'value': 'This is another test'}},
'\\n',
{'lxc.network.type': 'veth'},
{'lxc.network.flags': 'up'},
{'lxc.network.link': 'br0'},
{'lxc.network.mac': '$CONTAINER_MACADDR'},
{'lxc.network.ipv4': '$CONTAINER_IPADDR'},
{'lxc.network.name': '$CONTAINER_DEVICENAME'},
]
CLI Example:
.. code-block:: bash
salt 'minion' lxc.write_conf /etc/lxc/mycontainer.conf \\
out_format=commented
'''
if not isinstance(conf, list):
raise SaltInvocationError('Configuration must be passed as a list')
# construct the content prior to write to the file
# to avoid half written configs
content = ''
for line in conf:
if isinstance(line, (six.text_type, six.string_types)):
content += line
elif isinstance(line, dict):
for key in list(line.keys()):
out_line = None
if isinstance(
line[key],
(six.text_type, six.string_types, six.integer_types, float)
):
out_line = ' = '.join((key, "{0}".format(line[key])))
elif isinstance(line[key], dict):
out_line = ' = '.join((key, line[key]['value']))
if 'comment' in line[key]:
out_line = ' # '.join((out_line, line[key]['comment']))
if out_line:
content += out_line
content += '\n'
with salt.utils.files.fopen(conf_file, 'w') as fp_:
fp_.write(salt.utils.stringutils.to_str(content))
return {}
def edit_conf(conf_file,
out_format='simple',
read_only=False,
lxc_config=None,
**kwargs):
'''
Edit an LXC configuration file. If a setting is already present inside the
file, its value will be replaced. If it does not exist, it will be appended
to the end of the file. Comments and blank lines will be kept in-tact if
they already exist in the file.
out_format:
Set to simple if you need backward compatibility (multiple items for a
simple key is not supported)
read_only:
return only the edited configuration without applying it
to the underlying lxc configuration file
lxc_config:
List of dict containning lxc configuration items
For network configuration, you also need to add the device it belongs
to, otherwise it will default to eth0.
Also, any change to a network parameter will result in the whole
network reconfiguration to avoid mismatchs, be aware of that !
After the file is edited, its contents will be returned. By default, it
will be returned in ``simple`` format, meaning an unordered dict (which
may not represent the actual file order). Passing in an ``out_format`` of
``commented`` will return a data structure which accurately represents the
order and content of the file.
CLI Example:
.. code-block:: bash
salt 'minion' lxc.edit_conf /etc/lxc/mycontainer.conf \\
out_format=commented lxc.network.type=veth
salt 'minion' lxc.edit_conf /etc/lxc/mycontainer.conf \\
out_format=commented \\
lxc_config="[{'lxc.network.name': 'eth0', \\
'lxc.network.ipv4': '1.2.3.4'},
{'lxc.network.name': 'eth2', \\
'lxc.network.ipv4': '1.2.3.5',\\
'lxc.network.gateway': '1.2.3.1'}]"
'''
data = []
try:
conf = read_conf(conf_file, out_format=out_format)
except Exception:
conf = []
if not lxc_config:
lxc_config = []
lxc_config = copy.deepcopy(lxc_config)
# search if we want to access net config
# in that case, we will replace all the net configuration
net_config = []
for lxc_kws in lxc_config + [kwargs]:
net_params = {}
for kwarg in [a for a in lxc_kws]:
if kwarg.startswith('__'):
continue
if kwarg.startswith('lxc.network.'):
net_params[kwarg] = lxc_kws[kwarg]
lxc_kws.pop(kwarg, None)
if net_params:
net_config.append(net_params)
nic_opts = salt.utils.odict.OrderedDict()
for params in net_config:
dev = params.get('lxc.network.name', DEFAULT_NIC)
dev_opts = nic_opts.setdefault(dev, salt.utils.odict.OrderedDict())
for param in params:
opt = param.replace('lxc.network.', '')
opt = {'hwaddr': 'mac'}.get(opt, opt)
dev_opts[opt] = params[param]
net_changes = []
if nic_opts:
net_changes = _config_list(conf, only_net=True,
**{'network_profile': DEFAULT_NIC,
'nic_opts': nic_opts})
if net_changes:
lxc_config.extend(net_changes)
for line in conf:
if not isinstance(line, dict):
data.append(line)
continue
else:
for key in list(line.keys()):
val = line[key]
if net_changes and key.startswith('lxc.network.'):
continue
found = False
for ix in range(len(lxc_config)):
kw = lxc_config[ix]
if key in kw:
found = True
data.append({key: kw[key]})
del kw[key]
if not found:
data.append({key: val})
for lxc_kws in lxc_config:
for kwarg in lxc_kws:
data.append({kwarg: lxc_kws[kwarg]})
if read_only:
return data
write_conf(conf_file, data)
return read_conf(conf_file, out_format)
def reboot(name, path=None):
'''
Reboot a container.
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Examples:
.. code-block:: bash
salt 'minion' lxc.reboot myvm
'''
ret = {'result': True,
'changes': {},
'comment': '{0} rebooted'.format(name)}
does_exist = exists(name, path=path)
if does_exist and (state(name, path=path) == 'running'):
try:
stop(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
ret['result'] = False
return ret
if does_exist and (state(name, path=path) != 'running'):
try:
start(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
ret['result'] = False
return ret
ret['changes'][name] = 'rebooted'
return ret
def reconfigure(name,
cpu=None,
cpuset=None,
cpushare=None,
memory=None,
profile=None,
network_profile=None,
nic_opts=None,
bridge=None,
gateway=None,
autostart=None,
utsname=None,
rootfs=None,
path=None,
**kwargs):
'''
Reconfigure a container.
This only applies to a few property
name
Name of the container.
utsname
utsname of the container.
.. versionadded:: 2016.3.0
rootfs
rootfs of the container.
.. versionadded:: 2016.3.0
cpu
Select a random number of cpu cores and assign it to the cpuset, if the
cpuset option is set then this option will be ignored
cpuset
Explicitly define the cpus this container will be bound to
cpushare
cgroups cpu shares.
autostart
autostart container on reboot
memory
cgroups memory limit, in MB.
(0 for nolimit, None for old default 1024MB)
gateway
the ipv4 gateway to use
the default does nothing more than lxcutils does
bridge
the bridge to use
the default does nothing more than lxcutils does
nic
Network interfaces profile (defined in config or pillar).
nic_opts
Extra options for network interfaces, will override
``{"eth0": {"mac": "aa:bb:cc:dd:ee:ff", "ipv4": "10.1.1.1", "ipv6": "2001:db8::ff00:42:8329"}}``
or
``{"eth0": {"mac": "aa:bb:cc:dd:ee:ff", "ipv4": "10.1.1.1/24", "ipv6": "2001:db8::ff00:42:8329"}}``
path
path to the container parent
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt-call -lall mc_lxc_fork.reconfigure foobar nic_opts="{'eth1': {'mac': '00:16:3e:dd:ee:44'}}" memory=4
'''
changes = {}
cpath = get_root_path(path)
path = os.path.join(cpath, name, 'config')
ret = {'name': name,
'comment': 'config for {0} up to date'.format(name),
'result': True,
'changes': changes}
profile = get_container_profile(copy.deepcopy(profile))
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, _marker)
profile_match = profile.pop(key, default)
# let kwarg overrides be the preferred choice
if kw_overrides_match is _marker:
return profile_match
return kw_overrides_match
if nic_opts is not None and not network_profile:
network_profile = DEFAULT_NIC
if autostart is not None:
autostart = select('autostart', autostart)
else:
autostart = 'keep'
if not utsname:
utsname = select('utsname', utsname)
if os.path.exists(path):
old_chunks = read_conf(path, out_format='commented')
make_kw = salt.utils.odict.OrderedDict([
('utsname', utsname),
('rootfs', rootfs),
('autostart', autostart),
('cpu', cpu),
('gateway', gateway),
('cpuset', cpuset),
('cpushare', cpushare),
('network_profile', network_profile),
('nic_opts', nic_opts),
('bridge', bridge)])
# match 0 and none as memory = 0 in lxc config is harmful
if memory:
make_kw['memory'] = memory
kw = salt.utils.odict.OrderedDict()
for key, val in six.iteritems(make_kw):
if val is not None:
kw[key] = val
new_cfg = _config_list(conf_tuples=old_chunks, **kw)
if new_cfg:
edit_conf(path, out_format='commented', lxc_config=new_cfg)
chunks = read_conf(path, out_format='commented')
if old_chunks != chunks:
ret['comment'] = '{0} lxc config updated'.format(name)
if state(name, path=path) == 'running':
cret = reboot(name, path=path)
ret['result'] = cret['result']
return ret
def apply_network_profile(name, network_profile, nic_opts=None, path=None):
'''
.. versionadded:: 2015.5.0
Apply a network profile to a container
network_profile
profile name or default values (dict)
nic_opts
values to override in defaults (dict)
indexed by nic card names
path
path to the container parent
.. versionadded:: 2015.8.0
CLI Examples:
.. code-block:: bash
salt 'minion' lxc.apply_network_profile web1 centos
salt 'minion' lxc.apply_network_profile web1 centos \\
nic_opts="{'eth0': {'mac': 'xx:xx:xx:xx:xx:xx'}}"
salt 'minion' lxc.apply_network_profile web1 \\
"{'eth0': {'mac': 'xx:xx:xx:xx:xx:yy'}}"
nic_opts="{'eth0': {'mac': 'xx:xx:xx:xx:xx:xx'}}"
The special case to disable use of ethernet nics:
.. code-block:: bash
salt 'minion' lxc.apply_network_profile web1 centos \\
"{eth0: {disable: true}}"
'''
cpath = get_root_path(path)
cfgpath = os.path.join(cpath, name, 'config')
before = []
with salt.utils.files.fopen(cfgpath, 'r') as fp_:
for line in fp_:
before.append(line)
lxcconfig = _LXCConfig(name=name, path=path)
old_net = lxcconfig._filter_data('lxc.network')
network_params = {}
for param in _network_conf(
conf_tuples=old_net,
network_profile=network_profile, nic_opts=nic_opts
):
network_params.update(param)
if network_params:
edit_conf(cfgpath, out_format='commented', **network_params)
after = []
with salt.utils.files.fopen(cfgpath, 'r') as fp_:
for line in fp_:
after.append(line)
diff = ''
for line in difflib.unified_diff(before,
after,
fromfile='before',
tofile='after'):
diff += line
return diff
def get_pid(name, path=None):
'''
Returns a container pid.
Throw an exception if the container isn't running.
CLI Example:
.. code-block:: bash
salt '*' lxc.get_pid name
'''
if name not in list_(limit='running', path=path):
raise CommandExecutionError('Container {0} is not running, can\'t determine PID'.format(name))
info = __salt__['cmd.run']('lxc-info -n {0}'.format(name)).split("\n")
pid = [line.split(':')[1].strip() for line in info if re.match(r'\s*PID', line)][0]
return pid
def add_veth(name, interface_name, bridge=None, path=None):
'''
Add a veth to a container.
Note : this function doesn't update the container config, just add the interface at runtime
name
Name of the container
interface_name
Name of the interface in the container
bridge
Name of the bridge to attach the interface to (facultative)
CLI Examples:
.. code-block:: bash
salt '*' lxc.add_veth container_name eth1 br1
salt '*' lxc.add_veth container_name eth1
'''
# Get container init PID
pid = get_pid(name, path=path)
# Generate a ramdom string for veth and ensure that is isn't present on the system
while True:
random_veth = 'veth'+''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(6))
if random_veth not in __salt__['network.interfaces']().keys():
break
# Check prerequisites
if not __salt__['file.directory_exists']('/var/run/'):
raise CommandExecutionError('Directory /var/run required for lxc.add_veth doesn\'t exists')
if not __salt__['file.file_exists']('/proc/{0}/ns/net'.format(pid)):
raise CommandExecutionError('Proc file for container {0} network namespace doesn\'t exists'.format(name))
if not __salt__['file.directory_exists']('/var/run/netns'):
__salt__['file.mkdir']('/var/run/netns')
# Ensure that the symlink is up to date (change on container restart)
if __salt__['file.is_link']('/var/run/netns/{0}'.format(name)):
__salt__['file.remove']('/var/run/netns/{0}'.format(name))
__salt__['file.symlink']('/proc/{0}/ns/net'.format(pid), '/var/run/netns/{0}'.format(name))
# Ensure that interface doesn't exists
interface_exists = 0 == __salt__['cmd.retcode']('ip netns exec {netns} ip address list {interface}'.format(
netns=name,
interface=interface_name
))
if interface_exists:
raise CommandExecutionError('Interface {interface} already exists in {container}'.format(
interface=interface_name,
container=name
))
# Create veth and bring it up
if __salt__['cmd.retcode']('ip link add name {veth} type veth peer name {veth}_c'.format(veth=random_veth)) != 0:
raise CommandExecutionError('Error while creating the veth pair {0}'.format(random_veth))
if __salt__['cmd.retcode']('ip link set dev {0} up'.format(random_veth)) != 0:
raise CommandExecutionError('Error while bringing up host-side veth {0}'.format(random_veth))
# Attach it to the container
attached = 0 == __salt__['cmd.retcode']('ip link set dev {veth}_c netns {container} name {interface_name}'.format(
veth=random_veth,
container=name,
interface_name=interface_name
))
if not attached:
raise CommandExecutionError('Error while attaching the veth {veth} to container {container}'.format(
veth=random_veth,
container=name
))
__salt__['file.remove']('/var/run/netns/{0}'.format(name))
if bridge is not None:
__salt__['bridge.addif'](bridge, random_veth)
|
saltstack/salt
|
salt/modules/lxc.py
|
destroy
|
python
|
def destroy(name, stop=False, path=None):
'''
Destroy the named container.
.. warning::
Destroys all data associated with the container.
path
path to the container parent directory (default: /var/lib/lxc)
.. versionadded:: 2015.8.0
stop : False
If ``True``, the container will be destroyed even if it is
running/frozen.
.. versionchanged:: 2015.5.0
Default value changed to ``False``. This more closely matches the
behavior of ``lxc-destroy(1)``, and also makes it less likely that
an accidental command will destroy a running container that was
being used for important things.
CLI Examples:
.. code-block:: bash
salt '*' lxc.destroy foo
salt '*' lxc.destroy foo stop=True
'''
_ensure_exists(name, path=path)
if not stop and state(name, path=path) != 'stopped':
raise CommandExecutionError(
'Container \'{0}\' is not stopped'.format(name)
)
return _change_state('lxc-destroy', name, None, path=path)
|
Destroy the named container.
.. warning::
Destroys all data associated with the container.
path
path to the container parent directory (default: /var/lib/lxc)
.. versionadded:: 2015.8.0
stop : False
If ``True``, the container will be destroyed even if it is
running/frozen.
.. versionchanged:: 2015.5.0
Default value changed to ``False``. This more closely matches the
behavior of ``lxc-destroy(1)``, and also makes it less likely that
an accidental command will destroy a running container that was
being used for important things.
CLI Examples:
.. code-block:: bash
salt '*' lxc.destroy foo
salt '*' lxc.destroy foo stop=True
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/lxc.py#L2565-L2600
|
[
"def state(name, path=None):\n '''\n Returns the state of a container.\n\n path\n path to the container parent directory (default: /var/lib/lxc)\n\n .. versionadded:: 2015.8.0\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' lxc.state name\n '''\n # Don't use _ensure_exists() here, it will mess with _change_state()\n\n cachekey = 'lxc.state.{0}{1}'.format(name, path)\n try:\n return __context__[cachekey]\n except KeyError:\n if not exists(name, path=path):\n __context__[cachekey] = None\n else:\n cmd = 'lxc-info'\n if path:\n cmd += ' -P {0}'.format(pipes.quote(path))\n cmd += ' -n {0}'.format(name)\n ret = __salt__['cmd.run_all'](cmd, python_shell=False)\n if ret['retcode'] != 0:\n _clear_context()\n raise CommandExecutionError(\n 'Unable to get state of container \\'{0}\\''.format(name)\n )\n c_infos = ret['stdout'].splitlines()\n c_state = None\n for c_info in c_infos:\n stat = c_info.split(':')\n if stat[0].lower() == 'state':\n c_state = stat[1].strip().lower()\n break\n __context__[cachekey] = c_state\n return __context__[cachekey]\n",
"def _change_state(cmd,\n name,\n expected,\n stdin=_marker,\n stdout=_marker,\n stderr=_marker,\n with_communicate=_marker,\n use_vt=_marker,\n path=None):\n pre = state(name, path=path)\n if pre == expected:\n return {'result': True,\n 'state': {'old': expected, 'new': expected},\n 'comment': 'Container \\'{0}\\' already {1}'\n .format(name, expected)}\n\n if cmd == 'lxc-destroy':\n # Kill the container first\n scmd = 'lxc-stop'\n if path:\n scmd += ' -P {0}'.format(pipes.quote(path))\n scmd += ' -k -n {0}'.format(name)\n __salt__['cmd.run'](scmd,\n python_shell=False)\n\n if path and ' -P ' not in cmd:\n cmd += ' -P {0}'.format(pipes.quote(path))\n cmd += ' -n {0}'.format(name)\n\n # certain lxc commands need to be taken with care (lxc-start)\n # as te command itself mess with double forks; we must not\n # communicate with it, but just wait for the exit status\n pkwargs = {'python_shell': False,\n 'redirect_stderr': True,\n 'with_communicate': with_communicate,\n 'use_vt': use_vt,\n 'stdin': stdin,\n 'stdout': stdout}\n for i in [a for a in pkwargs]:\n val = pkwargs[i]\n if val is _marker:\n pkwargs.pop(i, None)\n\n _cmdout = __salt__['cmd.run_all'](cmd, **pkwargs)\n\n if _cmdout['retcode'] != 0:\n raise CommandExecutionError(\n 'Error changing state for container \\'{0}\\' using command '\n '\\'{1}\\': {2}'.format(name, cmd, _cmdout['stdout'])\n )\n if expected is not None:\n # some commands do not wait, so we will\n rcmd = 'lxc-wait'\n if path:\n rcmd += ' -P {0}'.format(pipes.quote(path))\n rcmd += ' -n {0} -s {1}'.format(name, expected.upper())\n __salt__['cmd.run'](rcmd, python_shell=False, timeout=30)\n _clear_context()\n post = state(name, path=path)\n ret = {'result': post == expected,\n 'state': {'old': pre, 'new': post}}\n return ret\n",
"def _ensure_exists(name, path=None):\n '''\n Raise an exception if the container does not exist\n '''\n if not exists(name, path=path):\n raise CommandExecutionError(\n 'Container \\'{0}\\' does not exist'.format(name)\n )\n"
] |
# -*- coding: utf-8 -*-
'''
Control Linux Containers via Salt
:depends: lxc package for distribution
lxc >= 1.0 (even beta alpha) is required
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import datetime
import copy
import string
import textwrap
import difflib
import logging
import tempfile
import os
import pipes
import time
import shutil
import re
import random
# Import salt libs
import salt.utils.args
import salt.utils.cloud
import salt.utils.data
import salt.utils.dictupdate
import salt.utils.files
import salt.utils.functools
import salt.utils.hashutils
import salt.utils.network
import salt.utils.odict
import salt.utils.path
import salt.utils.stringutils
from salt.exceptions import CommandExecutionError, SaltInvocationError
import salt.config
from salt.utils.versions import LooseVersion as _LooseVersion
# Import 3rd-party libs
from salt.ext import six
# pylint: disable=import-error,no-name-in-module
from salt.ext.six.moves import range # pylint: disable=redefined-builtin
from salt.ext.six.moves.urllib.parse import urlparse as _urlparse
# pylint: enable=import-error,no-name-in-module
# Set up logging
log = logging.getLogger(__name__)
# Don't shadow built-in's.
__func_alias__ = {
'list_': 'list',
'ls_': 'ls'
}
__virtualname__ = 'lxc'
DEFAULT_NIC = 'eth0'
DEFAULT_BR = 'br0'
SEED_MARKER = '/lxc.initial_seed'
EXEC_DRIVER = 'lxc-attach'
DEFAULT_PATH = '/var/lib/lxc'
_marker = object()
def __virtual__():
if salt.utils.path.which('lxc-start'):
return __virtualname__
# To speed up the whole thing, we decided to not use the
# subshell way and assume things are in place for lxc
# Discussion made by @kiorky and @thatch45
# lxc-version presence is not sufficient, in lxc1.0 alpha
# (precise backports), we have it and it is sufficient
# for the module to execute.
# elif salt.utils.path.which('lxc-version'):
# passed = False
# try:
# passed = subprocess.check_output(
# 'lxc-version').split(':')[1].strip() >= '1.0'
# except Exception:
# pass
# if not passed:
# log.warning('Support for lxc < 1.0 may be incomplete.')
# return 'lxc'
# return False
#
return (False, 'The lxc execution module cannot be loaded: the lxc-start binary is not in the path.')
def get_root_path(path):
'''
Get the configured lxc root for containers
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.get_root_path
'''
if not path:
path = __opts__.get('lxc.root_path', DEFAULT_PATH)
return path
def version():
'''
Return the actual lxc client version
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.version
'''
k = 'lxc.version'
if not __context__.get(k, None):
cversion = __salt__['cmd.run_all']('lxc-info --version')
if not cversion['retcode']:
ver = _LooseVersion(cversion['stdout'])
if ver < _LooseVersion('1.0'):
raise CommandExecutionError('LXC should be at least 1.0')
__context__[k] = "{0}".format(ver)
return __context__.get(k, None)
def _clear_context():
'''
Clear any lxc variables set in __context__
'''
for var in [x for x in __context__ if x.startswith('lxc.')]:
log.trace('Clearing __context__[\'%s\']', var)
__context__.pop(var, None)
def _ip_sort(ip):
'''Ip sorting'''
idx = '001'
if ip == '127.0.0.1':
idx = '200'
if ip == '::1':
idx = '201'
elif '::' in ip:
idx = '100'
return '{0}___{1}'.format(idx, ip)
def search_lxc_bridges():
'''
Search which bridges are potentially available as LXC bridges
CLI Example:
.. code-block:: bash
salt '*' lxc.search_lxc_bridges
'''
bridges = __context__.get('lxc.bridges', None)
# either match not yet called or no bridges were found
# to handle the case where lxc was not installed on the first
# call
if not bridges:
bridges = set()
running_bridges = set()
bridges.add(DEFAULT_BR)
try:
output = __salt__['cmd.run_all']('brctl show')
for line in output['stdout'].splitlines()[1:]:
if not line.startswith(' '):
running_bridges.add(line.split()[0].strip())
except (SaltInvocationError, CommandExecutionError):
pass
for ifc, ip in six.iteritems(
__grains__.get('ip_interfaces', {})
):
if ifc in running_bridges:
bridges.add(ifc)
elif os.path.exists(
'/sys/devices/virtual/net/{0}/bridge'.format(ifc)
):
bridges.add(ifc)
bridges = list(bridges)
# if we found interfaces that have lxc in their names
# we filter them as being the potential lxc bridges
# we also try to default on br0 on other cases
def sort_bridges(a):
pref = 'z'
if 'lxc' in a:
pref = 'a'
elif 'br0' == a:
pref = 'c'
return '{0}_{1}'.format(pref, a)
bridges.sort(key=sort_bridges)
__context__['lxc.bridges'] = bridges
return bridges
def search_lxc_bridge():
'''
Search the first bridge which is potentially available as LXC bridge
CLI Example:
.. code-block:: bash
salt '*' lxc.search_lxc_bridge
'''
return search_lxc_bridges()[0]
def _get_salt_config(config, **kwargs):
if not config:
config = kwargs.get('minion', {})
if not config:
config = {}
config.setdefault('master',
kwargs.get('master',
__opts__.get('master',
__opts__['id'])))
config.setdefault(
'master_port',
kwargs.get('master_port',
__opts__.get('master_port',
__opts__.get('ret_port',
__opts__.get('4506')))))
if not config['master']:
config = {}
return config
def cloud_init_interface(name, vm_=None, **kwargs):
'''
Interface between salt.cloud.lxc driver and lxc.init
``vm_`` is a mapping of vm opts in the salt.cloud format
as documented for the lxc driver.
This can be used either:
- from the salt cloud driver
- because you find the argument to give easier here
than using directly lxc.init
.. warning::
BE REALLY CAREFUL CHANGING DEFAULTS !!!
IT'S A RETRO COMPATIBLE INTERFACE WITH
THE SALT CLOUD DRIVER (ask kiorky).
name
name of the lxc container to create
pub_key
public key to preseed the minion with.
Can be the keycontent or a filepath
priv_key
private key to preseed the minion with.
Can be the keycontent or a filepath
path
path to the container parent directory (default: /var/lib/lxc)
.. versionadded:: 2015.8.0
profile
:ref:`profile <tutorial-lxc-profiles-container>` selection
network_profile
:ref:`network profile <tutorial-lxc-profiles-network>` selection
nic_opts
per interface settings compatibles with
network profile (ipv4/ipv6/link/gateway/mac/netmask)
eg::
- {'eth0': {'mac': '00:16:3e:01:29:40',
'gateway': None, (default)
'link': 'br0', (default)
'gateway': None, (default)
'netmask': '', (default)
'ip': '22.1.4.25'}}
unconditional_install
given to lxc.bootstrap (see relative doc)
force_install
given to lxc.bootstrap (see relative doc)
config
any extra argument for the salt minion config
dnsservers
list of DNS servers to set inside the container
dns_via_dhcp
do not set the dns servers, let them be set by the dhcp.
autostart
autostart the container at boot time
password
administrative password for the container
bootstrap_delay
delay before launching bootstrap script at Container init
.. warning::
Legacy but still supported options:
from_container
which container we use as a template
when running lxc.clone
image
which template do we use when we
are using lxc.create. This is the default
mode unless you specify something in from_container
backing
which backing store to use.
Values can be: overlayfs, dir(default), lvm, zfs, brtfs
fstype
When using a blockdevice level backing store,
which filesystem to use on
size
When using a blockdevice level backing store,
which size for the filesystem to use on
snapshot
Use snapshot when cloning the container source
vgname
if using LVM: vgname
lvname
if using LVM: lvname
thinpool:
if using LVM: thinpool
ip
ip for the primary nic
mac
mac address for the primary nic
netmask
netmask for the primary nic (24)
= ``vm_.get('netmask', '24')``
bridge
bridge for the primary nic (lxcbr0)
gateway
network gateway for the container
additional_ips
additional ips which will be wired on the main bridge (br0)
which is connected to internet.
Be aware that you may use manual virtual mac addresses
providen by you provider (online, ovh, etc).
This is a list of mappings {ip: '', mac: '', netmask:''}
Set gateway to None and an interface with a gateway
to escape from another interface that eth0.
eg::
- {'mac': '00:16:3e:01:29:40',
'gateway': None, (default)
'link': 'br0', (default)
'netmask': '', (default)
'ip': '22.1.4.25'}
users
administrative users for the container
default: [root] and [root, ubuntu] on ubuntu
default_nic
name of the first interface, you should
really not override this
CLI Example:
.. code-block:: bash
salt '*' lxc.cloud_init_interface foo
'''
if vm_ is None:
vm_ = {}
vm_ = copy.deepcopy(vm_)
vm_ = salt.utils.dictupdate.update(vm_, kwargs)
profile_data = copy.deepcopy(
vm_.get('lxc_profile',
vm_.get('profile', {})))
if not isinstance(profile_data, (dict, six.string_types)):
profile_data = {}
profile = get_container_profile(profile_data)
def _cloud_get(k, default=None):
return vm_.get(k, profile.get(k, default))
if name is None:
name = vm_['name']
# if we are on ubuntu, default to ubuntu
default_template = ''
if __grains__.get('os', '') in ['Ubuntu']:
default_template = 'ubuntu'
image = _cloud_get('image')
if not image:
_cloud_get('template', default_template)
backing = _cloud_get('backing', 'dir')
if image:
profile['template'] = image
vgname = _cloud_get('vgname', None)
if vgname:
profile['vgname'] = vgname
if backing:
profile['backing'] = backing
snapshot = _cloud_get('snapshot', False)
autostart = bool(_cloud_get('autostart', True))
dnsservers = _cloud_get('dnsservers', [])
dns_via_dhcp = _cloud_get('dns_via_dhcp', True)
password = _cloud_get('password', 's3cr3t')
password_encrypted = _cloud_get('password_encrypted', False)
fstype = _cloud_get('fstype', None)
lvname = _cloud_get('lvname', None)
thinpool = _cloud_get('thinpool', None)
pub_key = _cloud_get('pub_key', None)
priv_key = _cloud_get('priv_key', None)
size = _cloud_get('size', '20G')
script = _cloud_get('script', None)
script_args = _cloud_get('script_args', None)
users = _cloud_get('users', None)
if users is None:
users = []
ssh_username = _cloud_get('ssh_username', None)
if ssh_username and (ssh_username not in users):
users.append(ssh_username)
network_profile = _cloud_get('network_profile', None)
nic_opts = kwargs.get('nic_opts', None)
netmask = _cloud_get('netmask', '24')
path = _cloud_get('path', None)
bridge = _cloud_get('bridge', None)
gateway = _cloud_get('gateway', None)
unconditional_install = _cloud_get('unconditional_install', False)
force_install = _cloud_get('force_install', True)
config = _get_salt_config(_cloud_get('config', {}), **vm_)
default_nic = _cloud_get('default_nic', DEFAULT_NIC)
# do the interface with lxc.init mainly via nic_opts
# to avoid extra and confusing extra use cases.
if not isinstance(nic_opts, dict):
nic_opts = salt.utils.odict.OrderedDict()
# have a reference to the default nic
eth0 = nic_opts.setdefault(default_nic,
salt.utils.odict.OrderedDict())
# lxc config is based of ifc order, be sure to use odicts.
if not isinstance(nic_opts, salt.utils.odict.OrderedDict):
bnic_opts = salt.utils.odict.OrderedDict()
bnic_opts.update(nic_opts)
nic_opts = bnic_opts
gw = None
# legacy salt.cloud scheme for network interfaces settings support
bridge = _cloud_get('bridge', None)
ip = _cloud_get('ip', None)
mac = _cloud_get('mac', None)
if ip:
fullip = ip
if netmask:
fullip += '/{0}'.format(netmask)
eth0['ipv4'] = fullip
if mac is not None:
eth0['mac'] = mac
for ix, iopts in enumerate(_cloud_get("additional_ips", [])):
ifh = "eth{0}".format(ix+1)
ethx = nic_opts.setdefault(ifh, {})
if gw is None:
gw = iopts.get('gateway', ethx.get('gateway', None))
if gw:
# only one and only one default gateway is allowed !
eth0.pop('gateway', None)
gateway = None
# even if the gateway if on default "eth0" nic
# and we popped it will work
# as we reinject or set it here.
ethx['gateway'] = gw
elink = iopts.get('link', ethx.get('link', None))
if elink:
ethx['link'] = elink
# allow dhcp
aip = iopts.get('ipv4', iopts.get('ip', None))
if aip:
ethx['ipv4'] = aip
nm = iopts.get('netmask', '')
if nm:
ethx['ipv4'] += '/{0}'.format(nm)
for i in ('mac', 'hwaddr'):
if i in iopts:
ethx['mac'] = iopts[i]
break
if 'mac' not in ethx:
ethx['mac'] = salt.utils.network.gen_mac()
# last round checking for unique gateway and such
gw = None
for ethx in [a for a in nic_opts]:
ndata = nic_opts[ethx]
if gw:
ndata.pop('gateway', None)
if 'gateway' in ndata:
gw = ndata['gateway']
gateway = None
# only use a default bridge / gateway if we configured them
# via the legacy salt cloud configuration style.
# On other cases, we should rely on settings provided by the new
# salt lxc network profile style configuration which can
# be also be overridden or a per interface basis via the nic_opts dict.
if bridge:
eth0['link'] = bridge
if gateway:
eth0['gateway'] = gateway
#
lxc_init_interface = {}
lxc_init_interface['name'] = name
lxc_init_interface['config'] = config
lxc_init_interface['memory'] = _cloud_get('memory', 0) # nolimit
lxc_init_interface['pub_key'] = pub_key
lxc_init_interface['priv_key'] = priv_key
lxc_init_interface['nic_opts'] = nic_opts
for clone_from in ['clone_from', 'clone', 'from_container']:
# clone_from should default to None if not available
lxc_init_interface['clone_from'] = _cloud_get(clone_from, None)
if lxc_init_interface['clone_from'] is not None:
break
lxc_init_interface['profile'] = profile
lxc_init_interface['snapshot'] = snapshot
lxc_init_interface['dnsservers'] = dnsservers
lxc_init_interface['fstype'] = fstype
lxc_init_interface['path'] = path
lxc_init_interface['vgname'] = vgname
lxc_init_interface['size'] = size
lxc_init_interface['lvname'] = lvname
lxc_init_interface['thinpool'] = thinpool
lxc_init_interface['force_install'] = force_install
lxc_init_interface['unconditional_install'] = (
unconditional_install
)
lxc_init_interface['bootstrap_url'] = script
lxc_init_interface['bootstrap_args'] = script_args
lxc_init_interface['bootstrap_shell'] = _cloud_get('bootstrap_shell', 'sh')
lxc_init_interface['bootstrap_delay'] = _cloud_get('bootstrap_delay', None)
lxc_init_interface['autostart'] = autostart
lxc_init_interface['users'] = users
lxc_init_interface['password'] = password
lxc_init_interface['password_encrypted'] = password_encrypted
# be sure not to let objects goes inside the return
# as this return will be msgpacked for use in the runner !
lxc_init_interface['network_profile'] = network_profile
for i in ['cpu', 'cpuset', 'cpushare']:
if _cloud_get(i, None):
try:
lxc_init_interface[i] = vm_[i]
except KeyError:
lxc_init_interface[i] = profile[i]
return lxc_init_interface
def _get_profile(key, name, **kwargs):
if isinstance(name, dict):
profilename = name.pop('name', None)
return _get_profile(key, profilename, **name)
if name is None:
profile_match = {}
else:
profile_match = \
__salt__['config.get'](
'lxc.{1}:{0}'.format(name, key),
default=None,
merge='recurse'
)
if profile_match is None:
# No matching profile, make the profile an empty dict so that
# overrides can be applied below.
profile_match = {}
if not isinstance(profile_match, dict):
raise CommandExecutionError('lxc.{0} must be a dictionary'.format(key))
# Overlay the kwargs to override matched profile data
overrides = salt.utils.args.clean_kwargs(**copy.deepcopy(kwargs))
profile_match = salt.utils.dictupdate.update(
copy.deepcopy(profile_match),
overrides
)
return profile_match
def get_container_profile(name=None, **kwargs):
'''
.. versionadded:: 2015.5.0
Gather a pre-configured set of container configuration parameters. If no
arguments are passed, an empty profile is returned.
Profiles can be defined in the minion or master config files, or in pillar
or grains, and are loaded using :mod:`config.get
<salt.modules.config.get>`. The key under which LXC profiles must be
configured is ``lxc.container_profile.profile_name``. An example container
profile would be as follows:
.. code-block:: yaml
lxc.container_profile:
ubuntu:
template: ubuntu
backing: lvm
vgname: lxc
size: 1G
Parameters set in a profile can be overridden by passing additional
container creation arguments (such as the ones passed to :mod:`lxc.create
<salt.modules.lxc.create>`) to this function.
A profile can be defined either as the name of the profile, or a dictionary
of variable names and values. See the :ref:`LXC Tutorial
<tutorial-lxc-profiles>` for more information on how to use LXC profiles.
CLI Example:
.. code-block:: bash
salt-call lxc.get_container_profile centos
salt-call lxc.get_container_profile ubuntu template=ubuntu backing=overlayfs
'''
profile = _get_profile('container_profile', name, **kwargs)
return profile
def get_network_profile(name=None, **kwargs):
'''
.. versionadded:: 2015.5.0
Gather a pre-configured set of network configuration parameters. If no
arguments are passed, the following default profile is returned:
.. code-block:: python
{'eth0': {'link': 'br0', 'type': 'veth', 'flags': 'up'}}
Profiles can be defined in the minion or master config files, or in pillar
or grains, and are loaded using :mod:`config.get
<salt.modules.config.get>`. The key under which LXC profiles must be
configured is ``lxc.network_profile``. An example network profile would be
as follows:
.. code-block:: yaml
lxc.network_profile.centos:
eth0:
link: br0
type: veth
flags: up
To disable networking entirely:
.. code-block:: yaml
lxc.network_profile.centos:
eth0:
disable: true
Parameters set in a profile can be overridden by passing additional
arguments to this function.
A profile can be passed either as the name of the profile, or a
dictionary of variable names and values. See the :ref:`LXC Tutorial
<tutorial-lxc-profiles>` for more information on how to use network
profiles.
.. warning::
The ``ipv4``, ``ipv6``, ``gateway``, and ``link`` (bridge) settings in
network profiles will only work if the container doesn't redefine the
network configuration (for example in
``/etc/sysconfig/network-scripts/ifcfg-<interface_name>`` on
RHEL/CentOS, or ``/etc/network/interfaces`` on Debian/Ubuntu/etc.)
CLI Example:
.. code-block:: bash
salt-call lxc.get_network_profile default
'''
profile = _get_profile('network_profile', name, **kwargs)
return profile
def _rand_cpu_str(cpu):
'''
Return a random subset of cpus for the cpuset config
'''
cpu = int(cpu)
avail = __salt__['status.nproc']()
if cpu < avail:
return '0-{0}'.format(avail)
to_set = set()
while len(to_set) < cpu:
choice = random.randint(0, avail - 1)
if choice not in to_set:
to_set.add(six.text_type(choice))
return ','.join(sorted(to_set))
def _network_conf(conf_tuples=None, **kwargs):
'''
Network configuration defaults
network_profile
as for containers, we can either call this function
either with a network_profile dict or network profile name
in the kwargs
nic_opts
overrides or extra nics in the form {nic_name: {set: tings}
'''
nic = kwargs.get('network_profile', None)
ret = []
nic_opts = kwargs.get('nic_opts', {})
if nic_opts is None:
# coming from elsewhere
nic_opts = {}
if not conf_tuples:
conf_tuples = []
old = _get_veths(conf_tuples)
if not old:
old = {}
# if we have a profile name, get the profile and load the network settings
# this will obviously by default look for a profile called "eth0"
# or by what is defined in nic_opts
# and complete each nic settings by sane defaults
if nic and isinstance(nic, (six.string_types, dict)):
nicp = get_network_profile(nic)
else:
nicp = {}
if DEFAULT_NIC not in nicp:
nicp[DEFAULT_NIC] = {}
kwargs = copy.deepcopy(kwargs)
gateway = kwargs.pop('gateway', None)
bridge = kwargs.get('bridge', None)
if nic_opts:
for dev, args in six.iteritems(nic_opts):
ethx = nicp.setdefault(dev, {})
try:
ethx = salt.utils.dictupdate.update(ethx, args)
except AttributeError:
raise SaltInvocationError('Invalid nic_opts configuration')
ifs = [a for a in nicp]
ifs += [a for a in old if a not in nicp]
ifs.sort()
gateway_set = False
for dev in ifs:
args = nicp.get(dev, {})
opts = nic_opts.get(dev, {}) if nic_opts else {}
old_if = old.get(dev, {})
disable = opts.get('disable', args.get('disable', False))
if disable:
continue
mac = opts.get('mac',
opts.get('hwaddr',
args.get('mac',
args.get('hwaddr', ''))))
type_ = opts.get('type', args.get('type', ''))
flags = opts.get('flags', args.get('flags', ''))
link = opts.get('link', args.get('link', ''))
ipv4 = opts.get('ipv4', args.get('ipv4', ''))
ipv6 = opts.get('ipv6', args.get('ipv6', ''))
infos = salt.utils.odict.OrderedDict([
('lxc.network.type', {
'test': not type_,
'value': type_,
'old': old_if.get('lxc.network.type'),
'default': 'veth'}),
('lxc.network.name', {
'test': False,
'value': dev,
'old': dev,
'default': dev}),
('lxc.network.flags', {
'test': not flags,
'value': flags,
'old': old_if.get('lxc.network.flags'),
'default': 'up'}),
('lxc.network.link', {
'test': not link,
'value': link,
'old': old_if.get('lxc.network.link'),
'default': search_lxc_bridge()}),
('lxc.network.hwaddr', {
'test': not mac,
'value': mac,
'old': old_if.get('lxc.network.hwaddr'),
'default': salt.utils.network.gen_mac()}),
('lxc.network.ipv4', {
'test': not ipv4,
'value': ipv4,
'old': old_if.get('lxc.network.ipv4', ''),
'default': None}),
('lxc.network.ipv6', {
'test': not ipv6,
'value': ipv6,
'old': old_if.get('lxc.network.ipv6', ''),
'default': None})])
# for each parameter, if not explicitly set, the
# config value present in the LXC configuration should
# take precedence over the profile configuration
for info in list(infos.keys()):
bundle = infos[info]
if bundle['test']:
if bundle['old']:
bundle['value'] = bundle['old']
elif bundle['default']:
bundle['value'] = bundle['default']
for info, data in six.iteritems(infos):
if data['value']:
ret.append({info: data['value']})
for key, val in six.iteritems(args):
if key == 'link' and bridge:
val = bridge
val = opts.get(key, val)
if key in [
'type', 'flags', 'name',
'gateway', 'mac', 'link', 'ipv4', 'ipv6'
]:
continue
ret.append({'lxc.network.{0}'.format(key): val})
# gateway (in automode) must be appended following network conf !
if not gateway:
gateway = args.get('gateway', None)
if gateway is not None and not gateway_set:
ret.append({'lxc.network.ipv4.gateway': gateway})
# only one network gateway ;)
gateway_set = True
# normally, this won't happen
# set the gateway if specified even if we did
# not managed the network underlying
if gateway is not None and not gateway_set:
ret.append({'lxc.network.ipv4.gateway': gateway})
# only one network gateway ;)
gateway_set = True
new = _get_veths(ret)
# verify that we did not loose the mac settings
for iface in [a for a in new]:
ndata = new[iface]
nmac = ndata.get('lxc.network.hwaddr', '')
ntype = ndata.get('lxc.network.type', '')
omac, otype = '', ''
if iface in old:
odata = old[iface]
omac = odata.get('lxc.network.hwaddr', '')
otype = odata.get('lxc.network.type', '')
# default for network type is setted here
# attention not to change the network type
# without a good and explicit reason to.
if otype and not ntype:
ntype = otype
if not ntype:
ntype = 'veth'
new[iface]['lxc.network.type'] = ntype
if omac and not nmac:
new[iface]['lxc.network.hwaddr'] = omac
ret = []
for val in six.itervalues(new):
for row in val:
ret.append(salt.utils.odict.OrderedDict([(row, val[row])]))
# on old versions of lxc, still support the gateway auto mode
# if we didn't explicitly say no to
# (lxc.network.ipv4.gateway: auto)
if _LooseVersion(version()) <= _LooseVersion('1.0.7') and \
True not in ['lxc.network.ipv4.gateway' in a for a in ret] and \
True in ['lxc.network.ipv4' in a for a in ret]:
ret.append({'lxc.network.ipv4.gateway': 'auto'})
return ret
def _get_lxc_default_data(**kwargs):
kwargs = copy.deepcopy(kwargs)
ret = {}
for k in ['utsname', 'rootfs']:
val = kwargs.get(k, None)
if val is not None:
ret['lxc.{0}'.format(k)] = val
autostart = kwargs.get('autostart')
# autostart can have made in kwargs, but with the None
# value which is invalid, we need an explicit boolean
# autostart = on is the default.
if autostart is None:
autostart = True
# we will set the regular lxc marker to restart container at
# machine (re)boot only if we did not explicitly ask
# not to touch to the autostart settings via
# autostart == 'keep'
if autostart != 'keep':
if autostart:
ret['lxc.start.auto'] = '1'
else:
ret['lxc.start.auto'] = '0'
memory = kwargs.get('memory')
if memory is not None:
# converting the config value from MB to bytes
ret['lxc.cgroup.memory.limit_in_bytes'] = memory * 1024 * 1024
cpuset = kwargs.get('cpuset')
if cpuset:
ret['lxc.cgroup.cpuset.cpus'] = cpuset
cpushare = kwargs.get('cpushare')
cpu = kwargs.get('cpu')
if cpushare:
ret['lxc.cgroup.cpu.shares'] = cpushare
if cpu and not cpuset:
ret['lxc.cgroup.cpuset.cpus'] = _rand_cpu_str(cpu)
return ret
def _config_list(conf_tuples=None, only_net=False, **kwargs):
'''
Return a list of dicts from the salt level configurations
conf_tuples
_LXCConfig compatible list of entries which can contain
- string line
- tuple (lxc config param,value)
- dict of one entry: {lxc config param: value)
only_net
by default we add to the tuples a reflection of both
the real config if avalaible and a certain amount of
default values like the cpu parameters, the memory
and etc.
On the other hand, we also no matter the case reflect
the network configuration computed from the actual config if
available and given values.
if no_default_loads is set, we will only
reflect the network configuration back to the conf tuples
list
'''
# explicit cast
only_net = bool(only_net)
if not conf_tuples:
conf_tuples = []
kwargs = copy.deepcopy(kwargs)
ret = []
if not only_net:
default_data = _get_lxc_default_data(**kwargs)
for k, val in six.iteritems(default_data):
ret.append({k: val})
net_datas = _network_conf(conf_tuples=conf_tuples, **kwargs)
ret.extend(net_datas)
return ret
def _get_veths(net_data):
'''
Parse the nic setup inside lxc conf tuples back to a dictionary indexed by
network interface
'''
if isinstance(net_data, dict):
net_data = list(net_data.items())
nics = salt.utils.odict.OrderedDict()
current_nic = salt.utils.odict.OrderedDict()
no_names = True
for item in net_data:
if item and isinstance(item, dict):
item = list(item.items())[0]
# skip LXC configuration comment lines, and play only with tuples conf
elif isinstance(item, six.string_types):
# deal with reflection of commented lxc configs
sitem = item.strip()
if sitem.startswith('#') or not sitem:
continue
elif '=' in item:
item = tuple([a.strip() for a in item.split('=', 1)])
if item[0] == 'lxc.network.type':
current_nic = salt.utils.odict.OrderedDict()
if item[0] == 'lxc.network.name':
no_names = False
nics[item[1].strip()] = current_nic
current_nic[item[0].strip()] = item[1].strip()
# if not ethernet card name has been collected, assuming we collected
# data for eth0
if no_names and current_nic:
nics[DEFAULT_NIC] = current_nic
return nics
class _LXCConfig(object):
'''
LXC configuration data
'''
pattern = re.compile(r'^(\S+)(\s*)(=)(\s*)(.*)')
non_interpretable_pattern = re.compile(r'^((#.*)|(\s*))$')
def __init__(self, **kwargs):
kwargs = copy.deepcopy(kwargs)
self.name = kwargs.pop('name', None)
path = get_root_path(kwargs.get('path', None))
self.data = []
if self.name:
self.path = os.path.join(path, self.name, 'config')
if os.path.isfile(self.path):
with salt.utils.files.fopen(self.path) as fhr:
for line in salt.utils.data.decode(fhr.readlines()):
match = self.pattern.findall((line.strip()))
if match:
self.data.append((match[0][0], match[0][-1]))
match = self.non_interpretable_pattern.findall(
(line.strip()))
if match:
self.data.append(('', match[0][0]))
else:
self.path = None
def _replace(key, val):
if val:
self._filter_data(key)
self.data.append((key, val))
default_data = _get_lxc_default_data(**kwargs)
for key, val in six.iteritems(default_data):
_replace(key, val)
old_net = self._filter_data('lxc.network')
net_datas = _network_conf(conf_tuples=old_net, **kwargs)
if net_datas:
for row in net_datas:
self.data.extend(list(row.items()))
# be sure to reset harmful settings
for idx in ['lxc.cgroup.memory.limit_in_bytes']:
if not default_data.get(idx):
self._filter_data(idx)
def as_string(self):
chunks = ('{0[0]}{1}{0[1]}'.format(item, (' = ' if item[0] else '')) for item in self.data)
return '\n'.join(chunks) + '\n'
def write(self):
if self.path:
content = self.as_string()
# 2 step rendering to be sure not to open/wipe the config
# before as_string succeeds.
with salt.utils.files.fopen(self.path, 'w') as fic:
fic.write(salt.utils.stringutils.to_str(content))
fic.flush()
def tempfile(self):
# this might look like the function name is shadowing the
# module, but it's not since the method belongs to the class
ntf = tempfile.NamedTemporaryFile()
ntf.write(self.as_string())
ntf.flush()
return ntf
def _filter_data(self, pattern):
'''
Removes parameters which match the pattern from the config data
'''
removed = []
filtered = []
for param in self.data:
if not param[0].startswith(pattern):
filtered.append(param)
else:
removed.append(param)
self.data = filtered
return removed
def _get_base(**kwargs):
'''
If the needed base does not exist, then create it, if it does exist
create nothing and return the name of the base lxc container so
it can be cloned.
'''
profile = get_container_profile(copy.deepcopy(kwargs.get('profile')))
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, _marker)
profile_match = profile.pop(key, default)
# let kwarg overrides be the preferred choice
if kw_overrides_match is _marker:
return profile_match
return kw_overrides_match
template = select('template')
image = select('image')
vgname = select('vgname')
path = kwargs.get('path', None)
# remove the above three variables from kwargs, if they exist, to avoid
# duplicates if create() is invoked below.
for param in ('path', 'image', 'vgname', 'template'):
kwargs.pop(param, None)
if image:
proto = _urlparse(image).scheme
img_tar = __salt__['cp.cache_file'](image)
img_name = os.path.basename(img_tar)
hash_ = salt.utils.hashutils.get_hash(
img_tar,
__salt__['config.get']('hash_type'))
name = '__base_{0}_{1}_{2}'.format(proto, img_name, hash_)
if not exists(name, path=path):
create(name, template=template, image=image,
path=path, vgname=vgname, **kwargs)
if vgname:
rootfs = os.path.join('/dev', vgname, name)
edit_conf(info(name, path=path)['config'],
out_format='commented', **{'lxc.rootfs': rootfs})
return name
elif template:
name = '__base_{0}'.format(template)
if not exists(name, path=path):
create(name, template=template, image=image, path=path,
vgname=vgname, **kwargs)
if vgname:
rootfs = os.path.join('/dev', vgname, name)
edit_conf(info(name, path=path)['config'],
out_format='commented', **{'lxc.rootfs': rootfs})
return name
return ''
def init(name,
config=None,
cpuset=None,
cpushare=None,
memory=None,
profile=None,
network_profile=None,
nic_opts=None,
cpu=None,
autostart=True,
password=None,
password_encrypted=None,
users=None,
dnsservers=None,
searchdomains=None,
bridge=None,
gateway=None,
pub_key=None,
priv_key=None,
force_install=False,
unconditional_install=False,
bootstrap_delay=None,
bootstrap_args=None,
bootstrap_shell=None,
bootstrap_url=None,
**kwargs):
'''
Initialize a new container.
This is a partial idempotent function as if it is already provisioned, we
will reset a bit the lxc configuration file but much of the hard work will
be escaped as markers will prevent re-execution of harmful tasks.
name
Name of the container
image
A tar archive to use as the rootfs for the container. Conflicts with
the ``template`` argument.
cpus
Select a random number of cpu cores and assign it to the cpuset, if the
cpuset option is set then this option will be ignored
cpuset
Explicitly define the cpus this container will be bound to
cpushare
cgroups cpu shares
autostart
autostart container on reboot
memory
cgroups memory limit, in MB
.. versionchanged:: 2015.5.0
If no value is passed, no limit is set. In earlier Salt versions,
not passing this value causes a 1024MB memory limit to be set, and
it was necessary to pass ``memory=0`` to set no limit.
gateway
the ipv4 gateway to use
the default does nothing more than lxcutils does
bridge
the bridge to use
the default does nothing more than lxcutils does
network_profile
Network profile to use for the container
.. versionadded:: 2015.5.0
nic_opts
Extra options for network interfaces, will override
``{"eth0": {"hwaddr": "aa:bb:cc:dd:ee:ff", "ipv4": "10.1.1.1", "ipv6": "2001:db8::ff00:42:8329"}}``
or
``{"eth0": {"hwaddr": "aa:bb:cc:dd:ee:ff", "ipv4": "10.1.1.1/24", "ipv6": "2001:db8::ff00:42:8329"}}``
users
Users for which the password defined in the ``password`` param should
be set. Can be passed as a comma separated list or a python list.
Defaults to just the ``root`` user.
password
Set the initial password for the users defined in the ``users``
parameter
password_encrypted : False
Set to ``True`` to denote a password hash instead of a plaintext
password
.. versionadded:: 2015.5.0
profile
A LXC profile (defined in config or pillar).
This can be either a real profile mapping or a string
to retrieve it in configuration
start
Start the newly-created container
dnsservers
list of dns servers to set in the container, default [] (no setting)
seed
Seed the container with the minion config. Default: ``True``
install
If salt-minion is not already installed, install it. Default: ``True``
config
Optional config parameters. By default, the id is set to
the name of the container.
master
salt master (default to minion's master)
master_port
salt master port (default to minion's master port)
pub_key
Explicit public key to preseed the minion with (optional).
This can be either a filepath or a string representing the key
priv_key
Explicit private key to preseed the minion with (optional).
This can be either a filepath or a string representing the key
approve_key
If explicit preseeding is not used;
Attempt to request key approval from the master. Default: ``True``
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
clone_from
Original from which to use a clone operation to create the container.
Default: ``None``
bootstrap_delay
Delay in seconds between end of container creation and bootstrapping.
Useful when waiting for container to obtain a DHCP lease.
.. versionadded:: 2015.5.0
bootstrap_url
See lxc.bootstrap
bootstrap_shell
See lxc.bootstrap
bootstrap_args
See lxc.bootstrap
force_install
Force installation even if salt-minion is detected,
this is the way to run vendor bootstrap scripts even
if a salt minion is already present in the container
unconditional_install
Run the script even if the container seems seeded
CLI Example:
.. code-block:: bash
salt 'minion' lxc.init name [cpuset=cgroups_cpuset] \\
[cpushare=cgroups_cpushare] [memory=cgroups_memory] \\
[nic=nic_profile] [profile=lxc_profile] \\
[nic_opts=nic_opts] [start=(True|False)] \\
[seed=(True|False)] [install=(True|False)] \\
[config=minion_config] [approve_key=(True|False) \\
[clone_from=original] [autostart=True] \\
[priv_key=/path_or_content] [pub_key=/path_or_content] \\
[bridge=lxcbr0] [gateway=10.0.3.1] \\
[dnsservers[dns1,dns2]] \\
[users=[foo]] [password='secret'] \\
[password_encrypted=(True|False)]
'''
ret = {'name': name,
'changes': {}}
profile = get_container_profile(copy.deepcopy(profile))
if not network_profile:
network_profile = profile.get('network_profile')
if not network_profile:
network_profile = DEFAULT_NIC
# Changes is a pointer to changes_dict['init']. This method is used so that
# we can have a list of changes as they are made, providing an ordered list
# of things that were changed.
changes_dict = {'init': []}
changes = changes_dict.get('init')
if users is None:
users = []
dusers = ['root']
for user in dusers:
if user not in users:
users.append(user)
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, _marker)
profile_match = profile.pop(key, default)
# let kwarg overrides be the preferred choice
if kw_overrides_match is _marker:
return profile_match
return kw_overrides_match
path = select('path')
bpath = get_root_path(path)
state_pre = state(name, path=path)
tvg = select('vgname')
vgname = tvg if tvg else __salt__['config.get']('lxc.vgname')
start_ = select('start', True)
autostart = select('autostart', autostart)
seed = select('seed', True)
install = select('install', True)
seed_cmd = select('seed_cmd')
salt_config = _get_salt_config(config, **kwargs)
approve_key = select('approve_key', True)
clone_from = select('clone_from')
# If using a volume group then set up to make snapshot cow clones
if vgname and not clone_from:
try:
kwargs['vgname'] = vgname
clone_from = _get_base(profile=profile, **kwargs)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = exc.strerror
if changes:
ret['changes'] = changes_dict
return ret
if not kwargs.get('snapshot') is False:
kwargs['snapshot'] = True
does_exist = exists(name, path=path)
to_reboot = False
remove_seed_marker = False
if does_exist:
pass
elif clone_from:
remove_seed_marker = True
try:
clone(name, clone_from, profile=profile, **kwargs)
changes.append({'create': 'Container cloned'})
except (SaltInvocationError, CommandExecutionError) as exc:
if 'already exists' in exc.strerror:
changes.append({'create': 'Container already exists'})
else:
ret['result'] = False
ret['comment'] = exc.strerror
if changes:
ret['changes'] = changes_dict
return ret
cfg = _LXCConfig(name=name, network_profile=network_profile,
nic_opts=nic_opts, bridge=bridge, path=path,
gateway=gateway, autostart=autostart,
cpuset=cpuset, cpushare=cpushare, memory=memory)
old_chunks = read_conf(cfg.path, out_format='commented')
cfg.write()
chunks = read_conf(cfg.path, out_format='commented')
if old_chunks != chunks:
to_reboot = True
else:
remove_seed_marker = True
cfg = _LXCConfig(network_profile=network_profile,
nic_opts=nic_opts, cpuset=cpuset, path=path,
bridge=bridge, gateway=gateway,
autostart=autostart,
cpushare=cpushare, memory=memory)
with cfg.tempfile() as cfile:
try:
create(name, config=cfile.name, profile=profile, **kwargs)
changes.append({'create': 'Container created'})
except (SaltInvocationError, CommandExecutionError) as exc:
if 'already exists' in exc.strerror:
changes.append({'create': 'Container already exists'})
else:
ret['comment'] = exc.strerror
if changes:
ret['changes'] = changes_dict
return ret
cpath = os.path.join(bpath, name, 'config')
old_chunks = []
if os.path.exists(cpath):
old_chunks = read_conf(cpath, out_format='commented')
new_cfg = _config_list(conf_tuples=old_chunks,
cpu=cpu,
network_profile=network_profile,
nic_opts=nic_opts, bridge=bridge,
cpuset=cpuset, cpushare=cpushare,
memory=memory)
if new_cfg:
edit_conf(cpath, out_format='commented', lxc_config=new_cfg)
chunks = read_conf(cpath, out_format='commented')
if old_chunks != chunks:
to_reboot = True
# last time to be sure any of our property is correctly applied
cfg = _LXCConfig(name=name, network_profile=network_profile,
nic_opts=nic_opts, bridge=bridge, path=path,
gateway=gateway, autostart=autostart,
cpuset=cpuset, cpushare=cpushare, memory=memory)
old_chunks = []
if os.path.exists(cfg.path):
old_chunks = read_conf(cfg.path, out_format='commented')
cfg.write()
chunks = read_conf(cfg.path, out_format='commented')
if old_chunks != chunks:
changes.append({'config': 'Container configuration updated'})
to_reboot = True
if to_reboot:
try:
stop(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
if changes:
ret['changes'] = changes_dict
return ret
if not does_exist or (does_exist and state(name, path=path) != 'running'):
try:
start(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
if changes:
ret['changes'] = changes_dict
return ret
if remove_seed_marker:
run(name,
'rm -f \'{0}\''.format(SEED_MARKER),
path=path,
chroot_fallback=False,
python_shell=False)
# set the default user/password, only the first time
if ret.get('result', True) and password:
gid = '/.lxc.initial_pass'
gids = [gid,
'/lxc.initial_pass',
'/.lxc.{0}.initial_pass'.format(name)]
if not any(retcode(name,
'test -e "{0}"'.format(x),
chroot_fallback=True,
path=path,
ignore_retcode=True) == 0
for x in gids):
# think to touch the default user generated by default templates
# which has a really unsecure passwords...
# root is defined as a member earlier in the code
for default_user in ['ubuntu']:
if (
default_user not in users and
retcode(name,
'id {0}'.format(default_user),
python_shell=False,
path=path,
chroot_fallback=True,
ignore_retcode=True) == 0
):
users.append(default_user)
for user in users:
try:
cret = set_password(name,
users=[user],
path=path,
password=password,
encrypted=password_encrypted)
except (SaltInvocationError, CommandExecutionError) as exc:
msg = '{0}: Failed to set password'.format(
user) + exc.strerror
# only hardfail in unrecoverable situation:
# root cannot be setted up
if user == 'root':
ret['comment'] = msg
ret['result'] = False
else:
log.debug(msg)
if ret.get('result', True):
changes.append({'password': 'Password(s) updated'})
if retcode(name,
('sh -c \'touch "{0}"; test -e "{0}"\''
.format(gid)),
path=path,
chroot_fallback=True,
ignore_retcode=True) != 0:
ret['comment'] = 'Failed to set password marker'
changes[-1]['password'] += '. ' + ret['comment'] + '.'
ret['result'] = False
# set dns servers if any, only the first time
if ret.get('result', True) and dnsservers:
# retro compatibility, test also old markers
gid = '/.lxc.initial_dns'
gids = [gid,
'/lxc.initial_dns',
'/lxc.{0}.initial_dns'.format(name)]
if not any(retcode(name,
'test -e "{0}"'.format(x),
chroot_fallback=True,
path=path,
ignore_retcode=True) == 0
for x in gids):
try:
set_dns(name,
path=path,
dnsservers=dnsservers,
searchdomains=searchdomains)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Failed to set DNS: ' + exc.strerror
ret['result'] = False
else:
changes.append({'dns': 'DNS updated'})
if retcode(name,
('sh -c \'touch "{0}"; test -e "{0}"\''
.format(gid)),
chroot_fallback=True,
path=path,
ignore_retcode=True) != 0:
ret['comment'] = 'Failed to set DNS marker'
changes[-1]['dns'] += '. ' + ret['comment'] + '.'
ret['result'] = False
# retro compatibility, test also old markers
if remove_seed_marker:
run(name,
'rm -f \'{0}\''.format(SEED_MARKER),
path=path,
python_shell=False)
gid = '/.lxc.initial_seed'
gids = [gid, '/lxc.initial_seed']
if (
any(retcode(name,
'test -e {0}'.format(x),
path=path,
chroot_fallback=True,
ignore_retcode=True) == 0
for x in gids) or not ret.get('result', True)
):
pass
elif seed or seed_cmd:
if seed:
try:
result = bootstrap(
name, config=salt_config, path=path,
approve_key=approve_key,
pub_key=pub_key, priv_key=priv_key,
install=install,
force_install=force_install,
unconditional_install=unconditional_install,
bootstrap_delay=bootstrap_delay,
bootstrap_url=bootstrap_url,
bootstrap_shell=bootstrap_shell,
bootstrap_args=bootstrap_args)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Bootstrap failed: ' + exc.strerror
ret['result'] = False
else:
if not result:
ret['comment'] = ('Bootstrap failed, see minion log for '
'more information')
ret['result'] = False
else:
changes.append(
{'bootstrap': 'Container successfully bootstrapped'}
)
elif seed_cmd:
try:
result = __salt__[seed_cmd](info(name, path=path)['rootfs'],
name,
salt_config)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = ('Bootstrap via seed_cmd \'{0}\' failed: {1}'
.format(seed_cmd, exc.strerror))
ret['result'] = False
else:
if not result:
ret['comment'] = ('Bootstrap via seed_cmd \'{0}\' failed, '
'see minion log for more information '
.format(seed_cmd))
ret['result'] = False
else:
changes.append(
{'bootstrap': 'Container successfully bootstrapped '
'using seed_cmd \'{0}\''
.format(seed_cmd)}
)
if ret.get('result', True) and not start_:
try:
stop(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
ret['result'] = False
state_post = state(name, path=path)
if state_pre != state_post:
changes.append({'state': {'old': state_pre, 'new': state_post}})
if ret.get('result', True):
ret['comment'] = ('Container \'{0}\' successfully initialized'
.format(name))
ret['result'] = True
if changes:
ret['changes'] = changes_dict
return ret
def cloud_init(name, vm_=None, **kwargs):
'''
Thin wrapper to lxc.init to be used from the saltcloud lxc driver
name
Name of the container
may be None and then guessed from saltcloud mapping
`vm_`
saltcloud mapping defaults for the vm
CLI Example:
.. code-block:: bash
salt '*' lxc.cloud_init foo
'''
init_interface = cloud_init_interface(name, vm_, **kwargs)
name = init_interface.pop('name', name)
return init(name, **init_interface)
def images(dist=None):
'''
.. versionadded:: 2015.5.0
List the available images for LXC's ``download`` template.
dist : None
Filter results to a single Linux distribution
CLI Examples:
.. code-block:: bash
salt myminion lxc.images
salt myminion lxc.images dist=centos
'''
out = __salt__['cmd.run_stdout'](
'lxc-create -n __imgcheck -t download -- --list',
ignore_retcode=True
)
if 'DIST' not in out:
raise CommandExecutionError(
'Unable to run the \'download\' template script. Is it installed?'
)
ret = {}
passed_header = False
for line in out.splitlines():
try:
distro, release, arch, variant, build_time = line.split()
except ValueError:
continue
if not passed_header:
if distro == 'DIST':
passed_header = True
continue
dist_list = ret.setdefault(distro, [])
dist_list.append({
'release': release,
'arch': arch,
'variant': variant,
'build_time': build_time,
})
if dist is not None:
return dict([(dist, ret.get(dist, []))])
return ret
def templates():
'''
.. versionadded:: 2015.5.0
List the available LXC template scripts installed on the minion
CLI Examples:
.. code-block:: bash
salt myminion lxc.templates
'''
try:
template_scripts = os.listdir('/usr/share/lxc/templates')
except OSError:
return []
else:
return [x[4:] for x in template_scripts if x.startswith('lxc-')]
def _after_ignition_network_profile(cmd,
ret,
name,
network_profile,
path,
nic_opts):
_clear_context()
if ret['retcode'] == 0 and exists(name, path=path):
if network_profile:
network_changes = apply_network_profile(name,
network_profile,
path=path,
nic_opts=nic_opts)
if network_changes:
log.info(
'Network changes from applying network profile \'%s\' '
'to newly-created container \'%s\':\n%s',
network_profile, name, network_changes
)
c_state = state(name, path=path)
return {'result': True,
'state': {'old': None, 'new': c_state}}
else:
if exists(name, path=path):
# destroy the container if it was partially created
cmd = 'lxc-destroy'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0}'.format(name)
__salt__['cmd.retcode'](cmd, python_shell=False)
raise CommandExecutionError(
'Container could not be created with cmd \'{0}\': {1}'
.format(cmd, ret['stderr'])
)
def create(name,
config=None,
profile=None,
network_profile=None,
nic_opts=None,
**kwargs):
'''
Create a new container.
name
Name of the container
config
The config file to use for the container. Defaults to system-wide
config (usually in /etc/lxc/lxc.conf).
profile
Profile to use in container creation (see
:mod:`lxc.get_container_profile
<salt.modules.lxc.get_container_profile>`). Values in a profile will be
overridden by the **Container Creation Arguments** listed below.
network_profile
Network profile to use for container
.. versionadded:: 2015.5.0
**Container Creation Arguments**
template
The template to use. For example, ``ubuntu`` or ``fedora``.
For a full list of available templates, check out
the :mod:`lxc.templates <salt.modules.lxc.templates>` function.
Conflicts with the ``image`` argument.
.. note::
The ``download`` template requires the following three parameters
to be defined in ``options``:
* **dist** - The name of the distribution
* **release** - Release name/version
* **arch** - Architecture of the container
The available images can be listed using the :mod:`lxc.images
<salt.modules.lxc.images>` function.
options
Template-specific options to pass to the lxc-create command. These
correspond to the long options (ones beginning with two dashes) that
the template script accepts. For example:
.. code-block:: bash
options='{"dist": "centos", "release": "6", "arch": "amd64"}'
For available template options, refer to the lxc template scripts
which are ususally located under ``/usr/share/lxc/templates``,
or run ``lxc-create -t <template> -h``.
image
A tar archive to use as the rootfs for the container. Conflicts with
the ``template`` argument.
backing
The type of storage to use. Set to ``lvm`` to use an LVM group.
Defaults to filesystem within /var/lib/lxc.
fstype
Filesystem type to use on LVM logical volume
size : 1G
Size of the volume to create. Only applicable if ``backing=lvm``.
vgname : lxc
Name of the LVM volume group in which to create the volume for this
container. Only applicable if ``backing=lvm``.
lvname
Name of the LVM logical volume in which to create the volume for this
container. Only applicable if ``backing=lvm``.
thinpool
Name of a pool volume that will be used for thin-provisioning this
container. Only applicable if ``backing=lvm``.
nic_opts
give extra opts overriding network profile values
path
parent path for the container creation (default: /var/lib/lxc)
zfsroot
Name of the ZFS root in which to create the volume for this container.
Only applicable if ``backing=zfs``. (default: tank/lxc)
.. versionadded:: 2015.8.0
'''
# Required params for 'download' template
download_template_deps = ('dist', 'release', 'arch')
cmd = 'lxc-create -n {0}'.format(name)
profile = get_container_profile(copy.deepcopy(profile))
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, None)
profile_match = profile.pop(key, default)
# Return the profile match if the the kwarg match was None, as the
# lxc.present state will pass these kwargs set to None by default.
if kw_overrides_match is None:
return profile_match
return kw_overrides_match
path = select('path')
if exists(name, path=path):
raise CommandExecutionError(
'Container \'{0}\' already exists'.format(name)
)
tvg = select('vgname')
vgname = tvg if tvg else __salt__['config.get']('lxc.vgname')
# The 'template' and 'image' params conflict
template = select('template')
image = select('image')
if template and image:
raise SaltInvocationError(
'Only one of \'template\' and \'image\' is permitted'
)
elif not any((template, image, profile)):
raise SaltInvocationError(
'At least one of \'template\', \'image\', and \'profile\' is '
'required'
)
options = select('options') or {}
backing = select('backing')
if vgname and not backing:
backing = 'lvm'
lvname = select('lvname')
thinpool = select('thinpool')
fstype = select('fstype')
size = select('size', '1G')
zfsroot = select('zfsroot')
if backing in ('dir', 'overlayfs', 'btrfs', 'zfs'):
fstype = None
size = None
# some backends won't support some parameters
if backing in ('aufs', 'dir', 'overlayfs', 'btrfs'):
lvname = vgname = thinpool = None
if image:
img_tar = __salt__['cp.cache_file'](image)
template = os.path.join(
os.path.dirname(salt.__file__),
'templates',
'lxc',
'salt_tarball')
options['imgtar'] = img_tar
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
if not os.path.exists(path):
os.makedirs(path)
if config:
cmd += ' -f {0}'.format(config)
if template:
cmd += ' -t {0}'.format(template)
if backing:
backing = backing.lower()
cmd += ' -B {0}'.format(backing)
if backing in ('zfs',):
if zfsroot:
cmd += ' --zfsroot {0}'.format(zfsroot)
if backing in ('lvm',):
if lvname:
cmd += ' --lvname {0}'.format(lvname)
if vgname:
cmd += ' --vgname {0}'.format(vgname)
if thinpool:
cmd += ' --thinpool {0}'.format(thinpool)
if backing not in ('dir', 'overlayfs'):
if fstype:
cmd += ' --fstype {0}'.format(fstype)
if size:
cmd += ' --fssize {0}'.format(size)
if options:
if template == 'download':
missing_deps = [x for x in download_template_deps
if x not in options]
if missing_deps:
raise SaltInvocationError(
'Missing params in \'options\' dict: {0}'
.format(', '.join(missing_deps))
)
cmd += ' --'
for key, val in six.iteritems(options):
cmd += ' --{0} {1}'.format(key, val)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
# please do not merge extra conflicting stuff
# inside those two line (ret =, return)
return _after_ignition_network_profile(cmd,
ret,
name,
network_profile,
path,
nic_opts)
def clone(name,
orig,
profile=None,
network_profile=None,
nic_opts=None,
**kwargs):
'''
Create a new container as a clone of another container
name
Name of the container
orig
Name of the original container to be cloned
profile
Profile to use in container cloning (see
:mod:`lxc.get_container_profile
<salt.modules.lxc.get_container_profile>`). Values in a profile will be
overridden by the **Container Cloning Arguments** listed below.
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
**Container Cloning Arguments**
snapshot
Use Copy On Write snapshots (LVM)
size : 1G
Size of the volume to create. Only applicable if ``backing=lvm``.
backing
The type of storage to use. Set to ``lvm`` to use an LVM group.
Defaults to filesystem within /var/lib/lxc.
network_profile
Network profile to use for container
.. versionadded:: 2015.8.0
nic_opts
give extra opts overriding network profile values
.. versionadded:: 2015.8.0
CLI Examples:
.. code-block:: bash
salt '*' lxc.clone myclone orig=orig_container
salt '*' lxc.clone myclone orig=orig_container snapshot=True
'''
profile = get_container_profile(copy.deepcopy(profile))
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, None)
profile_match = profile.pop(key, default)
# let kwarg overrides be the preferred choice
if kw_overrides_match is None:
return profile_match
return kw_overrides_match
path = select('path')
if exists(name, path=path):
raise CommandExecutionError(
'Container \'{0}\' already exists'.format(name)
)
_ensure_exists(orig, path=path)
if state(orig, path=path) != 'stopped':
raise CommandExecutionError(
'Container \'{0}\' must be stopped to be cloned'.format(orig)
)
backing = select('backing')
snapshot = select('snapshot')
if backing in ('dir',):
snapshot = False
if not snapshot:
snapshot = ''
else:
snapshot = '-s'
size = select('size', '1G')
if backing in ('dir', 'overlayfs', 'btrfs'):
size = None
# LXC commands and options changed in 2.0 - CF issue #34086 for details
if _LooseVersion(version()) >= _LooseVersion('2.0'):
# https://linuxcontainers.org/lxc/manpages//man1/lxc-copy.1.html
cmd = 'lxc-copy'
cmd += ' {0} -n {1} -N {2}'.format(snapshot, orig, name)
else:
# https://linuxcontainers.org/lxc/manpages//man1/lxc-clone.1.html
cmd = 'lxc-clone'
cmd += ' {0} -o {1} -n {2}'.format(snapshot, orig, name)
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
if not os.path.exists(path):
os.makedirs(path)
if backing:
backing = backing.lower()
cmd += ' -B {0}'.format(backing)
if backing not in ('dir', 'overlayfs'):
if size:
cmd += ' -L {0}'.format(size)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
# please do not merge extra conflicting stuff
# inside those two line (ret =, return)
return _after_ignition_network_profile(cmd,
ret,
name,
network_profile,
path,
nic_opts)
def ls_(active=None, cache=True, path=None):
'''
Return a list of the containers available on the minion
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
active
If ``True``, return only active (i.e. running) containers
.. versionadded:: 2015.5.0
CLI Example:
.. code-block:: bash
salt '*' lxc.ls
salt '*' lxc.ls active=True
'''
contextvar = 'lxc.ls{0}'.format(path)
if active:
contextvar += '.active'
if cache and (contextvar in __context__):
return __context__[contextvar]
else:
ret = []
cmd = 'lxc-ls'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
if active:
cmd += ' --active'
output = __salt__['cmd.run_stdout'](cmd, python_shell=False)
for line in output.splitlines():
ret.extend(line.split())
__context__[contextvar] = ret
return ret
def list_(extra=False, limit=None, path=None):
'''
List containers classified by state
extra
Also get per-container specific info. This will change the return data.
Instead of returning a list of containers, a dictionary of containers
and each container's output from :mod:`lxc.info
<salt.modules.lxc.info>`.
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
limit
Return output matching a specific state (**frozen**, **running**, or
**stopped**).
.. versionadded:: 2015.5.0
CLI Examples:
.. code-block:: bash
salt '*' lxc.list
salt '*' lxc.list extra=True
salt '*' lxc.list limit=running
'''
ctnrs = ls_(path=path)
if extra:
stopped = {}
frozen = {}
running = {}
else:
stopped = []
frozen = []
running = []
ret = {'running': running,
'stopped': stopped,
'frozen': frozen}
for container in ctnrs:
cmd = 'lxc-info'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0}'.format(container)
c_info = __salt__['cmd.run'](
cmd,
python_shell=False,
output_loglevel='debug'
)
c_state = None
for line in c_info.splitlines():
stat = line.split(':')
if stat[0] in ('State', 'state'):
c_state = stat[1].strip()
break
if not c_state or (limit is not None and c_state.lower() != limit):
continue
if extra:
infos = info(container, path=path)
method = 'update'
value = {container: infos}
else:
method = 'append'
value = container
if c_state == 'STOPPED':
getattr(stopped, method)(value)
continue
if c_state == 'FROZEN':
getattr(frozen, method)(value)
continue
if c_state == 'RUNNING':
getattr(running, method)(value)
continue
if limit is not None:
return ret.get(limit, {} if extra else [])
return ret
def _change_state(cmd,
name,
expected,
stdin=_marker,
stdout=_marker,
stderr=_marker,
with_communicate=_marker,
use_vt=_marker,
path=None):
pre = state(name, path=path)
if pre == expected:
return {'result': True,
'state': {'old': expected, 'new': expected},
'comment': 'Container \'{0}\' already {1}'
.format(name, expected)}
if cmd == 'lxc-destroy':
# Kill the container first
scmd = 'lxc-stop'
if path:
scmd += ' -P {0}'.format(pipes.quote(path))
scmd += ' -k -n {0}'.format(name)
__salt__['cmd.run'](scmd,
python_shell=False)
if path and ' -P ' not in cmd:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0}'.format(name)
# certain lxc commands need to be taken with care (lxc-start)
# as te command itself mess with double forks; we must not
# communicate with it, but just wait for the exit status
pkwargs = {'python_shell': False,
'redirect_stderr': True,
'with_communicate': with_communicate,
'use_vt': use_vt,
'stdin': stdin,
'stdout': stdout}
for i in [a for a in pkwargs]:
val = pkwargs[i]
if val is _marker:
pkwargs.pop(i, None)
_cmdout = __salt__['cmd.run_all'](cmd, **pkwargs)
if _cmdout['retcode'] != 0:
raise CommandExecutionError(
'Error changing state for container \'{0}\' using command '
'\'{1}\': {2}'.format(name, cmd, _cmdout['stdout'])
)
if expected is not None:
# some commands do not wait, so we will
rcmd = 'lxc-wait'
if path:
rcmd += ' -P {0}'.format(pipes.quote(path))
rcmd += ' -n {0} -s {1}'.format(name, expected.upper())
__salt__['cmd.run'](rcmd, python_shell=False, timeout=30)
_clear_context()
post = state(name, path=path)
ret = {'result': post == expected,
'state': {'old': pre, 'new': post}}
return ret
def _ensure_exists(name, path=None):
'''
Raise an exception if the container does not exist
'''
if not exists(name, path=path):
raise CommandExecutionError(
'Container \'{0}\' does not exist'.format(name)
)
def _ensure_running(name, no_start=False, path=None):
'''
If the container is not currently running, start it. This function returns
the state that the container was in before changing
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
'''
_ensure_exists(name, path=path)
pre = state(name, path=path)
if pre == 'running':
# This will be a no-op but running the function will give us a pretty
# return dict.
return start(name, path=path)
elif pre == 'stopped':
if no_start:
raise CommandExecutionError(
'Container \'{0}\' is not running'.format(name)
)
return start(name, path=path)
elif pre == 'frozen':
if no_start:
raise CommandExecutionError(
'Container \'{0}\' is not running'.format(name)
)
return unfreeze(name, path=path)
def restart(name, path=None, lxc_config=None, force=False):
'''
.. versionadded:: 2015.5.0
Restart the named container. If the container was not running, the
container will merely be started.
name
The name of the container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
lxc_config
path to a lxc config file
config file will be guessed from container name otherwise
.. versionadded:: 2015.8.0
force : False
If ``True``, the container will be force-stopped instead of gracefully
shut down
CLI Example:
.. code-block:: bash
salt myminion lxc.restart name
'''
_ensure_exists(name, path=path)
orig_state = state(name, path=path)
if orig_state != 'stopped':
stop(name, kill=force, path=path)
ret = start(name, path=path, lxc_config=lxc_config)
ret['state']['old'] = orig_state
if orig_state != 'stopped':
ret['restarted'] = True
return ret
def start(name, **kwargs):
'''
Start the named container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
lxc_config
path to a lxc config file
config file will be guessed from container name otherwise
.. versionadded:: 2015.8.0
use_vt
run the command through VT
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.start name
'''
path = kwargs.get('path', None)
cpath = get_root_path(path)
lxc_config = kwargs.get('lxc_config', None)
cmd = 'lxc-start'
if not lxc_config:
lxc_config = os.path.join(cpath, name, 'config')
# we try to start, even without config, if global opts are there
if os.path.exists(lxc_config):
cmd += ' -f {0}'.format(pipes.quote(lxc_config))
cmd += ' -d'
_ensure_exists(name, path=path)
if state(name, path=path) == 'frozen':
raise CommandExecutionError(
'Container \'{0}\' is frozen, use lxc.unfreeze'.format(name)
)
# lxc-start daemonize itself violently, we must not communicate with it
use_vt = kwargs.get('use_vt', None)
with_communicate = kwargs.get('with_communicate', False)
return _change_state(cmd, name, 'running',
stdout=None,
stderr=None,
stdin=None,
with_communicate=with_communicate,
path=path,
use_vt=use_vt)
def stop(name, kill=False, path=None, use_vt=None):
'''
Stop the named container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
kill: False
Do not wait for the container to stop, kill all tasks in the container.
Older LXC versions will stop containers like this irrespective of this
argument.
.. versionchanged:: 2015.5.0
Default value changed to ``False``
use_vt
run the command through VT
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.stop name
'''
_ensure_exists(name, path=path)
orig_state = state(name, path=path)
if orig_state == 'frozen' and not kill:
# Gracefully stopping a frozen container is slower than unfreezing and
# then stopping it (at least in my testing), so if we're not
# force-stopping the container, unfreeze it first.
unfreeze(name, path=path)
cmd = 'lxc-stop'
if kill:
cmd += ' -k'
ret = _change_state(cmd, name, 'stopped', use_vt=use_vt, path=path)
ret['state']['old'] = orig_state
return ret
def freeze(name, **kwargs):
'''
Freeze the named container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
start : False
If ``True`` and the container is stopped, the container will be started
before attempting to freeze.
.. versionadded:: 2015.5.0
use_vt
run the command through VT
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.freeze name
'''
use_vt = kwargs.get('use_vt', None)
path = kwargs.get('path', None)
_ensure_exists(name, path=path)
orig_state = state(name, path=path)
start_ = kwargs.get('start', False)
if orig_state == 'stopped':
if not start_:
raise CommandExecutionError(
'Container \'{0}\' is stopped'.format(name)
)
start(name, path=path)
cmd = 'lxc-freeze'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
ret = _change_state(cmd, name, 'frozen', use_vt=use_vt, path=path)
if orig_state == 'stopped' and start_:
ret['state']['old'] = orig_state
ret['started'] = True
ret['state']['new'] = state(name, path=path)
return ret
def unfreeze(name, path=None, use_vt=None):
'''
Unfreeze the named container.
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
use_vt
run the command through VT
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.unfreeze name
'''
_ensure_exists(name, path=path)
if state(name, path=path) == 'stopped':
raise CommandExecutionError(
'Container \'{0}\' is stopped'.format(name)
)
cmd = 'lxc-unfreeze'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
return _change_state(cmd, name, 'running', path=path, use_vt=use_vt)
# Compatibility between LXC and nspawn
remove = salt.utils.functools.alias_function(destroy, 'remove')
def exists(name, path=None):
'''
Returns whether the named container exists.
path
path to the container parent directory (default: /var/lib/lxc)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.exists name
'''
_exists = name in ls_(path=path)
# container may be just created but we did cached earlier the
# lxc-ls results
if not _exists:
_exists = name in ls_(cache=False, path=path)
return _exists
def state(name, path=None):
'''
Returns the state of a container.
path
path to the container parent directory (default: /var/lib/lxc)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.state name
'''
# Don't use _ensure_exists() here, it will mess with _change_state()
cachekey = 'lxc.state.{0}{1}'.format(name, path)
try:
return __context__[cachekey]
except KeyError:
if not exists(name, path=path):
__context__[cachekey] = None
else:
cmd = 'lxc-info'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0}'.format(name)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
if ret['retcode'] != 0:
_clear_context()
raise CommandExecutionError(
'Unable to get state of container \'{0}\''.format(name)
)
c_infos = ret['stdout'].splitlines()
c_state = None
for c_info in c_infos:
stat = c_info.split(':')
if stat[0].lower() == 'state':
c_state = stat[1].strip().lower()
break
__context__[cachekey] = c_state
return __context__[cachekey]
def get_parameter(name, parameter, path=None):
'''
Returns the value of a cgroup parameter for a container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.get_parameter container_name memory.limit_in_bytes
'''
_ensure_exists(name, path=path)
cmd = 'lxc-cgroup'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0} {1}'.format(name, parameter)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
if ret['retcode'] != 0:
raise CommandExecutionError(
'Unable to retrieve value for \'{0}\''.format(parameter)
)
return ret['stdout'].strip()
def set_parameter(name, parameter, value, path=None):
'''
Set the value of a cgroup parameter for a container.
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.set_parameter name parameter value
'''
if not exists(name, path=path):
return None
cmd = 'lxc-cgroup'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0} {1} {2}'.format(name, parameter, value)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
if ret['retcode'] != 0:
return False
else:
return True
def info(name, path=None):
'''
Returns information about a container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.info name
'''
cachekey = 'lxc.info.{0}{1}'.format(name, path)
try:
return __context__[cachekey]
except KeyError:
_ensure_exists(name, path=path)
cpath = get_root_path(path)
try:
conf_file = os.path.join(cpath, name, 'config')
except AttributeError:
conf_file = os.path.join(cpath, six.text_type(name), 'config')
if not os.path.isfile(conf_file):
raise CommandExecutionError(
'LXC config file {0} does not exist'.format(conf_file)
)
ret = {}
config = []
with salt.utils.files.fopen(conf_file) as fp_:
for line in fp_:
line = salt.utils.stringutils.to_unicode(line)
comps = [x.strip() for x in
line.split('#', 1)[0].strip().split('=', 1)]
if len(comps) == 2:
config.append(tuple(comps))
ifaces = []
current = None
for key, val in config:
if key == 'lxc.network.type':
current = {'type': val}
ifaces.append(current)
elif not current:
continue
elif key.startswith('lxc.network.'):
current[key.replace('lxc.network.', '', 1)] = val
if ifaces:
ret['nics'] = ifaces
ret['rootfs'] = next(
(x[1] for x in config if x[0] == 'lxc.rootfs'),
None
)
ret['state'] = state(name, path=path)
ret['ips'] = []
ret['public_ips'] = []
ret['private_ips'] = []
ret['public_ipv4_ips'] = []
ret['public_ipv6_ips'] = []
ret['private_ipv4_ips'] = []
ret['private_ipv6_ips'] = []
ret['ipv4_ips'] = []
ret['ipv6_ips'] = []
ret['size'] = None
ret['config'] = conf_file
if ret['state'] == 'running':
try:
limit = int(get_parameter(name, 'memory.limit_in_bytes'))
except (CommandExecutionError, TypeError, ValueError):
limit = 0
try:
usage = int(get_parameter(name, 'memory.usage_in_bytes'))
except (CommandExecutionError, TypeError, ValueError):
usage = 0
free = limit - usage
ret['memory_limit'] = limit
ret['memory_free'] = free
size = run_stdout(name, 'df /', path=path, python_shell=False)
# The size is the 2nd column of the last line
ret['size'] = size.splitlines()[-1].split()[1]
# First try iproute2
ip_cmd = run_all(
name, 'ip link show', path=path, python_shell=False)
if ip_cmd['retcode'] == 0:
ip_data = ip_cmd['stdout']
ip_cmd = run_all(
name, 'ip addr show', path=path, python_shell=False)
ip_data += '\n' + ip_cmd['stdout']
ip_data = salt.utils.network._interfaces_ip(ip_data)
else:
# That didn't work, try ifconfig
ip_cmd = run_all(
name, 'ifconfig', path=path, python_shell=False)
if ip_cmd['retcode'] == 0:
ip_data = \
salt.utils.network._interfaces_ifconfig(
ip_cmd['stdout'])
else:
# Neither was successful, give up
log.warning(
'Unable to run ip or ifconfig in container \'%s\'', name
)
ip_data = {}
ret['ipv4_ips'] = salt.utils.network.ip_addrs(
include_loopback=True,
interface_data=ip_data
)
ret['ipv6_ips'] = salt.utils.network.ip_addrs6(
include_loopback=True,
interface_data=ip_data
)
ret['ips'] = ret['ipv4_ips'] + ret['ipv6_ips']
for address in ret['ipv4_ips']:
if address == '127.0.0.1':
ret['private_ips'].append(address)
ret['private_ipv4_ips'].append(address)
elif salt.utils.cloud.is_public_ip(address):
ret['public_ips'].append(address)
ret['public_ipv4_ips'].append(address)
else:
ret['private_ips'].append(address)
ret['private_ipv4_ips'].append(address)
for address in ret['ipv6_ips']:
if address == '::1' or address.startswith('fe80'):
ret['private_ips'].append(address)
ret['private_ipv6_ips'].append(address)
else:
ret['public_ips'].append(address)
ret['public_ipv6_ips'].append(address)
for key in [x for x in ret if x == 'ips' or x.endswith('ips')]:
ret[key].sort(key=_ip_sort)
__context__[cachekey] = ret
return __context__[cachekey]
def set_password(name, users, password, encrypted=True, path=None):
'''
.. versionchanged:: 2015.5.0
Function renamed from ``set_pass`` to ``set_password``. Additionally,
this function now supports (and defaults to using) a password hash
instead of a plaintext password.
Set the password of one or more system users inside containers
users
Comma-separated list (or python list) of users to change password
password
Password to set for the specified user(s)
encrypted : True
If true, ``password`` must be a password hash. Set to ``False`` to set
a plaintext password (not recommended).
.. versionadded:: 2015.5.0
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.set_pass container-name root '$6$uJ2uAyLU$KoI67t8As/0fXtJOPcHKGXmUpcoYUcVR2K6x93walnShTCQvjRwq25yIkiCBOqgbfdKQSFnAo28/ek6716vEV1'
salt '*' lxc.set_pass container-name root foo encrypted=False
'''
def _bad_user_input():
raise SaltInvocationError('Invalid input for \'users\' parameter')
if not isinstance(users, list):
try:
users = users.split(',')
except AttributeError:
_bad_user_input()
if not users:
_bad_user_input()
failed_users = []
for user in users:
result = retcode(name,
'chpasswd{0}'.format(' -e' if encrypted else ''),
stdin=':'.join((user, password)),
python_shell=False,
path=path,
chroot_fallback=True,
output_loglevel='quiet')
if result != 0:
failed_users.append(user)
if failed_users:
raise CommandExecutionError(
'Password change failed for the following user(s): {0}'
.format(', '.join(failed_users))
)
return True
set_pass = salt.utils.functools.alias_function(set_password, 'set_pass')
def update_lxc_conf(name, lxc_conf, lxc_conf_unset, path=None):
'''
Edit LXC configuration options
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.update_lxc_conf ubuntu \\
lxc_conf="[{'network.ipv4.ip':'10.0.3.5'}]" \\
lxc_conf_unset="['lxc.utsname']"
'''
_ensure_exists(name, path=path)
cpath = get_root_path(path)
lxc_conf_p = os.path.join(cpath, name, 'config')
if not os.path.exists(lxc_conf_p):
raise SaltInvocationError(
'Configuration file {0} does not exist'.format(lxc_conf_p)
)
changes = {'edited': [], 'added': [], 'removed': []}
ret = {'changes': changes, 'result': True, 'comment': ''}
# do not use salt.utils.files.fopen !
with salt.utils.files.fopen(lxc_conf_p, 'r') as fic:
filtered_lxc_conf = []
for row in lxc_conf:
if not row:
continue
for conf in row:
filtered_lxc_conf.append((conf.strip(),
row[conf].strip()))
ret['comment'] = 'lxc.conf is up to date'
lines = []
orig_config = salt.utils.stringutils.to_unicode(fic.read())
for line in orig_config.splitlines():
if line.startswith('#') or not line.strip():
lines.append([line, ''])
else:
line = line.split('=')
index = line.pop(0)
val = (index.strip(), '='.join(line).strip())
if val not in lines:
lines.append(val)
for key, item in filtered_lxc_conf:
matched = False
for idx, line in enumerate(lines[:]):
if line[0] == key:
matched = True
lines[idx] = (key, item)
if '='.join(line[1:]).strip() != item.strip():
changes['edited'].append(
({line[0]: line[1:]}, {key: item}))
break
if not matched:
if (key, item) not in lines:
lines.append((key, item))
changes['added'].append({key: item})
dest_lxc_conf = []
# filter unset
if lxc_conf_unset:
for line in lines:
for opt in lxc_conf_unset:
if (
not line[0].startswith(opt) and
line not in dest_lxc_conf
):
dest_lxc_conf.append(line)
else:
changes['removed'].append(opt)
else:
dest_lxc_conf = lines
conf = ''
for key, val in dest_lxc_conf:
if not val:
conf += '{0}\n'.format(key)
else:
conf += '{0} = {1}\n'.format(key.strip(), val.strip())
conf_changed = conf != orig_config
chrono = datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S')
if conf_changed:
# DO NOT USE salt.utils.files.fopen here, i got (kiorky)
# problems with lxc configs which were wiped !
with salt.utils.files.fopen('{0}.{1}'.format(lxc_conf_p, chrono), 'w') as wfic:
wfic.write(salt.utils.stringutils.to_str(conf))
with salt.utils.files.fopen(lxc_conf_p, 'w') as wfic:
wfic.write(salt.utils.stringutils.to_str(conf))
ret['comment'] = 'Updated'
ret['result'] = True
if not any(changes[x] for x in changes):
# Ensure an empty changes dict if nothing was modified
ret['changes'] = {}
return ret
def set_dns(name, dnsservers=None, searchdomains=None, path=None):
'''
.. versionchanged:: 2015.5.0
The ``dnsservers`` and ``searchdomains`` parameters can now be passed
as a comma-separated list.
Update /etc/resolv.confo
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.set_dns ubuntu "['8.8.8.8', '4.4.4.4']"
'''
if dnsservers is None:
dnsservers = ['8.8.8.8', '4.4.4.4']
elif not isinstance(dnsservers, list):
try:
dnsservers = dnsservers.split(',')
except AttributeError:
raise SaltInvocationError(
'Invalid input for \'dnsservers\' parameter'
)
if searchdomains is None:
searchdomains = []
elif not isinstance(searchdomains, list):
try:
searchdomains = searchdomains.split(',')
except AttributeError:
raise SaltInvocationError(
'Invalid input for \'searchdomains\' parameter'
)
dns = ['nameserver {0}'.format(x) for x in dnsservers]
dns.extend(['search {0}'.format(x) for x in searchdomains])
dns = '\n'.join(dns) + '\n'
# we may be using resolvconf in the container
# We need to handle that case with care:
# - we create the resolv.conf runtime directory (the
# linked directory) as anyway it will be shadowed when the real
# runned tmpfs mountpoint will be mounted.
# ( /etc/resolv.conf -> ../run/resolvconf/resolv.conf)
# Indeed, it can save us in any other case (running, eg, in a
# bare chroot when repairing or preparing the container for
# operation.
# - We also teach resolvconf to use the aforementioned dns.
# - We finally also set /etc/resolv.conf in all cases
rstr = __salt__['test.random_hash']()
# no tmp here, apparmor won't let us execute !
script = '/sbin/{0}_dns.sh'.format(rstr)
DNS_SCRIPT = "\n".join([
# 'set -x',
'#!/usr/bin/env bash',
'if [ -h /etc/resolv.conf ];then',
' if [ "x$(readlink /etc/resolv.conf)"'
' = "x../run/resolvconf/resolv.conf" ];then',
' if [ ! -d /run/resolvconf/ ];then',
' mkdir -p /run/resolvconf',
' fi',
' cat > /etc/resolvconf/resolv.conf.d/head <<EOF',
dns,
'EOF',
'',
' fi',
'fi',
'cat > /etc/resolv.conf <<EOF',
dns,
'EOF',
''])
result = run_all(
name, 'tee {0}'.format(script), path=path,
stdin=DNS_SCRIPT, python_shell=True)
if result['retcode'] == 0:
result = run_all(
name, 'sh -c "chmod +x {0};{0}"'.format(script),
path=path, python_shell=True)
# blindly delete the setter file
run_all(name,
'sh -c \'if [ -f "{0}" ];then rm -f "{0}";fi\''.format(script),
path=path, python_shell=True)
if result['retcode'] != 0:
error = ('Unable to write to /etc/resolv.conf in container \'{0}\''
.format(name))
if result['stderr']:
error += ': {0}'.format(result['stderr'])
raise CommandExecutionError(error)
return True
def running_systemd(name, cache=True, path=None):
'''
Determine if systemD is running
path
path to the container parent
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.running_systemd ubuntu
'''
k = 'lxc.systemd.test.{0}{1}'.format(name, path)
ret = __context__.get(k, None)
if ret is None or not cache:
rstr = __salt__['test.random_hash']()
# no tmp here, apparmor won't let us execute !
script = '/sbin/{0}_testsystemd.sh'.format(rstr)
# ubuntu already had since trusty some bits of systemd but was
# still using upstart ...
# we need to be a bit more careful that just testing that systemd
# is present
_script = textwrap.dedent(
'''\
#!/usr/bin/env bash
set -x
if ! command -v systemctl 1>/dev/null 2>/dev/null;then exit 2;fi
for i in \\
/run/systemd/journal/dev-log\\
/run/systemd/journal/flushed\\
/run/systemd/journal/kernel-seqnum\\
/run/systemd/journal/socket\\
/run/systemd/journal/stdout\\
/var/run/systemd/journal/dev-log\\
/var/run/systemd/journal/flushed\\
/var/run/systemd/journal/kernel-seqnum\\
/var/run/systemd/journal/socket\\
/var/run/systemd/journal/stdout\\
;do\\
if test -e ${i};then exit 0;fi
done
if test -d /var/systemd/system;then exit 0;fi
exit 2
''')
result = run_all(
name, 'tee {0}'.format(script), path=path,
stdin=_script, python_shell=True)
if result['retcode'] == 0:
result = run_all(name,
'sh -c "chmod +x {0};{0}"'''.format(script),
path=path,
python_shell=True)
else:
raise CommandExecutionError(
'lxc {0} failed to copy initd tester'.format(name))
run_all(name,
'sh -c \'if [ -f "{0}" ];then rm -f "{0}";fi\''
''.format(script),
path=path,
ignore_retcode=True,
python_shell=True)
if result['retcode'] != 0:
error = ('Unable to determine if the container \'{0}\''
' was running systemd, assmuming it is not.'
''.format(name))
if result['stderr']:
error += ': {0}'.format(result['stderr'])
# only cache result if we got a known exit code
if result['retcode'] in (0, 2):
__context__[k] = ret = not result['retcode']
return ret
def systemd_running_state(name, path=None):
'''
Get the operational state of a systemd based container
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.systemd_running_state ubuntu
'''
try:
ret = run_all(name,
'systemctl is-system-running',
path=path,
ignore_retcode=True)['stdout']
except CommandExecutionError:
ret = ''
return ret
def test_sd_started_state(name, path=None):
'''
Test if a systemd container is fully started
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.test_sd_started_state ubuntu
'''
qstate = systemd_running_state(name, path=path)
if qstate in ('initializing', 'starting'):
return False
elif qstate == '':
return None
else:
return True
def test_bare_started_state(name, path=None):
'''
Test if a non systemd container is fully started
For now, it consists only to test if the container is attachable
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.test_bare_started_state ubuntu
'''
try:
ret = run_all(
name, 'ls', path=path, ignore_retcode=True
)['retcode'] == 0
except (CommandExecutionError,):
ret = None
return ret
def wait_started(name, path=None, timeout=300):
'''
Check that the system has fully inited
This is actually very important for systemD based containers
see https://github.com/saltstack/salt/issues/23847
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.wait_started ubuntu
'''
if not exists(name, path=path):
raise CommandExecutionError(
'Container {0} does does exists'.format(name))
if not state(name, path=path) == 'running':
raise CommandExecutionError(
'Container {0} is not running'.format(name))
ret = False
if running_systemd(name, path=path):
test_started = test_sd_started_state
logger = log.error
else:
test_started = test_bare_started_state
logger = log.debug
now = time.time()
expire = now + timeout
now = time.time()
started = test_started(name, path=path)
while time.time() < expire and not started:
time.sleep(0.3)
started = test_started(name, path=path)
if started is None:
logger(
'Assuming %s is started, although we failed to detect that'
' is fully started correctly', name)
ret = True
else:
ret = started
return ret
def _needs_install(name, path=None):
ret = 0
has_minion = retcode(name,
'which salt-minion',
path=path,
ignore_retcode=True)
# we assume that installing is when no minion is running
# but testing the executable presence is not enougth for custom
# installs where the bootstrap can do much more than installing
# the bare salt binaries.
if has_minion:
processes = run_stdout(name, "ps aux", path=path)
if 'salt-minion' not in processes:
ret = 1
else:
retcode(name, 'salt-call --local service.stop salt-minion')
else:
ret = 1
return ret
def bootstrap(name,
config=None,
approve_key=True,
install=True,
pub_key=None,
priv_key=None,
bootstrap_url=None,
force_install=False,
unconditional_install=False,
path=None,
bootstrap_delay=None,
bootstrap_args=None,
bootstrap_shell=None):
'''
Install and configure salt in a container.
config
Minion configuration options. By default, the ``master`` option is set
to the target host's master.
approve_key
Request a pre-approval of the generated minion key. Requires
that the salt-master be configured to either auto-accept all keys or
expect a signing request from the target host. Default: ``True``
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
pub_key
Explicit public key to pressed the minion with (optional).
This can be either a filepath or a string representing the key
priv_key
Explicit private key to pressed the minion with (optional).
This can be either a filepath or a string representing the key
bootstrap_delay
Delay in seconds between end of container creation and bootstrapping.
Useful when waiting for container to obtain a DHCP lease.
.. versionadded:: 2015.5.0
bootstrap_url
url, content or filepath to the salt bootstrap script
bootstrap_args
salt bootstrap script arguments
bootstrap_shell
shell to execute the script into
install
Whether to attempt a full installation of salt-minion if needed.
force_install
Force installation even if salt-minion is detected,
this is the way to run vendor bootstrap scripts even
if a salt minion is already present in the container
unconditional_install
Run the script even if the container seems seeded
CLI Examples:
.. code-block:: bash
salt 'minion' lxc.bootstrap container_name [config=config_data] \\
[approve_key=(True|False)] [install=(True|False)]
'''
wait_started(name, path=path)
if bootstrap_delay is not None:
try:
log.info('LXC %s: bootstrap_delay: %s', name, bootstrap_delay)
time.sleep(bootstrap_delay)
except TypeError:
# Bad input, but assume since a value was passed that
# a delay was desired, and sleep for 5 seconds
time.sleep(5)
c_info = info(name, path=path)
if not c_info:
return None
# default set here as we cannot set them
# in def as it can come from a chain of procedures.
if bootstrap_args:
# custom bootstrap args can be totally customized, and user could
# have inserted the placeholder for the config directory.
# For example, some salt bootstrap script do not use at all -c
if '{0}' not in bootstrap_args:
bootstrap_args += ' -c {0}'
else:
bootstrap_args = '-c {0}'
if not bootstrap_shell:
bootstrap_shell = 'sh'
orig_state = _ensure_running(name, path=path)
if not orig_state:
return orig_state
if not force_install:
needs_install = _needs_install(name, path=path)
else:
needs_install = True
seeded = retcode(name,
'test -e \'{0}\''.format(SEED_MARKER),
path=path,
chroot_fallback=True,
ignore_retcode=True) == 0
tmp = tempfile.mkdtemp()
if seeded and not unconditional_install:
ret = True
else:
ret = False
cfg_files = __salt__['seed.mkconfig'](
config, tmp=tmp, id_=name, approve_key=approve_key,
pub_key=pub_key, priv_key=priv_key)
if needs_install or force_install or unconditional_install:
if install:
rstr = __salt__['test.random_hash']()
configdir = '/var/tmp/.c_{0}'.format(rstr)
cmd = 'install -m 0700 -d {0}'.format(configdir)
if run_all(
name, cmd, path=path, python_shell=False
)['retcode'] != 0:
log.error('tmpdir %s creation failed %s', configdir, cmd)
return False
bs_ = __salt__['config.gather_bootstrap_script'](
bootstrap=bootstrap_url)
script = '/sbin/{0}_bootstrap.sh'.format(rstr)
copy_to(name, bs_, script, path=path)
result = run_all(name,
'sh -c "chmod +x {0}"'.format(script),
path=path,
python_shell=True)
copy_to(name, cfg_files['config'],
os.path.join(configdir, 'minion'),
path=path)
copy_to(name, cfg_files['privkey'],
os.path.join(configdir, 'minion.pem'),
path=path)
copy_to(name, cfg_files['pubkey'],
os.path.join(configdir, 'minion.pub'),
path=path)
bootstrap_args = bootstrap_args.format(configdir)
cmd = ('{0} {2} {1}'
.format(bootstrap_shell,
bootstrap_args.replace("'", "''"),
script))
# log ASAP the forged bootstrap command which can be wrapped
# out of the output in case of unexpected problem
log.info('Running %s in LXC container \'%s\'', cmd, name)
ret = retcode(name, cmd, output_loglevel='info',
path=path, use_vt=True) == 0
run_all(name,
'sh -c \'if [ -f "{0}" ];then rm -f "{0}";fi\''
''.format(script),
path=path,
ignore_retcode=True,
python_shell=True)
else:
ret = False
else:
minion_config = salt.config.minion_config(cfg_files['config'])
pki_dir = minion_config['pki_dir']
copy_to(name,
cfg_files['config'],
'/etc/salt/minion',
path=path)
copy_to(name,
cfg_files['privkey'],
os.path.join(pki_dir, 'minion.pem'),
path=path)
copy_to(name,
cfg_files['pubkey'],
os.path.join(pki_dir, 'minion.pub'),
path=path)
run(name,
'salt-call --local service.enable salt-minion',
path=path,
python_shell=False)
ret = True
shutil.rmtree(tmp)
if orig_state == 'stopped':
stop(name, path=path)
elif orig_state == 'frozen':
freeze(name, path=path)
# mark seeded upon successful install
if ret:
run(name,
'touch \'{0}\''.format(SEED_MARKER),
path=path,
python_shell=False)
return ret
def attachable(name, path=None):
'''
Return True if the named container can be attached to via the lxc-attach
command
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt 'minion' lxc.attachable ubuntu
'''
cachekey = 'lxc.attachable{0}{1}'.format(name, path)
try:
return __context__[cachekey]
except KeyError:
_ensure_exists(name, path=path)
# Can't use run() here because it uses attachable() and would
# endlessly recurse, resulting in a traceback
log.debug('Checking if LXC container %s is attachable', name)
cmd = 'lxc-attach'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' --clear-env -n {0} -- /usr/bin/env'.format(name)
result = __salt__['cmd.retcode'](cmd,
python_shell=False,
output_loglevel='quiet',
ignore_retcode=True) == 0
__context__[cachekey] = result
return __context__[cachekey]
def _run(name,
cmd,
output=None,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=None,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
Common logic for lxc.run functions
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
'''
orig_state = state(name, path=path)
try:
if attachable(name, path=path):
ret = __salt__['container_resource.run'](
name,
cmd,
path=path,
container_type=__virtualname__,
exec_driver=EXEC_DRIVER,
output=output,
no_start=no_start,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
ignore_retcode=ignore_retcode,
use_vt=use_vt,
keep_env=keep_env)
else:
if not chroot_fallback:
raise CommandExecutionError(
'{0} is not attachable.'.format(name))
rootfs = info(name, path=path).get('rootfs')
# Set context var to make cmd.run_chroot run cmd.run instead of
# cmd.run_all.
__context__['cmd.run_chroot.func'] = __salt__['cmd.run']
ret = __salt__['cmd.run_chroot'](rootfs,
cmd,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
ignore_retcode=ignore_retcode)
except Exception:
raise
finally:
# Make sure we honor preserve_state, even if there was an exception
new_state = state(name, path=path)
if preserve_state:
if orig_state == 'stopped' and new_state != 'stopped':
stop(name, path=path)
elif orig_state == 'frozen' and new_state != 'frozen':
freeze(name, start=True, path=path)
if output in (None, 'all'):
return ret
else:
return ret[output]
def run(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.8.0
Run :mod:`cmd.run <salt.modules.cmdmod.run>` within a container
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed in stderr if the command being run
does not exist. If no output is returned using this function, try using
:mod:`lxc.run_stderr <salt.modules.lxc.run_stderr>` or
:mod:`lxc.run_all <salt.modules.lxc.run_all>`.
name
Name of the container in which to run the command
cmd
Command to run
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console. Assumes
``output=all``.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
CLI Example:
.. code-block:: bash
salt myminion lxc.run mycontainer 'ifconfig -a'
'''
return _run(name,
cmd,
path=path,
output=None,
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def run_stdout(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.5.0
Run :mod:`cmd.run_stdout <salt.modules.cmdmod.run_stdout>` within a container
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed in stderr if the command being run
does not exist. If no output is returned using this function, try using
:mod:`lxc.run_stderr <salt.modules.lxc.run_stderr>` or
:mod:`lxc.run_all <salt.modules.lxc.run_all>`.
name
Name of the container in which to run the command
cmd
Command to run
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console
``output=all``.
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
CLI Example:
.. code-block:: bash
salt myminion lxc.run_stdout mycontainer 'ifconfig -a'
'''
return _run(name,
cmd,
path=path,
output='stdout',
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def run_stderr(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.5.0
Run :mod:`cmd.run_stderr <salt.modules.cmdmod.run_stderr>` within a container
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed if the command being run does not
exist.
name
Name of the container in which to run the command
cmd
Command to run
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console
``output=all``.
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
CLI Example:
.. code-block:: bash
salt myminion lxc.run_stderr mycontainer 'ip addr show'
'''
return _run(name,
cmd,
path=path,
output='stderr',
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def retcode(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.5.0
Run :mod:`cmd.retcode <salt.modules.cmdmod.retcode>` within a container
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed in stderr if the command being run
does not exist. If the retcode is nonzero and not what was expected,
try using :mod:`lxc.run_stderr <salt.modules.lxc.run_stderr>`
or :mod:`lxc.run_all <salt.modules.lxc.run_all>`.
name
Name of the container in which to run the command
cmd
Command to run
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console
``output=all``.
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
CLI Example:
.. code-block:: bash
salt myminion lxc.retcode mycontainer 'ip addr show'
'''
return _run(name,
cmd,
output='retcode',
path=path,
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def run_all(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.5.0
Run :mod:`cmd.run_all <salt.modules.cmdmod.run_all>` within a container
.. note::
While the command is run within the container, it is initiated from the
host. Therefore, the PID in the return dict is from the host, not from
the container.
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed in stderr if the command being run
does not exist.
name
Name of the container in which to run the command
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
cmd
Command to run
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console
``output=all``.
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
CLI Example:
.. code-block:: bash
salt myminion lxc.run_all mycontainer 'ip addr show'
'''
return _run(name,
cmd,
output='all',
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
path=path,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def _get_md5(name, path):
'''
Get the MD5 checksum of a file from a container
'''
output = run_stdout(name, 'md5sum "{0}"'.format(path),
chroot_fallback=True,
ignore_retcode=True)
try:
return output.split()[0]
except IndexError:
# Destination file does not exist or could not be accessed
return None
def copy_to(name, source, dest, overwrite=False, makedirs=False, path=None):
'''
.. versionchanged:: 2015.8.0
Function renamed from ``lxc.cp`` to ``lxc.copy_to`` for consistency
with other container types. ``lxc.cp`` will continue to work, however.
For versions 2015.2.x and earlier, use ``lxc.cp``.
Copy a file or directory from the host into a container
name
Container name
source
File to be copied to the container
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
dest
Destination on the container. Must be an absolute path.
.. versionchanged:: 2015.5.0
If the destination is a directory, the file will be copied into
that directory.
overwrite : False
Unless this option is set to ``True``, then if a file exists at the
location specified by the ``dest`` argument, an error will be raised.
.. versionadded:: 2015.8.0
makedirs : False
Create the parent directory on the container if it does not already
exist.
.. versionadded:: 2015.5.0
CLI Example:
.. code-block:: bash
salt 'minion' lxc.copy_to /tmp/foo /root/foo
salt 'minion' lxc.cp /tmp/foo /root/foo
'''
_ensure_running(name, no_start=True, path=path)
return __salt__['container_resource.copy_to'](
name,
source,
dest,
container_type=__virtualname__,
path=path,
exec_driver=EXEC_DRIVER,
overwrite=overwrite,
makedirs=makedirs)
cp = salt.utils.functools.alias_function(copy_to, 'cp')
def read_conf(conf_file, out_format='simple'):
'''
Read in an LXC configuration file. By default returns a simple, unsorted
dict, but can also return a more detailed structure including blank lines
and comments.
out_format:
set to 'simple' if you need the old and unsupported behavior.
This won't support the multiple lxc values (eg: multiple network nics)
CLI Examples:
.. code-block:: bash
salt 'minion' lxc.read_conf /etc/lxc/mycontainer.conf
salt 'minion' lxc.read_conf /etc/lxc/mycontainer.conf out_format=commented
'''
ret_commented = []
ret_simple = {}
with salt.utils.files.fopen(conf_file, 'r') as fp_:
for line in salt.utils.data.decode(fp_.readlines()):
if '=' not in line:
ret_commented.append(line)
continue
comps = line.split('=')
value = '='.join(comps[1:]).strip()
comment = None
if value.strip().startswith('#'):
vcomps = value.strip().split('#')
value = vcomps[1].strip()
comment = '#'.join(vcomps[1:]).strip()
ret_commented.append({comps[0].strip(): {
'value': value,
'comment': comment,
}})
else:
ret_commented.append({comps[0].strip(): value})
ret_simple[comps[0].strip()] = value
if out_format == 'simple':
return ret_simple
return ret_commented
def write_conf(conf_file, conf):
'''
Write out an LXC configuration file
This is normally only used internally. The format of the data structure
must match that which is returned from ``lxc.read_conf()``, with
``out_format`` set to ``commented``.
An example might look like:
.. code-block:: python
[
{'lxc.utsname': '$CONTAINER_NAME'},
'# This is a commented line\\n',
'\\n',
{'lxc.mount': '$CONTAINER_FSTAB'},
{'lxc.rootfs': {'comment': 'This is another test',
'value': 'This is another test'}},
'\\n',
{'lxc.network.type': 'veth'},
{'lxc.network.flags': 'up'},
{'lxc.network.link': 'br0'},
{'lxc.network.mac': '$CONTAINER_MACADDR'},
{'lxc.network.ipv4': '$CONTAINER_IPADDR'},
{'lxc.network.name': '$CONTAINER_DEVICENAME'},
]
CLI Example:
.. code-block:: bash
salt 'minion' lxc.write_conf /etc/lxc/mycontainer.conf \\
out_format=commented
'''
if not isinstance(conf, list):
raise SaltInvocationError('Configuration must be passed as a list')
# construct the content prior to write to the file
# to avoid half written configs
content = ''
for line in conf:
if isinstance(line, (six.text_type, six.string_types)):
content += line
elif isinstance(line, dict):
for key in list(line.keys()):
out_line = None
if isinstance(
line[key],
(six.text_type, six.string_types, six.integer_types, float)
):
out_line = ' = '.join((key, "{0}".format(line[key])))
elif isinstance(line[key], dict):
out_line = ' = '.join((key, line[key]['value']))
if 'comment' in line[key]:
out_line = ' # '.join((out_line, line[key]['comment']))
if out_line:
content += out_line
content += '\n'
with salt.utils.files.fopen(conf_file, 'w') as fp_:
fp_.write(salt.utils.stringutils.to_str(content))
return {}
def edit_conf(conf_file,
out_format='simple',
read_only=False,
lxc_config=None,
**kwargs):
'''
Edit an LXC configuration file. If a setting is already present inside the
file, its value will be replaced. If it does not exist, it will be appended
to the end of the file. Comments and blank lines will be kept in-tact if
they already exist in the file.
out_format:
Set to simple if you need backward compatibility (multiple items for a
simple key is not supported)
read_only:
return only the edited configuration without applying it
to the underlying lxc configuration file
lxc_config:
List of dict containning lxc configuration items
For network configuration, you also need to add the device it belongs
to, otherwise it will default to eth0.
Also, any change to a network parameter will result in the whole
network reconfiguration to avoid mismatchs, be aware of that !
After the file is edited, its contents will be returned. By default, it
will be returned in ``simple`` format, meaning an unordered dict (which
may not represent the actual file order). Passing in an ``out_format`` of
``commented`` will return a data structure which accurately represents the
order and content of the file.
CLI Example:
.. code-block:: bash
salt 'minion' lxc.edit_conf /etc/lxc/mycontainer.conf \\
out_format=commented lxc.network.type=veth
salt 'minion' lxc.edit_conf /etc/lxc/mycontainer.conf \\
out_format=commented \\
lxc_config="[{'lxc.network.name': 'eth0', \\
'lxc.network.ipv4': '1.2.3.4'},
{'lxc.network.name': 'eth2', \\
'lxc.network.ipv4': '1.2.3.5',\\
'lxc.network.gateway': '1.2.3.1'}]"
'''
data = []
try:
conf = read_conf(conf_file, out_format=out_format)
except Exception:
conf = []
if not lxc_config:
lxc_config = []
lxc_config = copy.deepcopy(lxc_config)
# search if we want to access net config
# in that case, we will replace all the net configuration
net_config = []
for lxc_kws in lxc_config + [kwargs]:
net_params = {}
for kwarg in [a for a in lxc_kws]:
if kwarg.startswith('__'):
continue
if kwarg.startswith('lxc.network.'):
net_params[kwarg] = lxc_kws[kwarg]
lxc_kws.pop(kwarg, None)
if net_params:
net_config.append(net_params)
nic_opts = salt.utils.odict.OrderedDict()
for params in net_config:
dev = params.get('lxc.network.name', DEFAULT_NIC)
dev_opts = nic_opts.setdefault(dev, salt.utils.odict.OrderedDict())
for param in params:
opt = param.replace('lxc.network.', '')
opt = {'hwaddr': 'mac'}.get(opt, opt)
dev_opts[opt] = params[param]
net_changes = []
if nic_opts:
net_changes = _config_list(conf, only_net=True,
**{'network_profile': DEFAULT_NIC,
'nic_opts': nic_opts})
if net_changes:
lxc_config.extend(net_changes)
for line in conf:
if not isinstance(line, dict):
data.append(line)
continue
else:
for key in list(line.keys()):
val = line[key]
if net_changes and key.startswith('lxc.network.'):
continue
found = False
for ix in range(len(lxc_config)):
kw = lxc_config[ix]
if key in kw:
found = True
data.append({key: kw[key]})
del kw[key]
if not found:
data.append({key: val})
for lxc_kws in lxc_config:
for kwarg in lxc_kws:
data.append({kwarg: lxc_kws[kwarg]})
if read_only:
return data
write_conf(conf_file, data)
return read_conf(conf_file, out_format)
def reboot(name, path=None):
'''
Reboot a container.
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Examples:
.. code-block:: bash
salt 'minion' lxc.reboot myvm
'''
ret = {'result': True,
'changes': {},
'comment': '{0} rebooted'.format(name)}
does_exist = exists(name, path=path)
if does_exist and (state(name, path=path) == 'running'):
try:
stop(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
ret['result'] = False
return ret
if does_exist and (state(name, path=path) != 'running'):
try:
start(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
ret['result'] = False
return ret
ret['changes'][name] = 'rebooted'
return ret
def reconfigure(name,
cpu=None,
cpuset=None,
cpushare=None,
memory=None,
profile=None,
network_profile=None,
nic_opts=None,
bridge=None,
gateway=None,
autostart=None,
utsname=None,
rootfs=None,
path=None,
**kwargs):
'''
Reconfigure a container.
This only applies to a few property
name
Name of the container.
utsname
utsname of the container.
.. versionadded:: 2016.3.0
rootfs
rootfs of the container.
.. versionadded:: 2016.3.0
cpu
Select a random number of cpu cores and assign it to the cpuset, if the
cpuset option is set then this option will be ignored
cpuset
Explicitly define the cpus this container will be bound to
cpushare
cgroups cpu shares.
autostart
autostart container on reboot
memory
cgroups memory limit, in MB.
(0 for nolimit, None for old default 1024MB)
gateway
the ipv4 gateway to use
the default does nothing more than lxcutils does
bridge
the bridge to use
the default does nothing more than lxcutils does
nic
Network interfaces profile (defined in config or pillar).
nic_opts
Extra options for network interfaces, will override
``{"eth0": {"mac": "aa:bb:cc:dd:ee:ff", "ipv4": "10.1.1.1", "ipv6": "2001:db8::ff00:42:8329"}}``
or
``{"eth0": {"mac": "aa:bb:cc:dd:ee:ff", "ipv4": "10.1.1.1/24", "ipv6": "2001:db8::ff00:42:8329"}}``
path
path to the container parent
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt-call -lall mc_lxc_fork.reconfigure foobar nic_opts="{'eth1': {'mac': '00:16:3e:dd:ee:44'}}" memory=4
'''
changes = {}
cpath = get_root_path(path)
path = os.path.join(cpath, name, 'config')
ret = {'name': name,
'comment': 'config for {0} up to date'.format(name),
'result': True,
'changes': changes}
profile = get_container_profile(copy.deepcopy(profile))
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, _marker)
profile_match = profile.pop(key, default)
# let kwarg overrides be the preferred choice
if kw_overrides_match is _marker:
return profile_match
return kw_overrides_match
if nic_opts is not None and not network_profile:
network_profile = DEFAULT_NIC
if autostart is not None:
autostart = select('autostart', autostart)
else:
autostart = 'keep'
if not utsname:
utsname = select('utsname', utsname)
if os.path.exists(path):
old_chunks = read_conf(path, out_format='commented')
make_kw = salt.utils.odict.OrderedDict([
('utsname', utsname),
('rootfs', rootfs),
('autostart', autostart),
('cpu', cpu),
('gateway', gateway),
('cpuset', cpuset),
('cpushare', cpushare),
('network_profile', network_profile),
('nic_opts', nic_opts),
('bridge', bridge)])
# match 0 and none as memory = 0 in lxc config is harmful
if memory:
make_kw['memory'] = memory
kw = salt.utils.odict.OrderedDict()
for key, val in six.iteritems(make_kw):
if val is not None:
kw[key] = val
new_cfg = _config_list(conf_tuples=old_chunks, **kw)
if new_cfg:
edit_conf(path, out_format='commented', lxc_config=new_cfg)
chunks = read_conf(path, out_format='commented')
if old_chunks != chunks:
ret['comment'] = '{0} lxc config updated'.format(name)
if state(name, path=path) == 'running':
cret = reboot(name, path=path)
ret['result'] = cret['result']
return ret
def apply_network_profile(name, network_profile, nic_opts=None, path=None):
'''
.. versionadded:: 2015.5.0
Apply a network profile to a container
network_profile
profile name or default values (dict)
nic_opts
values to override in defaults (dict)
indexed by nic card names
path
path to the container parent
.. versionadded:: 2015.8.0
CLI Examples:
.. code-block:: bash
salt 'minion' lxc.apply_network_profile web1 centos
salt 'minion' lxc.apply_network_profile web1 centos \\
nic_opts="{'eth0': {'mac': 'xx:xx:xx:xx:xx:xx'}}"
salt 'minion' lxc.apply_network_profile web1 \\
"{'eth0': {'mac': 'xx:xx:xx:xx:xx:yy'}}"
nic_opts="{'eth0': {'mac': 'xx:xx:xx:xx:xx:xx'}}"
The special case to disable use of ethernet nics:
.. code-block:: bash
salt 'minion' lxc.apply_network_profile web1 centos \\
"{eth0: {disable: true}}"
'''
cpath = get_root_path(path)
cfgpath = os.path.join(cpath, name, 'config')
before = []
with salt.utils.files.fopen(cfgpath, 'r') as fp_:
for line in fp_:
before.append(line)
lxcconfig = _LXCConfig(name=name, path=path)
old_net = lxcconfig._filter_data('lxc.network')
network_params = {}
for param in _network_conf(
conf_tuples=old_net,
network_profile=network_profile, nic_opts=nic_opts
):
network_params.update(param)
if network_params:
edit_conf(cfgpath, out_format='commented', **network_params)
after = []
with salt.utils.files.fopen(cfgpath, 'r') as fp_:
for line in fp_:
after.append(line)
diff = ''
for line in difflib.unified_diff(before,
after,
fromfile='before',
tofile='after'):
diff += line
return diff
def get_pid(name, path=None):
'''
Returns a container pid.
Throw an exception if the container isn't running.
CLI Example:
.. code-block:: bash
salt '*' lxc.get_pid name
'''
if name not in list_(limit='running', path=path):
raise CommandExecutionError('Container {0} is not running, can\'t determine PID'.format(name))
info = __salt__['cmd.run']('lxc-info -n {0}'.format(name)).split("\n")
pid = [line.split(':')[1].strip() for line in info if re.match(r'\s*PID', line)][0]
return pid
def add_veth(name, interface_name, bridge=None, path=None):
'''
Add a veth to a container.
Note : this function doesn't update the container config, just add the interface at runtime
name
Name of the container
interface_name
Name of the interface in the container
bridge
Name of the bridge to attach the interface to (facultative)
CLI Examples:
.. code-block:: bash
salt '*' lxc.add_veth container_name eth1 br1
salt '*' lxc.add_veth container_name eth1
'''
# Get container init PID
pid = get_pid(name, path=path)
# Generate a ramdom string for veth and ensure that is isn't present on the system
while True:
random_veth = 'veth'+''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(6))
if random_veth not in __salt__['network.interfaces']().keys():
break
# Check prerequisites
if not __salt__['file.directory_exists']('/var/run/'):
raise CommandExecutionError('Directory /var/run required for lxc.add_veth doesn\'t exists')
if not __salt__['file.file_exists']('/proc/{0}/ns/net'.format(pid)):
raise CommandExecutionError('Proc file for container {0} network namespace doesn\'t exists'.format(name))
if not __salt__['file.directory_exists']('/var/run/netns'):
__salt__['file.mkdir']('/var/run/netns')
# Ensure that the symlink is up to date (change on container restart)
if __salt__['file.is_link']('/var/run/netns/{0}'.format(name)):
__salt__['file.remove']('/var/run/netns/{0}'.format(name))
__salt__['file.symlink']('/proc/{0}/ns/net'.format(pid), '/var/run/netns/{0}'.format(name))
# Ensure that interface doesn't exists
interface_exists = 0 == __salt__['cmd.retcode']('ip netns exec {netns} ip address list {interface}'.format(
netns=name,
interface=interface_name
))
if interface_exists:
raise CommandExecutionError('Interface {interface} already exists in {container}'.format(
interface=interface_name,
container=name
))
# Create veth and bring it up
if __salt__['cmd.retcode']('ip link add name {veth} type veth peer name {veth}_c'.format(veth=random_veth)) != 0:
raise CommandExecutionError('Error while creating the veth pair {0}'.format(random_veth))
if __salt__['cmd.retcode']('ip link set dev {0} up'.format(random_veth)) != 0:
raise CommandExecutionError('Error while bringing up host-side veth {0}'.format(random_veth))
# Attach it to the container
attached = 0 == __salt__['cmd.retcode']('ip link set dev {veth}_c netns {container} name {interface_name}'.format(
veth=random_veth,
container=name,
interface_name=interface_name
))
if not attached:
raise CommandExecutionError('Error while attaching the veth {veth} to container {container}'.format(
veth=random_veth,
container=name
))
__salt__['file.remove']('/var/run/netns/{0}'.format(name))
if bridge is not None:
__salt__['bridge.addif'](bridge, random_veth)
|
saltstack/salt
|
salt/modules/lxc.py
|
exists
|
python
|
def exists(name, path=None):
'''
Returns whether the named container exists.
path
path to the container parent directory (default: /var/lib/lxc)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.exists name
'''
_exists = name in ls_(path=path)
# container may be just created but we did cached earlier the
# lxc-ls results
if not _exists:
_exists = name in ls_(cache=False, path=path)
return _exists
|
Returns whether the named container exists.
path
path to the container parent directory (default: /var/lib/lxc)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.exists name
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/lxc.py#L2607-L2629
|
[
"def ls_(active=None, cache=True, path=None):\n '''\n Return a list of the containers available on the minion\n\n path\n path to the container parent directory\n default: /var/lib/lxc (system)\n\n .. versionadded:: 2015.8.0\n\n active\n If ``True``, return only active (i.e. running) containers\n\n .. versionadded:: 2015.5.0\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' lxc.ls\n salt '*' lxc.ls active=True\n '''\n contextvar = 'lxc.ls{0}'.format(path)\n if active:\n contextvar += '.active'\n if cache and (contextvar in __context__):\n return __context__[contextvar]\n else:\n ret = []\n cmd = 'lxc-ls'\n if path:\n cmd += ' -P {0}'.format(pipes.quote(path))\n if active:\n cmd += ' --active'\n output = __salt__['cmd.run_stdout'](cmd, python_shell=False)\n for line in output.splitlines():\n ret.extend(line.split())\n __context__[contextvar] = ret\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Control Linux Containers via Salt
:depends: lxc package for distribution
lxc >= 1.0 (even beta alpha) is required
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import datetime
import copy
import string
import textwrap
import difflib
import logging
import tempfile
import os
import pipes
import time
import shutil
import re
import random
# Import salt libs
import salt.utils.args
import salt.utils.cloud
import salt.utils.data
import salt.utils.dictupdate
import salt.utils.files
import salt.utils.functools
import salt.utils.hashutils
import salt.utils.network
import salt.utils.odict
import salt.utils.path
import salt.utils.stringutils
from salt.exceptions import CommandExecutionError, SaltInvocationError
import salt.config
from salt.utils.versions import LooseVersion as _LooseVersion
# Import 3rd-party libs
from salt.ext import six
# pylint: disable=import-error,no-name-in-module
from salt.ext.six.moves import range # pylint: disable=redefined-builtin
from salt.ext.six.moves.urllib.parse import urlparse as _urlparse
# pylint: enable=import-error,no-name-in-module
# Set up logging
log = logging.getLogger(__name__)
# Don't shadow built-in's.
__func_alias__ = {
'list_': 'list',
'ls_': 'ls'
}
__virtualname__ = 'lxc'
DEFAULT_NIC = 'eth0'
DEFAULT_BR = 'br0'
SEED_MARKER = '/lxc.initial_seed'
EXEC_DRIVER = 'lxc-attach'
DEFAULT_PATH = '/var/lib/lxc'
_marker = object()
def __virtual__():
if salt.utils.path.which('lxc-start'):
return __virtualname__
# To speed up the whole thing, we decided to not use the
# subshell way and assume things are in place for lxc
# Discussion made by @kiorky and @thatch45
# lxc-version presence is not sufficient, in lxc1.0 alpha
# (precise backports), we have it and it is sufficient
# for the module to execute.
# elif salt.utils.path.which('lxc-version'):
# passed = False
# try:
# passed = subprocess.check_output(
# 'lxc-version').split(':')[1].strip() >= '1.0'
# except Exception:
# pass
# if not passed:
# log.warning('Support for lxc < 1.0 may be incomplete.')
# return 'lxc'
# return False
#
return (False, 'The lxc execution module cannot be loaded: the lxc-start binary is not in the path.')
def get_root_path(path):
'''
Get the configured lxc root for containers
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.get_root_path
'''
if not path:
path = __opts__.get('lxc.root_path', DEFAULT_PATH)
return path
def version():
'''
Return the actual lxc client version
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.version
'''
k = 'lxc.version'
if not __context__.get(k, None):
cversion = __salt__['cmd.run_all']('lxc-info --version')
if not cversion['retcode']:
ver = _LooseVersion(cversion['stdout'])
if ver < _LooseVersion('1.0'):
raise CommandExecutionError('LXC should be at least 1.0')
__context__[k] = "{0}".format(ver)
return __context__.get(k, None)
def _clear_context():
'''
Clear any lxc variables set in __context__
'''
for var in [x for x in __context__ if x.startswith('lxc.')]:
log.trace('Clearing __context__[\'%s\']', var)
__context__.pop(var, None)
def _ip_sort(ip):
'''Ip sorting'''
idx = '001'
if ip == '127.0.0.1':
idx = '200'
if ip == '::1':
idx = '201'
elif '::' in ip:
idx = '100'
return '{0}___{1}'.format(idx, ip)
def search_lxc_bridges():
'''
Search which bridges are potentially available as LXC bridges
CLI Example:
.. code-block:: bash
salt '*' lxc.search_lxc_bridges
'''
bridges = __context__.get('lxc.bridges', None)
# either match not yet called or no bridges were found
# to handle the case where lxc was not installed on the first
# call
if not bridges:
bridges = set()
running_bridges = set()
bridges.add(DEFAULT_BR)
try:
output = __salt__['cmd.run_all']('brctl show')
for line in output['stdout'].splitlines()[1:]:
if not line.startswith(' '):
running_bridges.add(line.split()[0].strip())
except (SaltInvocationError, CommandExecutionError):
pass
for ifc, ip in six.iteritems(
__grains__.get('ip_interfaces', {})
):
if ifc in running_bridges:
bridges.add(ifc)
elif os.path.exists(
'/sys/devices/virtual/net/{0}/bridge'.format(ifc)
):
bridges.add(ifc)
bridges = list(bridges)
# if we found interfaces that have lxc in their names
# we filter them as being the potential lxc bridges
# we also try to default on br0 on other cases
def sort_bridges(a):
pref = 'z'
if 'lxc' in a:
pref = 'a'
elif 'br0' == a:
pref = 'c'
return '{0}_{1}'.format(pref, a)
bridges.sort(key=sort_bridges)
__context__['lxc.bridges'] = bridges
return bridges
def search_lxc_bridge():
'''
Search the first bridge which is potentially available as LXC bridge
CLI Example:
.. code-block:: bash
salt '*' lxc.search_lxc_bridge
'''
return search_lxc_bridges()[0]
def _get_salt_config(config, **kwargs):
if not config:
config = kwargs.get('minion', {})
if not config:
config = {}
config.setdefault('master',
kwargs.get('master',
__opts__.get('master',
__opts__['id'])))
config.setdefault(
'master_port',
kwargs.get('master_port',
__opts__.get('master_port',
__opts__.get('ret_port',
__opts__.get('4506')))))
if not config['master']:
config = {}
return config
def cloud_init_interface(name, vm_=None, **kwargs):
'''
Interface between salt.cloud.lxc driver and lxc.init
``vm_`` is a mapping of vm opts in the salt.cloud format
as documented for the lxc driver.
This can be used either:
- from the salt cloud driver
- because you find the argument to give easier here
than using directly lxc.init
.. warning::
BE REALLY CAREFUL CHANGING DEFAULTS !!!
IT'S A RETRO COMPATIBLE INTERFACE WITH
THE SALT CLOUD DRIVER (ask kiorky).
name
name of the lxc container to create
pub_key
public key to preseed the minion with.
Can be the keycontent or a filepath
priv_key
private key to preseed the minion with.
Can be the keycontent or a filepath
path
path to the container parent directory (default: /var/lib/lxc)
.. versionadded:: 2015.8.0
profile
:ref:`profile <tutorial-lxc-profiles-container>` selection
network_profile
:ref:`network profile <tutorial-lxc-profiles-network>` selection
nic_opts
per interface settings compatibles with
network profile (ipv4/ipv6/link/gateway/mac/netmask)
eg::
- {'eth0': {'mac': '00:16:3e:01:29:40',
'gateway': None, (default)
'link': 'br0', (default)
'gateway': None, (default)
'netmask': '', (default)
'ip': '22.1.4.25'}}
unconditional_install
given to lxc.bootstrap (see relative doc)
force_install
given to lxc.bootstrap (see relative doc)
config
any extra argument for the salt minion config
dnsservers
list of DNS servers to set inside the container
dns_via_dhcp
do not set the dns servers, let them be set by the dhcp.
autostart
autostart the container at boot time
password
administrative password for the container
bootstrap_delay
delay before launching bootstrap script at Container init
.. warning::
Legacy but still supported options:
from_container
which container we use as a template
when running lxc.clone
image
which template do we use when we
are using lxc.create. This is the default
mode unless you specify something in from_container
backing
which backing store to use.
Values can be: overlayfs, dir(default), lvm, zfs, brtfs
fstype
When using a blockdevice level backing store,
which filesystem to use on
size
When using a blockdevice level backing store,
which size for the filesystem to use on
snapshot
Use snapshot when cloning the container source
vgname
if using LVM: vgname
lvname
if using LVM: lvname
thinpool:
if using LVM: thinpool
ip
ip for the primary nic
mac
mac address for the primary nic
netmask
netmask for the primary nic (24)
= ``vm_.get('netmask', '24')``
bridge
bridge for the primary nic (lxcbr0)
gateway
network gateway for the container
additional_ips
additional ips which will be wired on the main bridge (br0)
which is connected to internet.
Be aware that you may use manual virtual mac addresses
providen by you provider (online, ovh, etc).
This is a list of mappings {ip: '', mac: '', netmask:''}
Set gateway to None and an interface with a gateway
to escape from another interface that eth0.
eg::
- {'mac': '00:16:3e:01:29:40',
'gateway': None, (default)
'link': 'br0', (default)
'netmask': '', (default)
'ip': '22.1.4.25'}
users
administrative users for the container
default: [root] and [root, ubuntu] on ubuntu
default_nic
name of the first interface, you should
really not override this
CLI Example:
.. code-block:: bash
salt '*' lxc.cloud_init_interface foo
'''
if vm_ is None:
vm_ = {}
vm_ = copy.deepcopy(vm_)
vm_ = salt.utils.dictupdate.update(vm_, kwargs)
profile_data = copy.deepcopy(
vm_.get('lxc_profile',
vm_.get('profile', {})))
if not isinstance(profile_data, (dict, six.string_types)):
profile_data = {}
profile = get_container_profile(profile_data)
def _cloud_get(k, default=None):
return vm_.get(k, profile.get(k, default))
if name is None:
name = vm_['name']
# if we are on ubuntu, default to ubuntu
default_template = ''
if __grains__.get('os', '') in ['Ubuntu']:
default_template = 'ubuntu'
image = _cloud_get('image')
if not image:
_cloud_get('template', default_template)
backing = _cloud_get('backing', 'dir')
if image:
profile['template'] = image
vgname = _cloud_get('vgname', None)
if vgname:
profile['vgname'] = vgname
if backing:
profile['backing'] = backing
snapshot = _cloud_get('snapshot', False)
autostart = bool(_cloud_get('autostart', True))
dnsservers = _cloud_get('dnsservers', [])
dns_via_dhcp = _cloud_get('dns_via_dhcp', True)
password = _cloud_get('password', 's3cr3t')
password_encrypted = _cloud_get('password_encrypted', False)
fstype = _cloud_get('fstype', None)
lvname = _cloud_get('lvname', None)
thinpool = _cloud_get('thinpool', None)
pub_key = _cloud_get('pub_key', None)
priv_key = _cloud_get('priv_key', None)
size = _cloud_get('size', '20G')
script = _cloud_get('script', None)
script_args = _cloud_get('script_args', None)
users = _cloud_get('users', None)
if users is None:
users = []
ssh_username = _cloud_get('ssh_username', None)
if ssh_username and (ssh_username not in users):
users.append(ssh_username)
network_profile = _cloud_get('network_profile', None)
nic_opts = kwargs.get('nic_opts', None)
netmask = _cloud_get('netmask', '24')
path = _cloud_get('path', None)
bridge = _cloud_get('bridge', None)
gateway = _cloud_get('gateway', None)
unconditional_install = _cloud_get('unconditional_install', False)
force_install = _cloud_get('force_install', True)
config = _get_salt_config(_cloud_get('config', {}), **vm_)
default_nic = _cloud_get('default_nic', DEFAULT_NIC)
# do the interface with lxc.init mainly via nic_opts
# to avoid extra and confusing extra use cases.
if not isinstance(nic_opts, dict):
nic_opts = salt.utils.odict.OrderedDict()
# have a reference to the default nic
eth0 = nic_opts.setdefault(default_nic,
salt.utils.odict.OrderedDict())
# lxc config is based of ifc order, be sure to use odicts.
if not isinstance(nic_opts, salt.utils.odict.OrderedDict):
bnic_opts = salt.utils.odict.OrderedDict()
bnic_opts.update(nic_opts)
nic_opts = bnic_opts
gw = None
# legacy salt.cloud scheme for network interfaces settings support
bridge = _cloud_get('bridge', None)
ip = _cloud_get('ip', None)
mac = _cloud_get('mac', None)
if ip:
fullip = ip
if netmask:
fullip += '/{0}'.format(netmask)
eth0['ipv4'] = fullip
if mac is not None:
eth0['mac'] = mac
for ix, iopts in enumerate(_cloud_get("additional_ips", [])):
ifh = "eth{0}".format(ix+1)
ethx = nic_opts.setdefault(ifh, {})
if gw is None:
gw = iopts.get('gateway', ethx.get('gateway', None))
if gw:
# only one and only one default gateway is allowed !
eth0.pop('gateway', None)
gateway = None
# even if the gateway if on default "eth0" nic
# and we popped it will work
# as we reinject or set it here.
ethx['gateway'] = gw
elink = iopts.get('link', ethx.get('link', None))
if elink:
ethx['link'] = elink
# allow dhcp
aip = iopts.get('ipv4', iopts.get('ip', None))
if aip:
ethx['ipv4'] = aip
nm = iopts.get('netmask', '')
if nm:
ethx['ipv4'] += '/{0}'.format(nm)
for i in ('mac', 'hwaddr'):
if i in iopts:
ethx['mac'] = iopts[i]
break
if 'mac' not in ethx:
ethx['mac'] = salt.utils.network.gen_mac()
# last round checking for unique gateway and such
gw = None
for ethx in [a for a in nic_opts]:
ndata = nic_opts[ethx]
if gw:
ndata.pop('gateway', None)
if 'gateway' in ndata:
gw = ndata['gateway']
gateway = None
# only use a default bridge / gateway if we configured them
# via the legacy salt cloud configuration style.
# On other cases, we should rely on settings provided by the new
# salt lxc network profile style configuration which can
# be also be overridden or a per interface basis via the nic_opts dict.
if bridge:
eth0['link'] = bridge
if gateway:
eth0['gateway'] = gateway
#
lxc_init_interface = {}
lxc_init_interface['name'] = name
lxc_init_interface['config'] = config
lxc_init_interface['memory'] = _cloud_get('memory', 0) # nolimit
lxc_init_interface['pub_key'] = pub_key
lxc_init_interface['priv_key'] = priv_key
lxc_init_interface['nic_opts'] = nic_opts
for clone_from in ['clone_from', 'clone', 'from_container']:
# clone_from should default to None if not available
lxc_init_interface['clone_from'] = _cloud_get(clone_from, None)
if lxc_init_interface['clone_from'] is not None:
break
lxc_init_interface['profile'] = profile
lxc_init_interface['snapshot'] = snapshot
lxc_init_interface['dnsservers'] = dnsservers
lxc_init_interface['fstype'] = fstype
lxc_init_interface['path'] = path
lxc_init_interface['vgname'] = vgname
lxc_init_interface['size'] = size
lxc_init_interface['lvname'] = lvname
lxc_init_interface['thinpool'] = thinpool
lxc_init_interface['force_install'] = force_install
lxc_init_interface['unconditional_install'] = (
unconditional_install
)
lxc_init_interface['bootstrap_url'] = script
lxc_init_interface['bootstrap_args'] = script_args
lxc_init_interface['bootstrap_shell'] = _cloud_get('bootstrap_shell', 'sh')
lxc_init_interface['bootstrap_delay'] = _cloud_get('bootstrap_delay', None)
lxc_init_interface['autostart'] = autostart
lxc_init_interface['users'] = users
lxc_init_interface['password'] = password
lxc_init_interface['password_encrypted'] = password_encrypted
# be sure not to let objects goes inside the return
# as this return will be msgpacked for use in the runner !
lxc_init_interface['network_profile'] = network_profile
for i in ['cpu', 'cpuset', 'cpushare']:
if _cloud_get(i, None):
try:
lxc_init_interface[i] = vm_[i]
except KeyError:
lxc_init_interface[i] = profile[i]
return lxc_init_interface
def _get_profile(key, name, **kwargs):
if isinstance(name, dict):
profilename = name.pop('name', None)
return _get_profile(key, profilename, **name)
if name is None:
profile_match = {}
else:
profile_match = \
__salt__['config.get'](
'lxc.{1}:{0}'.format(name, key),
default=None,
merge='recurse'
)
if profile_match is None:
# No matching profile, make the profile an empty dict so that
# overrides can be applied below.
profile_match = {}
if not isinstance(profile_match, dict):
raise CommandExecutionError('lxc.{0} must be a dictionary'.format(key))
# Overlay the kwargs to override matched profile data
overrides = salt.utils.args.clean_kwargs(**copy.deepcopy(kwargs))
profile_match = salt.utils.dictupdate.update(
copy.deepcopy(profile_match),
overrides
)
return profile_match
def get_container_profile(name=None, **kwargs):
'''
.. versionadded:: 2015.5.0
Gather a pre-configured set of container configuration parameters. If no
arguments are passed, an empty profile is returned.
Profiles can be defined in the minion or master config files, or in pillar
or grains, and are loaded using :mod:`config.get
<salt.modules.config.get>`. The key under which LXC profiles must be
configured is ``lxc.container_profile.profile_name``. An example container
profile would be as follows:
.. code-block:: yaml
lxc.container_profile:
ubuntu:
template: ubuntu
backing: lvm
vgname: lxc
size: 1G
Parameters set in a profile can be overridden by passing additional
container creation arguments (such as the ones passed to :mod:`lxc.create
<salt.modules.lxc.create>`) to this function.
A profile can be defined either as the name of the profile, or a dictionary
of variable names and values. See the :ref:`LXC Tutorial
<tutorial-lxc-profiles>` for more information on how to use LXC profiles.
CLI Example:
.. code-block:: bash
salt-call lxc.get_container_profile centos
salt-call lxc.get_container_profile ubuntu template=ubuntu backing=overlayfs
'''
profile = _get_profile('container_profile', name, **kwargs)
return profile
def get_network_profile(name=None, **kwargs):
'''
.. versionadded:: 2015.5.0
Gather a pre-configured set of network configuration parameters. If no
arguments are passed, the following default profile is returned:
.. code-block:: python
{'eth0': {'link': 'br0', 'type': 'veth', 'flags': 'up'}}
Profiles can be defined in the minion or master config files, or in pillar
or grains, and are loaded using :mod:`config.get
<salt.modules.config.get>`. The key under which LXC profiles must be
configured is ``lxc.network_profile``. An example network profile would be
as follows:
.. code-block:: yaml
lxc.network_profile.centos:
eth0:
link: br0
type: veth
flags: up
To disable networking entirely:
.. code-block:: yaml
lxc.network_profile.centos:
eth0:
disable: true
Parameters set in a profile can be overridden by passing additional
arguments to this function.
A profile can be passed either as the name of the profile, or a
dictionary of variable names and values. See the :ref:`LXC Tutorial
<tutorial-lxc-profiles>` for more information on how to use network
profiles.
.. warning::
The ``ipv4``, ``ipv6``, ``gateway``, and ``link`` (bridge) settings in
network profiles will only work if the container doesn't redefine the
network configuration (for example in
``/etc/sysconfig/network-scripts/ifcfg-<interface_name>`` on
RHEL/CentOS, or ``/etc/network/interfaces`` on Debian/Ubuntu/etc.)
CLI Example:
.. code-block:: bash
salt-call lxc.get_network_profile default
'''
profile = _get_profile('network_profile', name, **kwargs)
return profile
def _rand_cpu_str(cpu):
'''
Return a random subset of cpus for the cpuset config
'''
cpu = int(cpu)
avail = __salt__['status.nproc']()
if cpu < avail:
return '0-{0}'.format(avail)
to_set = set()
while len(to_set) < cpu:
choice = random.randint(0, avail - 1)
if choice not in to_set:
to_set.add(six.text_type(choice))
return ','.join(sorted(to_set))
def _network_conf(conf_tuples=None, **kwargs):
'''
Network configuration defaults
network_profile
as for containers, we can either call this function
either with a network_profile dict or network profile name
in the kwargs
nic_opts
overrides or extra nics in the form {nic_name: {set: tings}
'''
nic = kwargs.get('network_profile', None)
ret = []
nic_opts = kwargs.get('nic_opts', {})
if nic_opts is None:
# coming from elsewhere
nic_opts = {}
if not conf_tuples:
conf_tuples = []
old = _get_veths(conf_tuples)
if not old:
old = {}
# if we have a profile name, get the profile and load the network settings
# this will obviously by default look for a profile called "eth0"
# or by what is defined in nic_opts
# and complete each nic settings by sane defaults
if nic and isinstance(nic, (six.string_types, dict)):
nicp = get_network_profile(nic)
else:
nicp = {}
if DEFAULT_NIC not in nicp:
nicp[DEFAULT_NIC] = {}
kwargs = copy.deepcopy(kwargs)
gateway = kwargs.pop('gateway', None)
bridge = kwargs.get('bridge', None)
if nic_opts:
for dev, args in six.iteritems(nic_opts):
ethx = nicp.setdefault(dev, {})
try:
ethx = salt.utils.dictupdate.update(ethx, args)
except AttributeError:
raise SaltInvocationError('Invalid nic_opts configuration')
ifs = [a for a in nicp]
ifs += [a for a in old if a not in nicp]
ifs.sort()
gateway_set = False
for dev in ifs:
args = nicp.get(dev, {})
opts = nic_opts.get(dev, {}) if nic_opts else {}
old_if = old.get(dev, {})
disable = opts.get('disable', args.get('disable', False))
if disable:
continue
mac = opts.get('mac',
opts.get('hwaddr',
args.get('mac',
args.get('hwaddr', ''))))
type_ = opts.get('type', args.get('type', ''))
flags = opts.get('flags', args.get('flags', ''))
link = opts.get('link', args.get('link', ''))
ipv4 = opts.get('ipv4', args.get('ipv4', ''))
ipv6 = opts.get('ipv6', args.get('ipv6', ''))
infos = salt.utils.odict.OrderedDict([
('lxc.network.type', {
'test': not type_,
'value': type_,
'old': old_if.get('lxc.network.type'),
'default': 'veth'}),
('lxc.network.name', {
'test': False,
'value': dev,
'old': dev,
'default': dev}),
('lxc.network.flags', {
'test': not flags,
'value': flags,
'old': old_if.get('lxc.network.flags'),
'default': 'up'}),
('lxc.network.link', {
'test': not link,
'value': link,
'old': old_if.get('lxc.network.link'),
'default': search_lxc_bridge()}),
('lxc.network.hwaddr', {
'test': not mac,
'value': mac,
'old': old_if.get('lxc.network.hwaddr'),
'default': salt.utils.network.gen_mac()}),
('lxc.network.ipv4', {
'test': not ipv4,
'value': ipv4,
'old': old_if.get('lxc.network.ipv4', ''),
'default': None}),
('lxc.network.ipv6', {
'test': not ipv6,
'value': ipv6,
'old': old_if.get('lxc.network.ipv6', ''),
'default': None})])
# for each parameter, if not explicitly set, the
# config value present in the LXC configuration should
# take precedence over the profile configuration
for info in list(infos.keys()):
bundle = infos[info]
if bundle['test']:
if bundle['old']:
bundle['value'] = bundle['old']
elif bundle['default']:
bundle['value'] = bundle['default']
for info, data in six.iteritems(infos):
if data['value']:
ret.append({info: data['value']})
for key, val in six.iteritems(args):
if key == 'link' and bridge:
val = bridge
val = opts.get(key, val)
if key in [
'type', 'flags', 'name',
'gateway', 'mac', 'link', 'ipv4', 'ipv6'
]:
continue
ret.append({'lxc.network.{0}'.format(key): val})
# gateway (in automode) must be appended following network conf !
if not gateway:
gateway = args.get('gateway', None)
if gateway is not None and not gateway_set:
ret.append({'lxc.network.ipv4.gateway': gateway})
# only one network gateway ;)
gateway_set = True
# normally, this won't happen
# set the gateway if specified even if we did
# not managed the network underlying
if gateway is not None and not gateway_set:
ret.append({'lxc.network.ipv4.gateway': gateway})
# only one network gateway ;)
gateway_set = True
new = _get_veths(ret)
# verify that we did not loose the mac settings
for iface in [a for a in new]:
ndata = new[iface]
nmac = ndata.get('lxc.network.hwaddr', '')
ntype = ndata.get('lxc.network.type', '')
omac, otype = '', ''
if iface in old:
odata = old[iface]
omac = odata.get('lxc.network.hwaddr', '')
otype = odata.get('lxc.network.type', '')
# default for network type is setted here
# attention not to change the network type
# without a good and explicit reason to.
if otype and not ntype:
ntype = otype
if not ntype:
ntype = 'veth'
new[iface]['lxc.network.type'] = ntype
if omac and not nmac:
new[iface]['lxc.network.hwaddr'] = omac
ret = []
for val in six.itervalues(new):
for row in val:
ret.append(salt.utils.odict.OrderedDict([(row, val[row])]))
# on old versions of lxc, still support the gateway auto mode
# if we didn't explicitly say no to
# (lxc.network.ipv4.gateway: auto)
if _LooseVersion(version()) <= _LooseVersion('1.0.7') and \
True not in ['lxc.network.ipv4.gateway' in a for a in ret] and \
True in ['lxc.network.ipv4' in a for a in ret]:
ret.append({'lxc.network.ipv4.gateway': 'auto'})
return ret
def _get_lxc_default_data(**kwargs):
kwargs = copy.deepcopy(kwargs)
ret = {}
for k in ['utsname', 'rootfs']:
val = kwargs.get(k, None)
if val is not None:
ret['lxc.{0}'.format(k)] = val
autostart = kwargs.get('autostart')
# autostart can have made in kwargs, but with the None
# value which is invalid, we need an explicit boolean
# autostart = on is the default.
if autostart is None:
autostart = True
# we will set the regular lxc marker to restart container at
# machine (re)boot only if we did not explicitly ask
# not to touch to the autostart settings via
# autostart == 'keep'
if autostart != 'keep':
if autostart:
ret['lxc.start.auto'] = '1'
else:
ret['lxc.start.auto'] = '0'
memory = kwargs.get('memory')
if memory is not None:
# converting the config value from MB to bytes
ret['lxc.cgroup.memory.limit_in_bytes'] = memory * 1024 * 1024
cpuset = kwargs.get('cpuset')
if cpuset:
ret['lxc.cgroup.cpuset.cpus'] = cpuset
cpushare = kwargs.get('cpushare')
cpu = kwargs.get('cpu')
if cpushare:
ret['lxc.cgroup.cpu.shares'] = cpushare
if cpu and not cpuset:
ret['lxc.cgroup.cpuset.cpus'] = _rand_cpu_str(cpu)
return ret
def _config_list(conf_tuples=None, only_net=False, **kwargs):
'''
Return a list of dicts from the salt level configurations
conf_tuples
_LXCConfig compatible list of entries which can contain
- string line
- tuple (lxc config param,value)
- dict of one entry: {lxc config param: value)
only_net
by default we add to the tuples a reflection of both
the real config if avalaible and a certain amount of
default values like the cpu parameters, the memory
and etc.
On the other hand, we also no matter the case reflect
the network configuration computed from the actual config if
available and given values.
if no_default_loads is set, we will only
reflect the network configuration back to the conf tuples
list
'''
# explicit cast
only_net = bool(only_net)
if not conf_tuples:
conf_tuples = []
kwargs = copy.deepcopy(kwargs)
ret = []
if not only_net:
default_data = _get_lxc_default_data(**kwargs)
for k, val in six.iteritems(default_data):
ret.append({k: val})
net_datas = _network_conf(conf_tuples=conf_tuples, **kwargs)
ret.extend(net_datas)
return ret
def _get_veths(net_data):
'''
Parse the nic setup inside lxc conf tuples back to a dictionary indexed by
network interface
'''
if isinstance(net_data, dict):
net_data = list(net_data.items())
nics = salt.utils.odict.OrderedDict()
current_nic = salt.utils.odict.OrderedDict()
no_names = True
for item in net_data:
if item and isinstance(item, dict):
item = list(item.items())[0]
# skip LXC configuration comment lines, and play only with tuples conf
elif isinstance(item, six.string_types):
# deal with reflection of commented lxc configs
sitem = item.strip()
if sitem.startswith('#') or not sitem:
continue
elif '=' in item:
item = tuple([a.strip() for a in item.split('=', 1)])
if item[0] == 'lxc.network.type':
current_nic = salt.utils.odict.OrderedDict()
if item[0] == 'lxc.network.name':
no_names = False
nics[item[1].strip()] = current_nic
current_nic[item[0].strip()] = item[1].strip()
# if not ethernet card name has been collected, assuming we collected
# data for eth0
if no_names and current_nic:
nics[DEFAULT_NIC] = current_nic
return nics
class _LXCConfig(object):
'''
LXC configuration data
'''
pattern = re.compile(r'^(\S+)(\s*)(=)(\s*)(.*)')
non_interpretable_pattern = re.compile(r'^((#.*)|(\s*))$')
def __init__(self, **kwargs):
kwargs = copy.deepcopy(kwargs)
self.name = kwargs.pop('name', None)
path = get_root_path(kwargs.get('path', None))
self.data = []
if self.name:
self.path = os.path.join(path, self.name, 'config')
if os.path.isfile(self.path):
with salt.utils.files.fopen(self.path) as fhr:
for line in salt.utils.data.decode(fhr.readlines()):
match = self.pattern.findall((line.strip()))
if match:
self.data.append((match[0][0], match[0][-1]))
match = self.non_interpretable_pattern.findall(
(line.strip()))
if match:
self.data.append(('', match[0][0]))
else:
self.path = None
def _replace(key, val):
if val:
self._filter_data(key)
self.data.append((key, val))
default_data = _get_lxc_default_data(**kwargs)
for key, val in six.iteritems(default_data):
_replace(key, val)
old_net = self._filter_data('lxc.network')
net_datas = _network_conf(conf_tuples=old_net, **kwargs)
if net_datas:
for row in net_datas:
self.data.extend(list(row.items()))
# be sure to reset harmful settings
for idx in ['lxc.cgroup.memory.limit_in_bytes']:
if not default_data.get(idx):
self._filter_data(idx)
def as_string(self):
chunks = ('{0[0]}{1}{0[1]}'.format(item, (' = ' if item[0] else '')) for item in self.data)
return '\n'.join(chunks) + '\n'
def write(self):
if self.path:
content = self.as_string()
# 2 step rendering to be sure not to open/wipe the config
# before as_string succeeds.
with salt.utils.files.fopen(self.path, 'w') as fic:
fic.write(salt.utils.stringutils.to_str(content))
fic.flush()
def tempfile(self):
# this might look like the function name is shadowing the
# module, but it's not since the method belongs to the class
ntf = tempfile.NamedTemporaryFile()
ntf.write(self.as_string())
ntf.flush()
return ntf
def _filter_data(self, pattern):
'''
Removes parameters which match the pattern from the config data
'''
removed = []
filtered = []
for param in self.data:
if not param[0].startswith(pattern):
filtered.append(param)
else:
removed.append(param)
self.data = filtered
return removed
def _get_base(**kwargs):
'''
If the needed base does not exist, then create it, if it does exist
create nothing and return the name of the base lxc container so
it can be cloned.
'''
profile = get_container_profile(copy.deepcopy(kwargs.get('profile')))
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, _marker)
profile_match = profile.pop(key, default)
# let kwarg overrides be the preferred choice
if kw_overrides_match is _marker:
return profile_match
return kw_overrides_match
template = select('template')
image = select('image')
vgname = select('vgname')
path = kwargs.get('path', None)
# remove the above three variables from kwargs, if they exist, to avoid
# duplicates if create() is invoked below.
for param in ('path', 'image', 'vgname', 'template'):
kwargs.pop(param, None)
if image:
proto = _urlparse(image).scheme
img_tar = __salt__['cp.cache_file'](image)
img_name = os.path.basename(img_tar)
hash_ = salt.utils.hashutils.get_hash(
img_tar,
__salt__['config.get']('hash_type'))
name = '__base_{0}_{1}_{2}'.format(proto, img_name, hash_)
if not exists(name, path=path):
create(name, template=template, image=image,
path=path, vgname=vgname, **kwargs)
if vgname:
rootfs = os.path.join('/dev', vgname, name)
edit_conf(info(name, path=path)['config'],
out_format='commented', **{'lxc.rootfs': rootfs})
return name
elif template:
name = '__base_{0}'.format(template)
if not exists(name, path=path):
create(name, template=template, image=image, path=path,
vgname=vgname, **kwargs)
if vgname:
rootfs = os.path.join('/dev', vgname, name)
edit_conf(info(name, path=path)['config'],
out_format='commented', **{'lxc.rootfs': rootfs})
return name
return ''
def init(name,
config=None,
cpuset=None,
cpushare=None,
memory=None,
profile=None,
network_profile=None,
nic_opts=None,
cpu=None,
autostart=True,
password=None,
password_encrypted=None,
users=None,
dnsservers=None,
searchdomains=None,
bridge=None,
gateway=None,
pub_key=None,
priv_key=None,
force_install=False,
unconditional_install=False,
bootstrap_delay=None,
bootstrap_args=None,
bootstrap_shell=None,
bootstrap_url=None,
**kwargs):
'''
Initialize a new container.
This is a partial idempotent function as if it is already provisioned, we
will reset a bit the lxc configuration file but much of the hard work will
be escaped as markers will prevent re-execution of harmful tasks.
name
Name of the container
image
A tar archive to use as the rootfs for the container. Conflicts with
the ``template`` argument.
cpus
Select a random number of cpu cores and assign it to the cpuset, if the
cpuset option is set then this option will be ignored
cpuset
Explicitly define the cpus this container will be bound to
cpushare
cgroups cpu shares
autostart
autostart container on reboot
memory
cgroups memory limit, in MB
.. versionchanged:: 2015.5.0
If no value is passed, no limit is set. In earlier Salt versions,
not passing this value causes a 1024MB memory limit to be set, and
it was necessary to pass ``memory=0`` to set no limit.
gateway
the ipv4 gateway to use
the default does nothing more than lxcutils does
bridge
the bridge to use
the default does nothing more than lxcutils does
network_profile
Network profile to use for the container
.. versionadded:: 2015.5.0
nic_opts
Extra options for network interfaces, will override
``{"eth0": {"hwaddr": "aa:bb:cc:dd:ee:ff", "ipv4": "10.1.1.1", "ipv6": "2001:db8::ff00:42:8329"}}``
or
``{"eth0": {"hwaddr": "aa:bb:cc:dd:ee:ff", "ipv4": "10.1.1.1/24", "ipv6": "2001:db8::ff00:42:8329"}}``
users
Users for which the password defined in the ``password`` param should
be set. Can be passed as a comma separated list or a python list.
Defaults to just the ``root`` user.
password
Set the initial password for the users defined in the ``users``
parameter
password_encrypted : False
Set to ``True`` to denote a password hash instead of a plaintext
password
.. versionadded:: 2015.5.0
profile
A LXC profile (defined in config or pillar).
This can be either a real profile mapping or a string
to retrieve it in configuration
start
Start the newly-created container
dnsservers
list of dns servers to set in the container, default [] (no setting)
seed
Seed the container with the minion config. Default: ``True``
install
If salt-minion is not already installed, install it. Default: ``True``
config
Optional config parameters. By default, the id is set to
the name of the container.
master
salt master (default to minion's master)
master_port
salt master port (default to minion's master port)
pub_key
Explicit public key to preseed the minion with (optional).
This can be either a filepath or a string representing the key
priv_key
Explicit private key to preseed the minion with (optional).
This can be either a filepath or a string representing the key
approve_key
If explicit preseeding is not used;
Attempt to request key approval from the master. Default: ``True``
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
clone_from
Original from which to use a clone operation to create the container.
Default: ``None``
bootstrap_delay
Delay in seconds between end of container creation and bootstrapping.
Useful when waiting for container to obtain a DHCP lease.
.. versionadded:: 2015.5.0
bootstrap_url
See lxc.bootstrap
bootstrap_shell
See lxc.bootstrap
bootstrap_args
See lxc.bootstrap
force_install
Force installation even if salt-minion is detected,
this is the way to run vendor bootstrap scripts even
if a salt minion is already present in the container
unconditional_install
Run the script even if the container seems seeded
CLI Example:
.. code-block:: bash
salt 'minion' lxc.init name [cpuset=cgroups_cpuset] \\
[cpushare=cgroups_cpushare] [memory=cgroups_memory] \\
[nic=nic_profile] [profile=lxc_profile] \\
[nic_opts=nic_opts] [start=(True|False)] \\
[seed=(True|False)] [install=(True|False)] \\
[config=minion_config] [approve_key=(True|False) \\
[clone_from=original] [autostart=True] \\
[priv_key=/path_or_content] [pub_key=/path_or_content] \\
[bridge=lxcbr0] [gateway=10.0.3.1] \\
[dnsservers[dns1,dns2]] \\
[users=[foo]] [password='secret'] \\
[password_encrypted=(True|False)]
'''
ret = {'name': name,
'changes': {}}
profile = get_container_profile(copy.deepcopy(profile))
if not network_profile:
network_profile = profile.get('network_profile')
if not network_profile:
network_profile = DEFAULT_NIC
# Changes is a pointer to changes_dict['init']. This method is used so that
# we can have a list of changes as they are made, providing an ordered list
# of things that were changed.
changes_dict = {'init': []}
changes = changes_dict.get('init')
if users is None:
users = []
dusers = ['root']
for user in dusers:
if user not in users:
users.append(user)
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, _marker)
profile_match = profile.pop(key, default)
# let kwarg overrides be the preferred choice
if kw_overrides_match is _marker:
return profile_match
return kw_overrides_match
path = select('path')
bpath = get_root_path(path)
state_pre = state(name, path=path)
tvg = select('vgname')
vgname = tvg if tvg else __salt__['config.get']('lxc.vgname')
start_ = select('start', True)
autostart = select('autostart', autostart)
seed = select('seed', True)
install = select('install', True)
seed_cmd = select('seed_cmd')
salt_config = _get_salt_config(config, **kwargs)
approve_key = select('approve_key', True)
clone_from = select('clone_from')
# If using a volume group then set up to make snapshot cow clones
if vgname and not clone_from:
try:
kwargs['vgname'] = vgname
clone_from = _get_base(profile=profile, **kwargs)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = exc.strerror
if changes:
ret['changes'] = changes_dict
return ret
if not kwargs.get('snapshot') is False:
kwargs['snapshot'] = True
does_exist = exists(name, path=path)
to_reboot = False
remove_seed_marker = False
if does_exist:
pass
elif clone_from:
remove_seed_marker = True
try:
clone(name, clone_from, profile=profile, **kwargs)
changes.append({'create': 'Container cloned'})
except (SaltInvocationError, CommandExecutionError) as exc:
if 'already exists' in exc.strerror:
changes.append({'create': 'Container already exists'})
else:
ret['result'] = False
ret['comment'] = exc.strerror
if changes:
ret['changes'] = changes_dict
return ret
cfg = _LXCConfig(name=name, network_profile=network_profile,
nic_opts=nic_opts, bridge=bridge, path=path,
gateway=gateway, autostart=autostart,
cpuset=cpuset, cpushare=cpushare, memory=memory)
old_chunks = read_conf(cfg.path, out_format='commented')
cfg.write()
chunks = read_conf(cfg.path, out_format='commented')
if old_chunks != chunks:
to_reboot = True
else:
remove_seed_marker = True
cfg = _LXCConfig(network_profile=network_profile,
nic_opts=nic_opts, cpuset=cpuset, path=path,
bridge=bridge, gateway=gateway,
autostart=autostart,
cpushare=cpushare, memory=memory)
with cfg.tempfile() as cfile:
try:
create(name, config=cfile.name, profile=profile, **kwargs)
changes.append({'create': 'Container created'})
except (SaltInvocationError, CommandExecutionError) as exc:
if 'already exists' in exc.strerror:
changes.append({'create': 'Container already exists'})
else:
ret['comment'] = exc.strerror
if changes:
ret['changes'] = changes_dict
return ret
cpath = os.path.join(bpath, name, 'config')
old_chunks = []
if os.path.exists(cpath):
old_chunks = read_conf(cpath, out_format='commented')
new_cfg = _config_list(conf_tuples=old_chunks,
cpu=cpu,
network_profile=network_profile,
nic_opts=nic_opts, bridge=bridge,
cpuset=cpuset, cpushare=cpushare,
memory=memory)
if new_cfg:
edit_conf(cpath, out_format='commented', lxc_config=new_cfg)
chunks = read_conf(cpath, out_format='commented')
if old_chunks != chunks:
to_reboot = True
# last time to be sure any of our property is correctly applied
cfg = _LXCConfig(name=name, network_profile=network_profile,
nic_opts=nic_opts, bridge=bridge, path=path,
gateway=gateway, autostart=autostart,
cpuset=cpuset, cpushare=cpushare, memory=memory)
old_chunks = []
if os.path.exists(cfg.path):
old_chunks = read_conf(cfg.path, out_format='commented')
cfg.write()
chunks = read_conf(cfg.path, out_format='commented')
if old_chunks != chunks:
changes.append({'config': 'Container configuration updated'})
to_reboot = True
if to_reboot:
try:
stop(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
if changes:
ret['changes'] = changes_dict
return ret
if not does_exist or (does_exist and state(name, path=path) != 'running'):
try:
start(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
if changes:
ret['changes'] = changes_dict
return ret
if remove_seed_marker:
run(name,
'rm -f \'{0}\''.format(SEED_MARKER),
path=path,
chroot_fallback=False,
python_shell=False)
# set the default user/password, only the first time
if ret.get('result', True) and password:
gid = '/.lxc.initial_pass'
gids = [gid,
'/lxc.initial_pass',
'/.lxc.{0}.initial_pass'.format(name)]
if not any(retcode(name,
'test -e "{0}"'.format(x),
chroot_fallback=True,
path=path,
ignore_retcode=True) == 0
for x in gids):
# think to touch the default user generated by default templates
# which has a really unsecure passwords...
# root is defined as a member earlier in the code
for default_user in ['ubuntu']:
if (
default_user not in users and
retcode(name,
'id {0}'.format(default_user),
python_shell=False,
path=path,
chroot_fallback=True,
ignore_retcode=True) == 0
):
users.append(default_user)
for user in users:
try:
cret = set_password(name,
users=[user],
path=path,
password=password,
encrypted=password_encrypted)
except (SaltInvocationError, CommandExecutionError) as exc:
msg = '{0}: Failed to set password'.format(
user) + exc.strerror
# only hardfail in unrecoverable situation:
# root cannot be setted up
if user == 'root':
ret['comment'] = msg
ret['result'] = False
else:
log.debug(msg)
if ret.get('result', True):
changes.append({'password': 'Password(s) updated'})
if retcode(name,
('sh -c \'touch "{0}"; test -e "{0}"\''
.format(gid)),
path=path,
chroot_fallback=True,
ignore_retcode=True) != 0:
ret['comment'] = 'Failed to set password marker'
changes[-1]['password'] += '. ' + ret['comment'] + '.'
ret['result'] = False
# set dns servers if any, only the first time
if ret.get('result', True) and dnsservers:
# retro compatibility, test also old markers
gid = '/.lxc.initial_dns'
gids = [gid,
'/lxc.initial_dns',
'/lxc.{0}.initial_dns'.format(name)]
if not any(retcode(name,
'test -e "{0}"'.format(x),
chroot_fallback=True,
path=path,
ignore_retcode=True) == 0
for x in gids):
try:
set_dns(name,
path=path,
dnsservers=dnsservers,
searchdomains=searchdomains)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Failed to set DNS: ' + exc.strerror
ret['result'] = False
else:
changes.append({'dns': 'DNS updated'})
if retcode(name,
('sh -c \'touch "{0}"; test -e "{0}"\''
.format(gid)),
chroot_fallback=True,
path=path,
ignore_retcode=True) != 0:
ret['comment'] = 'Failed to set DNS marker'
changes[-1]['dns'] += '. ' + ret['comment'] + '.'
ret['result'] = False
# retro compatibility, test also old markers
if remove_seed_marker:
run(name,
'rm -f \'{0}\''.format(SEED_MARKER),
path=path,
python_shell=False)
gid = '/.lxc.initial_seed'
gids = [gid, '/lxc.initial_seed']
if (
any(retcode(name,
'test -e {0}'.format(x),
path=path,
chroot_fallback=True,
ignore_retcode=True) == 0
for x in gids) or not ret.get('result', True)
):
pass
elif seed or seed_cmd:
if seed:
try:
result = bootstrap(
name, config=salt_config, path=path,
approve_key=approve_key,
pub_key=pub_key, priv_key=priv_key,
install=install,
force_install=force_install,
unconditional_install=unconditional_install,
bootstrap_delay=bootstrap_delay,
bootstrap_url=bootstrap_url,
bootstrap_shell=bootstrap_shell,
bootstrap_args=bootstrap_args)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Bootstrap failed: ' + exc.strerror
ret['result'] = False
else:
if not result:
ret['comment'] = ('Bootstrap failed, see minion log for '
'more information')
ret['result'] = False
else:
changes.append(
{'bootstrap': 'Container successfully bootstrapped'}
)
elif seed_cmd:
try:
result = __salt__[seed_cmd](info(name, path=path)['rootfs'],
name,
salt_config)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = ('Bootstrap via seed_cmd \'{0}\' failed: {1}'
.format(seed_cmd, exc.strerror))
ret['result'] = False
else:
if not result:
ret['comment'] = ('Bootstrap via seed_cmd \'{0}\' failed, '
'see minion log for more information '
.format(seed_cmd))
ret['result'] = False
else:
changes.append(
{'bootstrap': 'Container successfully bootstrapped '
'using seed_cmd \'{0}\''
.format(seed_cmd)}
)
if ret.get('result', True) and not start_:
try:
stop(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
ret['result'] = False
state_post = state(name, path=path)
if state_pre != state_post:
changes.append({'state': {'old': state_pre, 'new': state_post}})
if ret.get('result', True):
ret['comment'] = ('Container \'{0}\' successfully initialized'
.format(name))
ret['result'] = True
if changes:
ret['changes'] = changes_dict
return ret
def cloud_init(name, vm_=None, **kwargs):
'''
Thin wrapper to lxc.init to be used from the saltcloud lxc driver
name
Name of the container
may be None and then guessed from saltcloud mapping
`vm_`
saltcloud mapping defaults for the vm
CLI Example:
.. code-block:: bash
salt '*' lxc.cloud_init foo
'''
init_interface = cloud_init_interface(name, vm_, **kwargs)
name = init_interface.pop('name', name)
return init(name, **init_interface)
def images(dist=None):
'''
.. versionadded:: 2015.5.0
List the available images for LXC's ``download`` template.
dist : None
Filter results to a single Linux distribution
CLI Examples:
.. code-block:: bash
salt myminion lxc.images
salt myminion lxc.images dist=centos
'''
out = __salt__['cmd.run_stdout'](
'lxc-create -n __imgcheck -t download -- --list',
ignore_retcode=True
)
if 'DIST' not in out:
raise CommandExecutionError(
'Unable to run the \'download\' template script. Is it installed?'
)
ret = {}
passed_header = False
for line in out.splitlines():
try:
distro, release, arch, variant, build_time = line.split()
except ValueError:
continue
if not passed_header:
if distro == 'DIST':
passed_header = True
continue
dist_list = ret.setdefault(distro, [])
dist_list.append({
'release': release,
'arch': arch,
'variant': variant,
'build_time': build_time,
})
if dist is not None:
return dict([(dist, ret.get(dist, []))])
return ret
def templates():
'''
.. versionadded:: 2015.5.0
List the available LXC template scripts installed on the minion
CLI Examples:
.. code-block:: bash
salt myminion lxc.templates
'''
try:
template_scripts = os.listdir('/usr/share/lxc/templates')
except OSError:
return []
else:
return [x[4:] for x in template_scripts if x.startswith('lxc-')]
def _after_ignition_network_profile(cmd,
ret,
name,
network_profile,
path,
nic_opts):
_clear_context()
if ret['retcode'] == 0 and exists(name, path=path):
if network_profile:
network_changes = apply_network_profile(name,
network_profile,
path=path,
nic_opts=nic_opts)
if network_changes:
log.info(
'Network changes from applying network profile \'%s\' '
'to newly-created container \'%s\':\n%s',
network_profile, name, network_changes
)
c_state = state(name, path=path)
return {'result': True,
'state': {'old': None, 'new': c_state}}
else:
if exists(name, path=path):
# destroy the container if it was partially created
cmd = 'lxc-destroy'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0}'.format(name)
__salt__['cmd.retcode'](cmd, python_shell=False)
raise CommandExecutionError(
'Container could not be created with cmd \'{0}\': {1}'
.format(cmd, ret['stderr'])
)
def create(name,
config=None,
profile=None,
network_profile=None,
nic_opts=None,
**kwargs):
'''
Create a new container.
name
Name of the container
config
The config file to use for the container. Defaults to system-wide
config (usually in /etc/lxc/lxc.conf).
profile
Profile to use in container creation (see
:mod:`lxc.get_container_profile
<salt.modules.lxc.get_container_profile>`). Values in a profile will be
overridden by the **Container Creation Arguments** listed below.
network_profile
Network profile to use for container
.. versionadded:: 2015.5.0
**Container Creation Arguments**
template
The template to use. For example, ``ubuntu`` or ``fedora``.
For a full list of available templates, check out
the :mod:`lxc.templates <salt.modules.lxc.templates>` function.
Conflicts with the ``image`` argument.
.. note::
The ``download`` template requires the following three parameters
to be defined in ``options``:
* **dist** - The name of the distribution
* **release** - Release name/version
* **arch** - Architecture of the container
The available images can be listed using the :mod:`lxc.images
<salt.modules.lxc.images>` function.
options
Template-specific options to pass to the lxc-create command. These
correspond to the long options (ones beginning with two dashes) that
the template script accepts. For example:
.. code-block:: bash
options='{"dist": "centos", "release": "6", "arch": "amd64"}'
For available template options, refer to the lxc template scripts
which are ususally located under ``/usr/share/lxc/templates``,
or run ``lxc-create -t <template> -h``.
image
A tar archive to use as the rootfs for the container. Conflicts with
the ``template`` argument.
backing
The type of storage to use. Set to ``lvm`` to use an LVM group.
Defaults to filesystem within /var/lib/lxc.
fstype
Filesystem type to use on LVM logical volume
size : 1G
Size of the volume to create. Only applicable if ``backing=lvm``.
vgname : lxc
Name of the LVM volume group in which to create the volume for this
container. Only applicable if ``backing=lvm``.
lvname
Name of the LVM logical volume in which to create the volume for this
container. Only applicable if ``backing=lvm``.
thinpool
Name of a pool volume that will be used for thin-provisioning this
container. Only applicable if ``backing=lvm``.
nic_opts
give extra opts overriding network profile values
path
parent path for the container creation (default: /var/lib/lxc)
zfsroot
Name of the ZFS root in which to create the volume for this container.
Only applicable if ``backing=zfs``. (default: tank/lxc)
.. versionadded:: 2015.8.0
'''
# Required params for 'download' template
download_template_deps = ('dist', 'release', 'arch')
cmd = 'lxc-create -n {0}'.format(name)
profile = get_container_profile(copy.deepcopy(profile))
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, None)
profile_match = profile.pop(key, default)
# Return the profile match if the the kwarg match was None, as the
# lxc.present state will pass these kwargs set to None by default.
if kw_overrides_match is None:
return profile_match
return kw_overrides_match
path = select('path')
if exists(name, path=path):
raise CommandExecutionError(
'Container \'{0}\' already exists'.format(name)
)
tvg = select('vgname')
vgname = tvg if tvg else __salt__['config.get']('lxc.vgname')
# The 'template' and 'image' params conflict
template = select('template')
image = select('image')
if template and image:
raise SaltInvocationError(
'Only one of \'template\' and \'image\' is permitted'
)
elif not any((template, image, profile)):
raise SaltInvocationError(
'At least one of \'template\', \'image\', and \'profile\' is '
'required'
)
options = select('options') or {}
backing = select('backing')
if vgname and not backing:
backing = 'lvm'
lvname = select('lvname')
thinpool = select('thinpool')
fstype = select('fstype')
size = select('size', '1G')
zfsroot = select('zfsroot')
if backing in ('dir', 'overlayfs', 'btrfs', 'zfs'):
fstype = None
size = None
# some backends won't support some parameters
if backing in ('aufs', 'dir', 'overlayfs', 'btrfs'):
lvname = vgname = thinpool = None
if image:
img_tar = __salt__['cp.cache_file'](image)
template = os.path.join(
os.path.dirname(salt.__file__),
'templates',
'lxc',
'salt_tarball')
options['imgtar'] = img_tar
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
if not os.path.exists(path):
os.makedirs(path)
if config:
cmd += ' -f {0}'.format(config)
if template:
cmd += ' -t {0}'.format(template)
if backing:
backing = backing.lower()
cmd += ' -B {0}'.format(backing)
if backing in ('zfs',):
if zfsroot:
cmd += ' --zfsroot {0}'.format(zfsroot)
if backing in ('lvm',):
if lvname:
cmd += ' --lvname {0}'.format(lvname)
if vgname:
cmd += ' --vgname {0}'.format(vgname)
if thinpool:
cmd += ' --thinpool {0}'.format(thinpool)
if backing not in ('dir', 'overlayfs'):
if fstype:
cmd += ' --fstype {0}'.format(fstype)
if size:
cmd += ' --fssize {0}'.format(size)
if options:
if template == 'download':
missing_deps = [x for x in download_template_deps
if x not in options]
if missing_deps:
raise SaltInvocationError(
'Missing params in \'options\' dict: {0}'
.format(', '.join(missing_deps))
)
cmd += ' --'
for key, val in six.iteritems(options):
cmd += ' --{0} {1}'.format(key, val)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
# please do not merge extra conflicting stuff
# inside those two line (ret =, return)
return _after_ignition_network_profile(cmd,
ret,
name,
network_profile,
path,
nic_opts)
def clone(name,
orig,
profile=None,
network_profile=None,
nic_opts=None,
**kwargs):
'''
Create a new container as a clone of another container
name
Name of the container
orig
Name of the original container to be cloned
profile
Profile to use in container cloning (see
:mod:`lxc.get_container_profile
<salt.modules.lxc.get_container_profile>`). Values in a profile will be
overridden by the **Container Cloning Arguments** listed below.
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
**Container Cloning Arguments**
snapshot
Use Copy On Write snapshots (LVM)
size : 1G
Size of the volume to create. Only applicable if ``backing=lvm``.
backing
The type of storage to use. Set to ``lvm`` to use an LVM group.
Defaults to filesystem within /var/lib/lxc.
network_profile
Network profile to use for container
.. versionadded:: 2015.8.0
nic_opts
give extra opts overriding network profile values
.. versionadded:: 2015.8.0
CLI Examples:
.. code-block:: bash
salt '*' lxc.clone myclone orig=orig_container
salt '*' lxc.clone myclone orig=orig_container snapshot=True
'''
profile = get_container_profile(copy.deepcopy(profile))
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, None)
profile_match = profile.pop(key, default)
# let kwarg overrides be the preferred choice
if kw_overrides_match is None:
return profile_match
return kw_overrides_match
path = select('path')
if exists(name, path=path):
raise CommandExecutionError(
'Container \'{0}\' already exists'.format(name)
)
_ensure_exists(orig, path=path)
if state(orig, path=path) != 'stopped':
raise CommandExecutionError(
'Container \'{0}\' must be stopped to be cloned'.format(orig)
)
backing = select('backing')
snapshot = select('snapshot')
if backing in ('dir',):
snapshot = False
if not snapshot:
snapshot = ''
else:
snapshot = '-s'
size = select('size', '1G')
if backing in ('dir', 'overlayfs', 'btrfs'):
size = None
# LXC commands and options changed in 2.0 - CF issue #34086 for details
if _LooseVersion(version()) >= _LooseVersion('2.0'):
# https://linuxcontainers.org/lxc/manpages//man1/lxc-copy.1.html
cmd = 'lxc-copy'
cmd += ' {0} -n {1} -N {2}'.format(snapshot, orig, name)
else:
# https://linuxcontainers.org/lxc/manpages//man1/lxc-clone.1.html
cmd = 'lxc-clone'
cmd += ' {0} -o {1} -n {2}'.format(snapshot, orig, name)
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
if not os.path.exists(path):
os.makedirs(path)
if backing:
backing = backing.lower()
cmd += ' -B {0}'.format(backing)
if backing not in ('dir', 'overlayfs'):
if size:
cmd += ' -L {0}'.format(size)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
# please do not merge extra conflicting stuff
# inside those two line (ret =, return)
return _after_ignition_network_profile(cmd,
ret,
name,
network_profile,
path,
nic_opts)
def ls_(active=None, cache=True, path=None):
'''
Return a list of the containers available on the minion
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
active
If ``True``, return only active (i.e. running) containers
.. versionadded:: 2015.5.0
CLI Example:
.. code-block:: bash
salt '*' lxc.ls
salt '*' lxc.ls active=True
'''
contextvar = 'lxc.ls{0}'.format(path)
if active:
contextvar += '.active'
if cache and (contextvar in __context__):
return __context__[contextvar]
else:
ret = []
cmd = 'lxc-ls'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
if active:
cmd += ' --active'
output = __salt__['cmd.run_stdout'](cmd, python_shell=False)
for line in output.splitlines():
ret.extend(line.split())
__context__[contextvar] = ret
return ret
def list_(extra=False, limit=None, path=None):
'''
List containers classified by state
extra
Also get per-container specific info. This will change the return data.
Instead of returning a list of containers, a dictionary of containers
and each container's output from :mod:`lxc.info
<salt.modules.lxc.info>`.
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
limit
Return output matching a specific state (**frozen**, **running**, or
**stopped**).
.. versionadded:: 2015.5.0
CLI Examples:
.. code-block:: bash
salt '*' lxc.list
salt '*' lxc.list extra=True
salt '*' lxc.list limit=running
'''
ctnrs = ls_(path=path)
if extra:
stopped = {}
frozen = {}
running = {}
else:
stopped = []
frozen = []
running = []
ret = {'running': running,
'stopped': stopped,
'frozen': frozen}
for container in ctnrs:
cmd = 'lxc-info'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0}'.format(container)
c_info = __salt__['cmd.run'](
cmd,
python_shell=False,
output_loglevel='debug'
)
c_state = None
for line in c_info.splitlines():
stat = line.split(':')
if stat[0] in ('State', 'state'):
c_state = stat[1].strip()
break
if not c_state or (limit is not None and c_state.lower() != limit):
continue
if extra:
infos = info(container, path=path)
method = 'update'
value = {container: infos}
else:
method = 'append'
value = container
if c_state == 'STOPPED':
getattr(stopped, method)(value)
continue
if c_state == 'FROZEN':
getattr(frozen, method)(value)
continue
if c_state == 'RUNNING':
getattr(running, method)(value)
continue
if limit is not None:
return ret.get(limit, {} if extra else [])
return ret
def _change_state(cmd,
name,
expected,
stdin=_marker,
stdout=_marker,
stderr=_marker,
with_communicate=_marker,
use_vt=_marker,
path=None):
pre = state(name, path=path)
if pre == expected:
return {'result': True,
'state': {'old': expected, 'new': expected},
'comment': 'Container \'{0}\' already {1}'
.format(name, expected)}
if cmd == 'lxc-destroy':
# Kill the container first
scmd = 'lxc-stop'
if path:
scmd += ' -P {0}'.format(pipes.quote(path))
scmd += ' -k -n {0}'.format(name)
__salt__['cmd.run'](scmd,
python_shell=False)
if path and ' -P ' not in cmd:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0}'.format(name)
# certain lxc commands need to be taken with care (lxc-start)
# as te command itself mess with double forks; we must not
# communicate with it, but just wait for the exit status
pkwargs = {'python_shell': False,
'redirect_stderr': True,
'with_communicate': with_communicate,
'use_vt': use_vt,
'stdin': stdin,
'stdout': stdout}
for i in [a for a in pkwargs]:
val = pkwargs[i]
if val is _marker:
pkwargs.pop(i, None)
_cmdout = __salt__['cmd.run_all'](cmd, **pkwargs)
if _cmdout['retcode'] != 0:
raise CommandExecutionError(
'Error changing state for container \'{0}\' using command '
'\'{1}\': {2}'.format(name, cmd, _cmdout['stdout'])
)
if expected is not None:
# some commands do not wait, so we will
rcmd = 'lxc-wait'
if path:
rcmd += ' -P {0}'.format(pipes.quote(path))
rcmd += ' -n {0} -s {1}'.format(name, expected.upper())
__salt__['cmd.run'](rcmd, python_shell=False, timeout=30)
_clear_context()
post = state(name, path=path)
ret = {'result': post == expected,
'state': {'old': pre, 'new': post}}
return ret
def _ensure_exists(name, path=None):
'''
Raise an exception if the container does not exist
'''
if not exists(name, path=path):
raise CommandExecutionError(
'Container \'{0}\' does not exist'.format(name)
)
def _ensure_running(name, no_start=False, path=None):
'''
If the container is not currently running, start it. This function returns
the state that the container was in before changing
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
'''
_ensure_exists(name, path=path)
pre = state(name, path=path)
if pre == 'running':
# This will be a no-op but running the function will give us a pretty
# return dict.
return start(name, path=path)
elif pre == 'stopped':
if no_start:
raise CommandExecutionError(
'Container \'{0}\' is not running'.format(name)
)
return start(name, path=path)
elif pre == 'frozen':
if no_start:
raise CommandExecutionError(
'Container \'{0}\' is not running'.format(name)
)
return unfreeze(name, path=path)
def restart(name, path=None, lxc_config=None, force=False):
'''
.. versionadded:: 2015.5.0
Restart the named container. If the container was not running, the
container will merely be started.
name
The name of the container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
lxc_config
path to a lxc config file
config file will be guessed from container name otherwise
.. versionadded:: 2015.8.0
force : False
If ``True``, the container will be force-stopped instead of gracefully
shut down
CLI Example:
.. code-block:: bash
salt myminion lxc.restart name
'''
_ensure_exists(name, path=path)
orig_state = state(name, path=path)
if orig_state != 'stopped':
stop(name, kill=force, path=path)
ret = start(name, path=path, lxc_config=lxc_config)
ret['state']['old'] = orig_state
if orig_state != 'stopped':
ret['restarted'] = True
return ret
def start(name, **kwargs):
'''
Start the named container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
lxc_config
path to a lxc config file
config file will be guessed from container name otherwise
.. versionadded:: 2015.8.0
use_vt
run the command through VT
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.start name
'''
path = kwargs.get('path', None)
cpath = get_root_path(path)
lxc_config = kwargs.get('lxc_config', None)
cmd = 'lxc-start'
if not lxc_config:
lxc_config = os.path.join(cpath, name, 'config')
# we try to start, even without config, if global opts are there
if os.path.exists(lxc_config):
cmd += ' -f {0}'.format(pipes.quote(lxc_config))
cmd += ' -d'
_ensure_exists(name, path=path)
if state(name, path=path) == 'frozen':
raise CommandExecutionError(
'Container \'{0}\' is frozen, use lxc.unfreeze'.format(name)
)
# lxc-start daemonize itself violently, we must not communicate with it
use_vt = kwargs.get('use_vt', None)
with_communicate = kwargs.get('with_communicate', False)
return _change_state(cmd, name, 'running',
stdout=None,
stderr=None,
stdin=None,
with_communicate=with_communicate,
path=path,
use_vt=use_vt)
def stop(name, kill=False, path=None, use_vt=None):
'''
Stop the named container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
kill: False
Do not wait for the container to stop, kill all tasks in the container.
Older LXC versions will stop containers like this irrespective of this
argument.
.. versionchanged:: 2015.5.0
Default value changed to ``False``
use_vt
run the command through VT
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.stop name
'''
_ensure_exists(name, path=path)
orig_state = state(name, path=path)
if orig_state == 'frozen' and not kill:
# Gracefully stopping a frozen container is slower than unfreezing and
# then stopping it (at least in my testing), so if we're not
# force-stopping the container, unfreeze it first.
unfreeze(name, path=path)
cmd = 'lxc-stop'
if kill:
cmd += ' -k'
ret = _change_state(cmd, name, 'stopped', use_vt=use_vt, path=path)
ret['state']['old'] = orig_state
return ret
def freeze(name, **kwargs):
'''
Freeze the named container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
start : False
If ``True`` and the container is stopped, the container will be started
before attempting to freeze.
.. versionadded:: 2015.5.0
use_vt
run the command through VT
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.freeze name
'''
use_vt = kwargs.get('use_vt', None)
path = kwargs.get('path', None)
_ensure_exists(name, path=path)
orig_state = state(name, path=path)
start_ = kwargs.get('start', False)
if orig_state == 'stopped':
if not start_:
raise CommandExecutionError(
'Container \'{0}\' is stopped'.format(name)
)
start(name, path=path)
cmd = 'lxc-freeze'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
ret = _change_state(cmd, name, 'frozen', use_vt=use_vt, path=path)
if orig_state == 'stopped' and start_:
ret['state']['old'] = orig_state
ret['started'] = True
ret['state']['new'] = state(name, path=path)
return ret
def unfreeze(name, path=None, use_vt=None):
'''
Unfreeze the named container.
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
use_vt
run the command through VT
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.unfreeze name
'''
_ensure_exists(name, path=path)
if state(name, path=path) == 'stopped':
raise CommandExecutionError(
'Container \'{0}\' is stopped'.format(name)
)
cmd = 'lxc-unfreeze'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
return _change_state(cmd, name, 'running', path=path, use_vt=use_vt)
def destroy(name, stop=False, path=None):
'''
Destroy the named container.
.. warning::
Destroys all data associated with the container.
path
path to the container parent directory (default: /var/lib/lxc)
.. versionadded:: 2015.8.0
stop : False
If ``True``, the container will be destroyed even if it is
running/frozen.
.. versionchanged:: 2015.5.0
Default value changed to ``False``. This more closely matches the
behavior of ``lxc-destroy(1)``, and also makes it less likely that
an accidental command will destroy a running container that was
being used for important things.
CLI Examples:
.. code-block:: bash
salt '*' lxc.destroy foo
salt '*' lxc.destroy foo stop=True
'''
_ensure_exists(name, path=path)
if not stop and state(name, path=path) != 'stopped':
raise CommandExecutionError(
'Container \'{0}\' is not stopped'.format(name)
)
return _change_state('lxc-destroy', name, None, path=path)
# Compatibility between LXC and nspawn
remove = salt.utils.functools.alias_function(destroy, 'remove')
def state(name, path=None):
'''
Returns the state of a container.
path
path to the container parent directory (default: /var/lib/lxc)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.state name
'''
# Don't use _ensure_exists() here, it will mess with _change_state()
cachekey = 'lxc.state.{0}{1}'.format(name, path)
try:
return __context__[cachekey]
except KeyError:
if not exists(name, path=path):
__context__[cachekey] = None
else:
cmd = 'lxc-info'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0}'.format(name)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
if ret['retcode'] != 0:
_clear_context()
raise CommandExecutionError(
'Unable to get state of container \'{0}\''.format(name)
)
c_infos = ret['stdout'].splitlines()
c_state = None
for c_info in c_infos:
stat = c_info.split(':')
if stat[0].lower() == 'state':
c_state = stat[1].strip().lower()
break
__context__[cachekey] = c_state
return __context__[cachekey]
def get_parameter(name, parameter, path=None):
'''
Returns the value of a cgroup parameter for a container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.get_parameter container_name memory.limit_in_bytes
'''
_ensure_exists(name, path=path)
cmd = 'lxc-cgroup'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0} {1}'.format(name, parameter)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
if ret['retcode'] != 0:
raise CommandExecutionError(
'Unable to retrieve value for \'{0}\''.format(parameter)
)
return ret['stdout'].strip()
def set_parameter(name, parameter, value, path=None):
'''
Set the value of a cgroup parameter for a container.
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.set_parameter name parameter value
'''
if not exists(name, path=path):
return None
cmd = 'lxc-cgroup'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' -n {0} {1} {2}'.format(name, parameter, value)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
if ret['retcode'] != 0:
return False
else:
return True
def info(name, path=None):
'''
Returns information about a container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.info name
'''
cachekey = 'lxc.info.{0}{1}'.format(name, path)
try:
return __context__[cachekey]
except KeyError:
_ensure_exists(name, path=path)
cpath = get_root_path(path)
try:
conf_file = os.path.join(cpath, name, 'config')
except AttributeError:
conf_file = os.path.join(cpath, six.text_type(name), 'config')
if not os.path.isfile(conf_file):
raise CommandExecutionError(
'LXC config file {0} does not exist'.format(conf_file)
)
ret = {}
config = []
with salt.utils.files.fopen(conf_file) as fp_:
for line in fp_:
line = salt.utils.stringutils.to_unicode(line)
comps = [x.strip() for x in
line.split('#', 1)[0].strip().split('=', 1)]
if len(comps) == 2:
config.append(tuple(comps))
ifaces = []
current = None
for key, val in config:
if key == 'lxc.network.type':
current = {'type': val}
ifaces.append(current)
elif not current:
continue
elif key.startswith('lxc.network.'):
current[key.replace('lxc.network.', '', 1)] = val
if ifaces:
ret['nics'] = ifaces
ret['rootfs'] = next(
(x[1] for x in config if x[0] == 'lxc.rootfs'),
None
)
ret['state'] = state(name, path=path)
ret['ips'] = []
ret['public_ips'] = []
ret['private_ips'] = []
ret['public_ipv4_ips'] = []
ret['public_ipv6_ips'] = []
ret['private_ipv4_ips'] = []
ret['private_ipv6_ips'] = []
ret['ipv4_ips'] = []
ret['ipv6_ips'] = []
ret['size'] = None
ret['config'] = conf_file
if ret['state'] == 'running':
try:
limit = int(get_parameter(name, 'memory.limit_in_bytes'))
except (CommandExecutionError, TypeError, ValueError):
limit = 0
try:
usage = int(get_parameter(name, 'memory.usage_in_bytes'))
except (CommandExecutionError, TypeError, ValueError):
usage = 0
free = limit - usage
ret['memory_limit'] = limit
ret['memory_free'] = free
size = run_stdout(name, 'df /', path=path, python_shell=False)
# The size is the 2nd column of the last line
ret['size'] = size.splitlines()[-1].split()[1]
# First try iproute2
ip_cmd = run_all(
name, 'ip link show', path=path, python_shell=False)
if ip_cmd['retcode'] == 0:
ip_data = ip_cmd['stdout']
ip_cmd = run_all(
name, 'ip addr show', path=path, python_shell=False)
ip_data += '\n' + ip_cmd['stdout']
ip_data = salt.utils.network._interfaces_ip(ip_data)
else:
# That didn't work, try ifconfig
ip_cmd = run_all(
name, 'ifconfig', path=path, python_shell=False)
if ip_cmd['retcode'] == 0:
ip_data = \
salt.utils.network._interfaces_ifconfig(
ip_cmd['stdout'])
else:
# Neither was successful, give up
log.warning(
'Unable to run ip or ifconfig in container \'%s\'', name
)
ip_data = {}
ret['ipv4_ips'] = salt.utils.network.ip_addrs(
include_loopback=True,
interface_data=ip_data
)
ret['ipv6_ips'] = salt.utils.network.ip_addrs6(
include_loopback=True,
interface_data=ip_data
)
ret['ips'] = ret['ipv4_ips'] + ret['ipv6_ips']
for address in ret['ipv4_ips']:
if address == '127.0.0.1':
ret['private_ips'].append(address)
ret['private_ipv4_ips'].append(address)
elif salt.utils.cloud.is_public_ip(address):
ret['public_ips'].append(address)
ret['public_ipv4_ips'].append(address)
else:
ret['private_ips'].append(address)
ret['private_ipv4_ips'].append(address)
for address in ret['ipv6_ips']:
if address == '::1' or address.startswith('fe80'):
ret['private_ips'].append(address)
ret['private_ipv6_ips'].append(address)
else:
ret['public_ips'].append(address)
ret['public_ipv6_ips'].append(address)
for key in [x for x in ret if x == 'ips' or x.endswith('ips')]:
ret[key].sort(key=_ip_sort)
__context__[cachekey] = ret
return __context__[cachekey]
def set_password(name, users, password, encrypted=True, path=None):
'''
.. versionchanged:: 2015.5.0
Function renamed from ``set_pass`` to ``set_password``. Additionally,
this function now supports (and defaults to using) a password hash
instead of a plaintext password.
Set the password of one or more system users inside containers
users
Comma-separated list (or python list) of users to change password
password
Password to set for the specified user(s)
encrypted : True
If true, ``password`` must be a password hash. Set to ``False`` to set
a plaintext password (not recommended).
.. versionadded:: 2015.5.0
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.set_pass container-name root '$6$uJ2uAyLU$KoI67t8As/0fXtJOPcHKGXmUpcoYUcVR2K6x93walnShTCQvjRwq25yIkiCBOqgbfdKQSFnAo28/ek6716vEV1'
salt '*' lxc.set_pass container-name root foo encrypted=False
'''
def _bad_user_input():
raise SaltInvocationError('Invalid input for \'users\' parameter')
if not isinstance(users, list):
try:
users = users.split(',')
except AttributeError:
_bad_user_input()
if not users:
_bad_user_input()
failed_users = []
for user in users:
result = retcode(name,
'chpasswd{0}'.format(' -e' if encrypted else ''),
stdin=':'.join((user, password)),
python_shell=False,
path=path,
chroot_fallback=True,
output_loglevel='quiet')
if result != 0:
failed_users.append(user)
if failed_users:
raise CommandExecutionError(
'Password change failed for the following user(s): {0}'
.format(', '.join(failed_users))
)
return True
set_pass = salt.utils.functools.alias_function(set_password, 'set_pass')
def update_lxc_conf(name, lxc_conf, lxc_conf_unset, path=None):
'''
Edit LXC configuration options
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.update_lxc_conf ubuntu \\
lxc_conf="[{'network.ipv4.ip':'10.0.3.5'}]" \\
lxc_conf_unset="['lxc.utsname']"
'''
_ensure_exists(name, path=path)
cpath = get_root_path(path)
lxc_conf_p = os.path.join(cpath, name, 'config')
if not os.path.exists(lxc_conf_p):
raise SaltInvocationError(
'Configuration file {0} does not exist'.format(lxc_conf_p)
)
changes = {'edited': [], 'added': [], 'removed': []}
ret = {'changes': changes, 'result': True, 'comment': ''}
# do not use salt.utils.files.fopen !
with salt.utils.files.fopen(lxc_conf_p, 'r') as fic:
filtered_lxc_conf = []
for row in lxc_conf:
if not row:
continue
for conf in row:
filtered_lxc_conf.append((conf.strip(),
row[conf].strip()))
ret['comment'] = 'lxc.conf is up to date'
lines = []
orig_config = salt.utils.stringutils.to_unicode(fic.read())
for line in orig_config.splitlines():
if line.startswith('#') or not line.strip():
lines.append([line, ''])
else:
line = line.split('=')
index = line.pop(0)
val = (index.strip(), '='.join(line).strip())
if val not in lines:
lines.append(val)
for key, item in filtered_lxc_conf:
matched = False
for idx, line in enumerate(lines[:]):
if line[0] == key:
matched = True
lines[idx] = (key, item)
if '='.join(line[1:]).strip() != item.strip():
changes['edited'].append(
({line[0]: line[1:]}, {key: item}))
break
if not matched:
if (key, item) not in lines:
lines.append((key, item))
changes['added'].append({key: item})
dest_lxc_conf = []
# filter unset
if lxc_conf_unset:
for line in lines:
for opt in lxc_conf_unset:
if (
not line[0].startswith(opt) and
line not in dest_lxc_conf
):
dest_lxc_conf.append(line)
else:
changes['removed'].append(opt)
else:
dest_lxc_conf = lines
conf = ''
for key, val in dest_lxc_conf:
if not val:
conf += '{0}\n'.format(key)
else:
conf += '{0} = {1}\n'.format(key.strip(), val.strip())
conf_changed = conf != orig_config
chrono = datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S')
if conf_changed:
# DO NOT USE salt.utils.files.fopen here, i got (kiorky)
# problems with lxc configs which were wiped !
with salt.utils.files.fopen('{0}.{1}'.format(lxc_conf_p, chrono), 'w') as wfic:
wfic.write(salt.utils.stringutils.to_str(conf))
with salt.utils.files.fopen(lxc_conf_p, 'w') as wfic:
wfic.write(salt.utils.stringutils.to_str(conf))
ret['comment'] = 'Updated'
ret['result'] = True
if not any(changes[x] for x in changes):
# Ensure an empty changes dict if nothing was modified
ret['changes'] = {}
return ret
def set_dns(name, dnsservers=None, searchdomains=None, path=None):
'''
.. versionchanged:: 2015.5.0
The ``dnsservers`` and ``searchdomains`` parameters can now be passed
as a comma-separated list.
Update /etc/resolv.confo
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.set_dns ubuntu "['8.8.8.8', '4.4.4.4']"
'''
if dnsservers is None:
dnsservers = ['8.8.8.8', '4.4.4.4']
elif not isinstance(dnsservers, list):
try:
dnsservers = dnsservers.split(',')
except AttributeError:
raise SaltInvocationError(
'Invalid input for \'dnsservers\' parameter'
)
if searchdomains is None:
searchdomains = []
elif not isinstance(searchdomains, list):
try:
searchdomains = searchdomains.split(',')
except AttributeError:
raise SaltInvocationError(
'Invalid input for \'searchdomains\' parameter'
)
dns = ['nameserver {0}'.format(x) for x in dnsservers]
dns.extend(['search {0}'.format(x) for x in searchdomains])
dns = '\n'.join(dns) + '\n'
# we may be using resolvconf in the container
# We need to handle that case with care:
# - we create the resolv.conf runtime directory (the
# linked directory) as anyway it will be shadowed when the real
# runned tmpfs mountpoint will be mounted.
# ( /etc/resolv.conf -> ../run/resolvconf/resolv.conf)
# Indeed, it can save us in any other case (running, eg, in a
# bare chroot when repairing or preparing the container for
# operation.
# - We also teach resolvconf to use the aforementioned dns.
# - We finally also set /etc/resolv.conf in all cases
rstr = __salt__['test.random_hash']()
# no tmp here, apparmor won't let us execute !
script = '/sbin/{0}_dns.sh'.format(rstr)
DNS_SCRIPT = "\n".join([
# 'set -x',
'#!/usr/bin/env bash',
'if [ -h /etc/resolv.conf ];then',
' if [ "x$(readlink /etc/resolv.conf)"'
' = "x../run/resolvconf/resolv.conf" ];then',
' if [ ! -d /run/resolvconf/ ];then',
' mkdir -p /run/resolvconf',
' fi',
' cat > /etc/resolvconf/resolv.conf.d/head <<EOF',
dns,
'EOF',
'',
' fi',
'fi',
'cat > /etc/resolv.conf <<EOF',
dns,
'EOF',
''])
result = run_all(
name, 'tee {0}'.format(script), path=path,
stdin=DNS_SCRIPT, python_shell=True)
if result['retcode'] == 0:
result = run_all(
name, 'sh -c "chmod +x {0};{0}"'.format(script),
path=path, python_shell=True)
# blindly delete the setter file
run_all(name,
'sh -c \'if [ -f "{0}" ];then rm -f "{0}";fi\''.format(script),
path=path, python_shell=True)
if result['retcode'] != 0:
error = ('Unable to write to /etc/resolv.conf in container \'{0}\''
.format(name))
if result['stderr']:
error += ': {0}'.format(result['stderr'])
raise CommandExecutionError(error)
return True
def running_systemd(name, cache=True, path=None):
'''
Determine if systemD is running
path
path to the container parent
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.running_systemd ubuntu
'''
k = 'lxc.systemd.test.{0}{1}'.format(name, path)
ret = __context__.get(k, None)
if ret is None or not cache:
rstr = __salt__['test.random_hash']()
# no tmp here, apparmor won't let us execute !
script = '/sbin/{0}_testsystemd.sh'.format(rstr)
# ubuntu already had since trusty some bits of systemd but was
# still using upstart ...
# we need to be a bit more careful that just testing that systemd
# is present
_script = textwrap.dedent(
'''\
#!/usr/bin/env bash
set -x
if ! command -v systemctl 1>/dev/null 2>/dev/null;then exit 2;fi
for i in \\
/run/systemd/journal/dev-log\\
/run/systemd/journal/flushed\\
/run/systemd/journal/kernel-seqnum\\
/run/systemd/journal/socket\\
/run/systemd/journal/stdout\\
/var/run/systemd/journal/dev-log\\
/var/run/systemd/journal/flushed\\
/var/run/systemd/journal/kernel-seqnum\\
/var/run/systemd/journal/socket\\
/var/run/systemd/journal/stdout\\
;do\\
if test -e ${i};then exit 0;fi
done
if test -d /var/systemd/system;then exit 0;fi
exit 2
''')
result = run_all(
name, 'tee {0}'.format(script), path=path,
stdin=_script, python_shell=True)
if result['retcode'] == 0:
result = run_all(name,
'sh -c "chmod +x {0};{0}"'''.format(script),
path=path,
python_shell=True)
else:
raise CommandExecutionError(
'lxc {0} failed to copy initd tester'.format(name))
run_all(name,
'sh -c \'if [ -f "{0}" ];then rm -f "{0}";fi\''
''.format(script),
path=path,
ignore_retcode=True,
python_shell=True)
if result['retcode'] != 0:
error = ('Unable to determine if the container \'{0}\''
' was running systemd, assmuming it is not.'
''.format(name))
if result['stderr']:
error += ': {0}'.format(result['stderr'])
# only cache result if we got a known exit code
if result['retcode'] in (0, 2):
__context__[k] = ret = not result['retcode']
return ret
def systemd_running_state(name, path=None):
'''
Get the operational state of a systemd based container
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.systemd_running_state ubuntu
'''
try:
ret = run_all(name,
'systemctl is-system-running',
path=path,
ignore_retcode=True)['stdout']
except CommandExecutionError:
ret = ''
return ret
def test_sd_started_state(name, path=None):
'''
Test if a systemd container is fully started
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.test_sd_started_state ubuntu
'''
qstate = systemd_running_state(name, path=path)
if qstate in ('initializing', 'starting'):
return False
elif qstate == '':
return None
else:
return True
def test_bare_started_state(name, path=None):
'''
Test if a non systemd container is fully started
For now, it consists only to test if the container is attachable
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.test_bare_started_state ubuntu
'''
try:
ret = run_all(
name, 'ls', path=path, ignore_retcode=True
)['retcode'] == 0
except (CommandExecutionError,):
ret = None
return ret
def wait_started(name, path=None, timeout=300):
'''
Check that the system has fully inited
This is actually very important for systemD based containers
see https://github.com/saltstack/salt/issues/23847
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.wait_started ubuntu
'''
if not exists(name, path=path):
raise CommandExecutionError(
'Container {0} does does exists'.format(name))
if not state(name, path=path) == 'running':
raise CommandExecutionError(
'Container {0} is not running'.format(name))
ret = False
if running_systemd(name, path=path):
test_started = test_sd_started_state
logger = log.error
else:
test_started = test_bare_started_state
logger = log.debug
now = time.time()
expire = now + timeout
now = time.time()
started = test_started(name, path=path)
while time.time() < expire and not started:
time.sleep(0.3)
started = test_started(name, path=path)
if started is None:
logger(
'Assuming %s is started, although we failed to detect that'
' is fully started correctly', name)
ret = True
else:
ret = started
return ret
def _needs_install(name, path=None):
ret = 0
has_minion = retcode(name,
'which salt-minion',
path=path,
ignore_retcode=True)
# we assume that installing is when no minion is running
# but testing the executable presence is not enougth for custom
# installs where the bootstrap can do much more than installing
# the bare salt binaries.
if has_minion:
processes = run_stdout(name, "ps aux", path=path)
if 'salt-minion' not in processes:
ret = 1
else:
retcode(name, 'salt-call --local service.stop salt-minion')
else:
ret = 1
return ret
def bootstrap(name,
config=None,
approve_key=True,
install=True,
pub_key=None,
priv_key=None,
bootstrap_url=None,
force_install=False,
unconditional_install=False,
path=None,
bootstrap_delay=None,
bootstrap_args=None,
bootstrap_shell=None):
'''
Install and configure salt in a container.
config
Minion configuration options. By default, the ``master`` option is set
to the target host's master.
approve_key
Request a pre-approval of the generated minion key. Requires
that the salt-master be configured to either auto-accept all keys or
expect a signing request from the target host. Default: ``True``
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
pub_key
Explicit public key to pressed the minion with (optional).
This can be either a filepath or a string representing the key
priv_key
Explicit private key to pressed the minion with (optional).
This can be either a filepath or a string representing the key
bootstrap_delay
Delay in seconds between end of container creation and bootstrapping.
Useful when waiting for container to obtain a DHCP lease.
.. versionadded:: 2015.5.0
bootstrap_url
url, content or filepath to the salt bootstrap script
bootstrap_args
salt bootstrap script arguments
bootstrap_shell
shell to execute the script into
install
Whether to attempt a full installation of salt-minion if needed.
force_install
Force installation even if salt-minion is detected,
this is the way to run vendor bootstrap scripts even
if a salt minion is already present in the container
unconditional_install
Run the script even if the container seems seeded
CLI Examples:
.. code-block:: bash
salt 'minion' lxc.bootstrap container_name [config=config_data] \\
[approve_key=(True|False)] [install=(True|False)]
'''
wait_started(name, path=path)
if bootstrap_delay is not None:
try:
log.info('LXC %s: bootstrap_delay: %s', name, bootstrap_delay)
time.sleep(bootstrap_delay)
except TypeError:
# Bad input, but assume since a value was passed that
# a delay was desired, and sleep for 5 seconds
time.sleep(5)
c_info = info(name, path=path)
if not c_info:
return None
# default set here as we cannot set them
# in def as it can come from a chain of procedures.
if bootstrap_args:
# custom bootstrap args can be totally customized, and user could
# have inserted the placeholder for the config directory.
# For example, some salt bootstrap script do not use at all -c
if '{0}' not in bootstrap_args:
bootstrap_args += ' -c {0}'
else:
bootstrap_args = '-c {0}'
if not bootstrap_shell:
bootstrap_shell = 'sh'
orig_state = _ensure_running(name, path=path)
if not orig_state:
return orig_state
if not force_install:
needs_install = _needs_install(name, path=path)
else:
needs_install = True
seeded = retcode(name,
'test -e \'{0}\''.format(SEED_MARKER),
path=path,
chroot_fallback=True,
ignore_retcode=True) == 0
tmp = tempfile.mkdtemp()
if seeded and not unconditional_install:
ret = True
else:
ret = False
cfg_files = __salt__['seed.mkconfig'](
config, tmp=tmp, id_=name, approve_key=approve_key,
pub_key=pub_key, priv_key=priv_key)
if needs_install or force_install or unconditional_install:
if install:
rstr = __salt__['test.random_hash']()
configdir = '/var/tmp/.c_{0}'.format(rstr)
cmd = 'install -m 0700 -d {0}'.format(configdir)
if run_all(
name, cmd, path=path, python_shell=False
)['retcode'] != 0:
log.error('tmpdir %s creation failed %s', configdir, cmd)
return False
bs_ = __salt__['config.gather_bootstrap_script'](
bootstrap=bootstrap_url)
script = '/sbin/{0}_bootstrap.sh'.format(rstr)
copy_to(name, bs_, script, path=path)
result = run_all(name,
'sh -c "chmod +x {0}"'.format(script),
path=path,
python_shell=True)
copy_to(name, cfg_files['config'],
os.path.join(configdir, 'minion'),
path=path)
copy_to(name, cfg_files['privkey'],
os.path.join(configdir, 'minion.pem'),
path=path)
copy_to(name, cfg_files['pubkey'],
os.path.join(configdir, 'minion.pub'),
path=path)
bootstrap_args = bootstrap_args.format(configdir)
cmd = ('{0} {2} {1}'
.format(bootstrap_shell,
bootstrap_args.replace("'", "''"),
script))
# log ASAP the forged bootstrap command which can be wrapped
# out of the output in case of unexpected problem
log.info('Running %s in LXC container \'%s\'', cmd, name)
ret = retcode(name, cmd, output_loglevel='info',
path=path, use_vt=True) == 0
run_all(name,
'sh -c \'if [ -f "{0}" ];then rm -f "{0}";fi\''
''.format(script),
path=path,
ignore_retcode=True,
python_shell=True)
else:
ret = False
else:
minion_config = salt.config.minion_config(cfg_files['config'])
pki_dir = minion_config['pki_dir']
copy_to(name,
cfg_files['config'],
'/etc/salt/minion',
path=path)
copy_to(name,
cfg_files['privkey'],
os.path.join(pki_dir, 'minion.pem'),
path=path)
copy_to(name,
cfg_files['pubkey'],
os.path.join(pki_dir, 'minion.pub'),
path=path)
run(name,
'salt-call --local service.enable salt-minion',
path=path,
python_shell=False)
ret = True
shutil.rmtree(tmp)
if orig_state == 'stopped':
stop(name, path=path)
elif orig_state == 'frozen':
freeze(name, path=path)
# mark seeded upon successful install
if ret:
run(name,
'touch \'{0}\''.format(SEED_MARKER),
path=path,
python_shell=False)
return ret
def attachable(name, path=None):
'''
Return True if the named container can be attached to via the lxc-attach
command
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt 'minion' lxc.attachable ubuntu
'''
cachekey = 'lxc.attachable{0}{1}'.format(name, path)
try:
return __context__[cachekey]
except KeyError:
_ensure_exists(name, path=path)
# Can't use run() here because it uses attachable() and would
# endlessly recurse, resulting in a traceback
log.debug('Checking if LXC container %s is attachable', name)
cmd = 'lxc-attach'
if path:
cmd += ' -P {0}'.format(pipes.quote(path))
cmd += ' --clear-env -n {0} -- /usr/bin/env'.format(name)
result = __salt__['cmd.retcode'](cmd,
python_shell=False,
output_loglevel='quiet',
ignore_retcode=True) == 0
__context__[cachekey] = result
return __context__[cachekey]
def _run(name,
cmd,
output=None,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=None,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
Common logic for lxc.run functions
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
'''
orig_state = state(name, path=path)
try:
if attachable(name, path=path):
ret = __salt__['container_resource.run'](
name,
cmd,
path=path,
container_type=__virtualname__,
exec_driver=EXEC_DRIVER,
output=output,
no_start=no_start,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
ignore_retcode=ignore_retcode,
use_vt=use_vt,
keep_env=keep_env)
else:
if not chroot_fallback:
raise CommandExecutionError(
'{0} is not attachable.'.format(name))
rootfs = info(name, path=path).get('rootfs')
# Set context var to make cmd.run_chroot run cmd.run instead of
# cmd.run_all.
__context__['cmd.run_chroot.func'] = __salt__['cmd.run']
ret = __salt__['cmd.run_chroot'](rootfs,
cmd,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
ignore_retcode=ignore_retcode)
except Exception:
raise
finally:
# Make sure we honor preserve_state, even if there was an exception
new_state = state(name, path=path)
if preserve_state:
if orig_state == 'stopped' and new_state != 'stopped':
stop(name, path=path)
elif orig_state == 'frozen' and new_state != 'frozen':
freeze(name, start=True, path=path)
if output in (None, 'all'):
return ret
else:
return ret[output]
def run(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.8.0
Run :mod:`cmd.run <salt.modules.cmdmod.run>` within a container
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed in stderr if the command being run
does not exist. If no output is returned using this function, try using
:mod:`lxc.run_stderr <salt.modules.lxc.run_stderr>` or
:mod:`lxc.run_all <salt.modules.lxc.run_all>`.
name
Name of the container in which to run the command
cmd
Command to run
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console. Assumes
``output=all``.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
CLI Example:
.. code-block:: bash
salt myminion lxc.run mycontainer 'ifconfig -a'
'''
return _run(name,
cmd,
path=path,
output=None,
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def run_stdout(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.5.0
Run :mod:`cmd.run_stdout <salt.modules.cmdmod.run_stdout>` within a container
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed in stderr if the command being run
does not exist. If no output is returned using this function, try using
:mod:`lxc.run_stderr <salt.modules.lxc.run_stderr>` or
:mod:`lxc.run_all <salt.modules.lxc.run_all>`.
name
Name of the container in which to run the command
cmd
Command to run
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console
``output=all``.
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
CLI Example:
.. code-block:: bash
salt myminion lxc.run_stdout mycontainer 'ifconfig -a'
'''
return _run(name,
cmd,
path=path,
output='stdout',
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def run_stderr(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.5.0
Run :mod:`cmd.run_stderr <salt.modules.cmdmod.run_stderr>` within a container
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed if the command being run does not
exist.
name
Name of the container in which to run the command
cmd
Command to run
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console
``output=all``.
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
CLI Example:
.. code-block:: bash
salt myminion lxc.run_stderr mycontainer 'ip addr show'
'''
return _run(name,
cmd,
path=path,
output='stderr',
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def retcode(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.5.0
Run :mod:`cmd.retcode <salt.modules.cmdmod.retcode>` within a container
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed in stderr if the command being run
does not exist. If the retcode is nonzero and not what was expected,
try using :mod:`lxc.run_stderr <salt.modules.lxc.run_stderr>`
or :mod:`lxc.run_all <salt.modules.lxc.run_all>`.
name
Name of the container in which to run the command
cmd
Command to run
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console
``output=all``.
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
CLI Example:
.. code-block:: bash
salt myminion lxc.retcode mycontainer 'ip addr show'
'''
return _run(name,
cmd,
output='retcode',
path=path,
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def run_all(name,
cmd,
no_start=False,
preserve_state=True,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
path=None,
ignore_retcode=False,
chroot_fallback=False,
keep_env='http_proxy,https_proxy,no_proxy'):
'''
.. versionadded:: 2015.5.0
Run :mod:`cmd.run_all <salt.modules.cmdmod.run_all>` within a container
.. note::
While the command is run within the container, it is initiated from the
host. Therefore, the PID in the return dict is from the host, not from
the container.
.. warning::
Many shell builtins do not work, failing with stderr similar to the
following:
.. code-block:: bash
lxc_container: No such file or directory - failed to exec 'command'
The same error will be displayed in stderr if the command being run
does not exist.
name
Name of the container in which to run the command
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
cmd
Command to run
no_start : False
If the container is not running, don't start it
preserve_state : True
After running the command, return the container to its previous state
stdin : None
Standard input to be used for the command
output_loglevel : debug
Level at which to log the output from the command. Set to ``quiet`` to
suppress logging.
use_vt : False
Use SaltStack's utils.vt to stream output to console
``output=all``.
keep_env : http_proxy,https_proxy,no_proxy
A list of env vars to preserve. May be passed as commma-delimited list.
chroot_fallback
if the container is not running, try to run the command using chroot
default: false
CLI Example:
.. code-block:: bash
salt myminion lxc.run_all mycontainer 'ip addr show'
'''
return _run(name,
cmd,
output='all',
no_start=no_start,
preserve_state=preserve_state,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
path=path,
ignore_retcode=ignore_retcode,
chroot_fallback=chroot_fallback,
keep_env=keep_env)
def _get_md5(name, path):
'''
Get the MD5 checksum of a file from a container
'''
output = run_stdout(name, 'md5sum "{0}"'.format(path),
chroot_fallback=True,
ignore_retcode=True)
try:
return output.split()[0]
except IndexError:
# Destination file does not exist or could not be accessed
return None
def copy_to(name, source, dest, overwrite=False, makedirs=False, path=None):
'''
.. versionchanged:: 2015.8.0
Function renamed from ``lxc.cp`` to ``lxc.copy_to`` for consistency
with other container types. ``lxc.cp`` will continue to work, however.
For versions 2015.2.x and earlier, use ``lxc.cp``.
Copy a file or directory from the host into a container
name
Container name
source
File to be copied to the container
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
dest
Destination on the container. Must be an absolute path.
.. versionchanged:: 2015.5.0
If the destination is a directory, the file will be copied into
that directory.
overwrite : False
Unless this option is set to ``True``, then if a file exists at the
location specified by the ``dest`` argument, an error will be raised.
.. versionadded:: 2015.8.0
makedirs : False
Create the parent directory on the container if it does not already
exist.
.. versionadded:: 2015.5.0
CLI Example:
.. code-block:: bash
salt 'minion' lxc.copy_to /tmp/foo /root/foo
salt 'minion' lxc.cp /tmp/foo /root/foo
'''
_ensure_running(name, no_start=True, path=path)
return __salt__['container_resource.copy_to'](
name,
source,
dest,
container_type=__virtualname__,
path=path,
exec_driver=EXEC_DRIVER,
overwrite=overwrite,
makedirs=makedirs)
cp = salt.utils.functools.alias_function(copy_to, 'cp')
def read_conf(conf_file, out_format='simple'):
'''
Read in an LXC configuration file. By default returns a simple, unsorted
dict, but can also return a more detailed structure including blank lines
and comments.
out_format:
set to 'simple' if you need the old and unsupported behavior.
This won't support the multiple lxc values (eg: multiple network nics)
CLI Examples:
.. code-block:: bash
salt 'minion' lxc.read_conf /etc/lxc/mycontainer.conf
salt 'minion' lxc.read_conf /etc/lxc/mycontainer.conf out_format=commented
'''
ret_commented = []
ret_simple = {}
with salt.utils.files.fopen(conf_file, 'r') as fp_:
for line in salt.utils.data.decode(fp_.readlines()):
if '=' not in line:
ret_commented.append(line)
continue
comps = line.split('=')
value = '='.join(comps[1:]).strip()
comment = None
if value.strip().startswith('#'):
vcomps = value.strip().split('#')
value = vcomps[1].strip()
comment = '#'.join(vcomps[1:]).strip()
ret_commented.append({comps[0].strip(): {
'value': value,
'comment': comment,
}})
else:
ret_commented.append({comps[0].strip(): value})
ret_simple[comps[0].strip()] = value
if out_format == 'simple':
return ret_simple
return ret_commented
def write_conf(conf_file, conf):
'''
Write out an LXC configuration file
This is normally only used internally. The format of the data structure
must match that which is returned from ``lxc.read_conf()``, with
``out_format`` set to ``commented``.
An example might look like:
.. code-block:: python
[
{'lxc.utsname': '$CONTAINER_NAME'},
'# This is a commented line\\n',
'\\n',
{'lxc.mount': '$CONTAINER_FSTAB'},
{'lxc.rootfs': {'comment': 'This is another test',
'value': 'This is another test'}},
'\\n',
{'lxc.network.type': 'veth'},
{'lxc.network.flags': 'up'},
{'lxc.network.link': 'br0'},
{'lxc.network.mac': '$CONTAINER_MACADDR'},
{'lxc.network.ipv4': '$CONTAINER_IPADDR'},
{'lxc.network.name': '$CONTAINER_DEVICENAME'},
]
CLI Example:
.. code-block:: bash
salt 'minion' lxc.write_conf /etc/lxc/mycontainer.conf \\
out_format=commented
'''
if not isinstance(conf, list):
raise SaltInvocationError('Configuration must be passed as a list')
# construct the content prior to write to the file
# to avoid half written configs
content = ''
for line in conf:
if isinstance(line, (six.text_type, six.string_types)):
content += line
elif isinstance(line, dict):
for key in list(line.keys()):
out_line = None
if isinstance(
line[key],
(six.text_type, six.string_types, six.integer_types, float)
):
out_line = ' = '.join((key, "{0}".format(line[key])))
elif isinstance(line[key], dict):
out_line = ' = '.join((key, line[key]['value']))
if 'comment' in line[key]:
out_line = ' # '.join((out_line, line[key]['comment']))
if out_line:
content += out_line
content += '\n'
with salt.utils.files.fopen(conf_file, 'w') as fp_:
fp_.write(salt.utils.stringutils.to_str(content))
return {}
def edit_conf(conf_file,
out_format='simple',
read_only=False,
lxc_config=None,
**kwargs):
'''
Edit an LXC configuration file. If a setting is already present inside the
file, its value will be replaced. If it does not exist, it will be appended
to the end of the file. Comments and blank lines will be kept in-tact if
they already exist in the file.
out_format:
Set to simple if you need backward compatibility (multiple items for a
simple key is not supported)
read_only:
return only the edited configuration without applying it
to the underlying lxc configuration file
lxc_config:
List of dict containning lxc configuration items
For network configuration, you also need to add the device it belongs
to, otherwise it will default to eth0.
Also, any change to a network parameter will result in the whole
network reconfiguration to avoid mismatchs, be aware of that !
After the file is edited, its contents will be returned. By default, it
will be returned in ``simple`` format, meaning an unordered dict (which
may not represent the actual file order). Passing in an ``out_format`` of
``commented`` will return a data structure which accurately represents the
order and content of the file.
CLI Example:
.. code-block:: bash
salt 'minion' lxc.edit_conf /etc/lxc/mycontainer.conf \\
out_format=commented lxc.network.type=veth
salt 'minion' lxc.edit_conf /etc/lxc/mycontainer.conf \\
out_format=commented \\
lxc_config="[{'lxc.network.name': 'eth0', \\
'lxc.network.ipv4': '1.2.3.4'},
{'lxc.network.name': 'eth2', \\
'lxc.network.ipv4': '1.2.3.5',\\
'lxc.network.gateway': '1.2.3.1'}]"
'''
data = []
try:
conf = read_conf(conf_file, out_format=out_format)
except Exception:
conf = []
if not lxc_config:
lxc_config = []
lxc_config = copy.deepcopy(lxc_config)
# search if we want to access net config
# in that case, we will replace all the net configuration
net_config = []
for lxc_kws in lxc_config + [kwargs]:
net_params = {}
for kwarg in [a for a in lxc_kws]:
if kwarg.startswith('__'):
continue
if kwarg.startswith('lxc.network.'):
net_params[kwarg] = lxc_kws[kwarg]
lxc_kws.pop(kwarg, None)
if net_params:
net_config.append(net_params)
nic_opts = salt.utils.odict.OrderedDict()
for params in net_config:
dev = params.get('lxc.network.name', DEFAULT_NIC)
dev_opts = nic_opts.setdefault(dev, salt.utils.odict.OrderedDict())
for param in params:
opt = param.replace('lxc.network.', '')
opt = {'hwaddr': 'mac'}.get(opt, opt)
dev_opts[opt] = params[param]
net_changes = []
if nic_opts:
net_changes = _config_list(conf, only_net=True,
**{'network_profile': DEFAULT_NIC,
'nic_opts': nic_opts})
if net_changes:
lxc_config.extend(net_changes)
for line in conf:
if not isinstance(line, dict):
data.append(line)
continue
else:
for key in list(line.keys()):
val = line[key]
if net_changes and key.startswith('lxc.network.'):
continue
found = False
for ix in range(len(lxc_config)):
kw = lxc_config[ix]
if key in kw:
found = True
data.append({key: kw[key]})
del kw[key]
if not found:
data.append({key: val})
for lxc_kws in lxc_config:
for kwarg in lxc_kws:
data.append({kwarg: lxc_kws[kwarg]})
if read_only:
return data
write_conf(conf_file, data)
return read_conf(conf_file, out_format)
def reboot(name, path=None):
'''
Reboot a container.
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Examples:
.. code-block:: bash
salt 'minion' lxc.reboot myvm
'''
ret = {'result': True,
'changes': {},
'comment': '{0} rebooted'.format(name)}
does_exist = exists(name, path=path)
if does_exist and (state(name, path=path) == 'running'):
try:
stop(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
ret['result'] = False
return ret
if does_exist and (state(name, path=path) != 'running'):
try:
start(name, path=path)
except (SaltInvocationError, CommandExecutionError) as exc:
ret['comment'] = 'Unable to stop container: {0}'.format(exc)
ret['result'] = False
return ret
ret['changes'][name] = 'rebooted'
return ret
def reconfigure(name,
cpu=None,
cpuset=None,
cpushare=None,
memory=None,
profile=None,
network_profile=None,
nic_opts=None,
bridge=None,
gateway=None,
autostart=None,
utsname=None,
rootfs=None,
path=None,
**kwargs):
'''
Reconfigure a container.
This only applies to a few property
name
Name of the container.
utsname
utsname of the container.
.. versionadded:: 2016.3.0
rootfs
rootfs of the container.
.. versionadded:: 2016.3.0
cpu
Select a random number of cpu cores and assign it to the cpuset, if the
cpuset option is set then this option will be ignored
cpuset
Explicitly define the cpus this container will be bound to
cpushare
cgroups cpu shares.
autostart
autostart container on reboot
memory
cgroups memory limit, in MB.
(0 for nolimit, None for old default 1024MB)
gateway
the ipv4 gateway to use
the default does nothing more than lxcutils does
bridge
the bridge to use
the default does nothing more than lxcutils does
nic
Network interfaces profile (defined in config or pillar).
nic_opts
Extra options for network interfaces, will override
``{"eth0": {"mac": "aa:bb:cc:dd:ee:ff", "ipv4": "10.1.1.1", "ipv6": "2001:db8::ff00:42:8329"}}``
or
``{"eth0": {"mac": "aa:bb:cc:dd:ee:ff", "ipv4": "10.1.1.1/24", "ipv6": "2001:db8::ff00:42:8329"}}``
path
path to the container parent
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt-call -lall mc_lxc_fork.reconfigure foobar nic_opts="{'eth1': {'mac': '00:16:3e:dd:ee:44'}}" memory=4
'''
changes = {}
cpath = get_root_path(path)
path = os.path.join(cpath, name, 'config')
ret = {'name': name,
'comment': 'config for {0} up to date'.format(name),
'result': True,
'changes': changes}
profile = get_container_profile(copy.deepcopy(profile))
kw_overrides = copy.deepcopy(kwargs)
def select(key, default=None):
kw_overrides_match = kw_overrides.pop(key, _marker)
profile_match = profile.pop(key, default)
# let kwarg overrides be the preferred choice
if kw_overrides_match is _marker:
return profile_match
return kw_overrides_match
if nic_opts is not None and not network_profile:
network_profile = DEFAULT_NIC
if autostart is not None:
autostart = select('autostart', autostart)
else:
autostart = 'keep'
if not utsname:
utsname = select('utsname', utsname)
if os.path.exists(path):
old_chunks = read_conf(path, out_format='commented')
make_kw = salt.utils.odict.OrderedDict([
('utsname', utsname),
('rootfs', rootfs),
('autostart', autostart),
('cpu', cpu),
('gateway', gateway),
('cpuset', cpuset),
('cpushare', cpushare),
('network_profile', network_profile),
('nic_opts', nic_opts),
('bridge', bridge)])
# match 0 and none as memory = 0 in lxc config is harmful
if memory:
make_kw['memory'] = memory
kw = salt.utils.odict.OrderedDict()
for key, val in six.iteritems(make_kw):
if val is not None:
kw[key] = val
new_cfg = _config_list(conf_tuples=old_chunks, **kw)
if new_cfg:
edit_conf(path, out_format='commented', lxc_config=new_cfg)
chunks = read_conf(path, out_format='commented')
if old_chunks != chunks:
ret['comment'] = '{0} lxc config updated'.format(name)
if state(name, path=path) == 'running':
cret = reboot(name, path=path)
ret['result'] = cret['result']
return ret
def apply_network_profile(name, network_profile, nic_opts=None, path=None):
'''
.. versionadded:: 2015.5.0
Apply a network profile to a container
network_profile
profile name or default values (dict)
nic_opts
values to override in defaults (dict)
indexed by nic card names
path
path to the container parent
.. versionadded:: 2015.8.0
CLI Examples:
.. code-block:: bash
salt 'minion' lxc.apply_network_profile web1 centos
salt 'minion' lxc.apply_network_profile web1 centos \\
nic_opts="{'eth0': {'mac': 'xx:xx:xx:xx:xx:xx'}}"
salt 'minion' lxc.apply_network_profile web1 \\
"{'eth0': {'mac': 'xx:xx:xx:xx:xx:yy'}}"
nic_opts="{'eth0': {'mac': 'xx:xx:xx:xx:xx:xx'}}"
The special case to disable use of ethernet nics:
.. code-block:: bash
salt 'minion' lxc.apply_network_profile web1 centos \\
"{eth0: {disable: true}}"
'''
cpath = get_root_path(path)
cfgpath = os.path.join(cpath, name, 'config')
before = []
with salt.utils.files.fopen(cfgpath, 'r') as fp_:
for line in fp_:
before.append(line)
lxcconfig = _LXCConfig(name=name, path=path)
old_net = lxcconfig._filter_data('lxc.network')
network_params = {}
for param in _network_conf(
conf_tuples=old_net,
network_profile=network_profile, nic_opts=nic_opts
):
network_params.update(param)
if network_params:
edit_conf(cfgpath, out_format='commented', **network_params)
after = []
with salt.utils.files.fopen(cfgpath, 'r') as fp_:
for line in fp_:
after.append(line)
diff = ''
for line in difflib.unified_diff(before,
after,
fromfile='before',
tofile='after'):
diff += line
return diff
def get_pid(name, path=None):
'''
Returns a container pid.
Throw an exception if the container isn't running.
CLI Example:
.. code-block:: bash
salt '*' lxc.get_pid name
'''
if name not in list_(limit='running', path=path):
raise CommandExecutionError('Container {0} is not running, can\'t determine PID'.format(name))
info = __salt__['cmd.run']('lxc-info -n {0}'.format(name)).split("\n")
pid = [line.split(':')[1].strip() for line in info if re.match(r'\s*PID', line)][0]
return pid
def add_veth(name, interface_name, bridge=None, path=None):
'''
Add a veth to a container.
Note : this function doesn't update the container config, just add the interface at runtime
name
Name of the container
interface_name
Name of the interface in the container
bridge
Name of the bridge to attach the interface to (facultative)
CLI Examples:
.. code-block:: bash
salt '*' lxc.add_veth container_name eth1 br1
salt '*' lxc.add_veth container_name eth1
'''
# Get container init PID
pid = get_pid(name, path=path)
# Generate a ramdom string for veth and ensure that is isn't present on the system
while True:
random_veth = 'veth'+''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(6))
if random_veth not in __salt__['network.interfaces']().keys():
break
# Check prerequisites
if not __salt__['file.directory_exists']('/var/run/'):
raise CommandExecutionError('Directory /var/run required for lxc.add_veth doesn\'t exists')
if not __salt__['file.file_exists']('/proc/{0}/ns/net'.format(pid)):
raise CommandExecutionError('Proc file for container {0} network namespace doesn\'t exists'.format(name))
if not __salt__['file.directory_exists']('/var/run/netns'):
__salt__['file.mkdir']('/var/run/netns')
# Ensure that the symlink is up to date (change on container restart)
if __salt__['file.is_link']('/var/run/netns/{0}'.format(name)):
__salt__['file.remove']('/var/run/netns/{0}'.format(name))
__salt__['file.symlink']('/proc/{0}/ns/net'.format(pid), '/var/run/netns/{0}'.format(name))
# Ensure that interface doesn't exists
interface_exists = 0 == __salt__['cmd.retcode']('ip netns exec {netns} ip address list {interface}'.format(
netns=name,
interface=interface_name
))
if interface_exists:
raise CommandExecutionError('Interface {interface} already exists in {container}'.format(
interface=interface_name,
container=name
))
# Create veth and bring it up
if __salt__['cmd.retcode']('ip link add name {veth} type veth peer name {veth}_c'.format(veth=random_veth)) != 0:
raise CommandExecutionError('Error while creating the veth pair {0}'.format(random_veth))
if __salt__['cmd.retcode']('ip link set dev {0} up'.format(random_veth)) != 0:
raise CommandExecutionError('Error while bringing up host-side veth {0}'.format(random_veth))
# Attach it to the container
attached = 0 == __salt__['cmd.retcode']('ip link set dev {veth}_c netns {container} name {interface_name}'.format(
veth=random_veth,
container=name,
interface_name=interface_name
))
if not attached:
raise CommandExecutionError('Error while attaching the veth {veth} to container {container}'.format(
veth=random_veth,
container=name
))
__salt__['file.remove']('/var/run/netns/{0}'.format(name))
if bridge is not None:
__salt__['bridge.addif'](bridge, random_veth)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.