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/modules/lxc.py
|
state
|
python
|
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]
|
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
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/lxc.py#L2632-L2674
|
[
"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 _clear_context():\n '''\n Clear any lxc variables set in __context__\n '''\n for var in [x for x in __context__ if x.startswith('lxc.')]:\n log.trace('Clearing __context__[\\'%s\\']', var)\n __context__.pop(var, None)\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 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 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_parameter
|
python
|
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()
|
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
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/lxc.py#L2677-L2703
|
[
"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)
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 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
|
set_parameter
|
python
|
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
|
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
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/lxc.py#L2706-L2733
|
[
"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_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 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
|
info
|
python
|
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]
|
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
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/lxc.py#L2736-L2879
|
[
"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 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 get_parameter(name, parameter, path=None):\n '''\n Returns the value of a cgroup parameter for 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.get_parameter container_name memory.limit_in_bytes\n '''\n _ensure_exists(name, path=path)\n cmd = 'lxc-cgroup'\n if path:\n cmd += ' -P {0}'.format(pipes.quote(path))\n cmd += ' -n {0} {1}'.format(name, parameter)\n ret = __salt__['cmd.run_all'](cmd, python_shell=False)\n if ret['retcode'] != 0:\n raise CommandExecutionError(\n 'Unable to retrieve value for \\'{0}\\''.format(parameter)\n )\n return ret['stdout'].strip()\n",
"def is_public_ip(ip):\n '''\n Determines whether an IP address falls within one of the private IP ranges\n '''\n if ':' in ip:\n # ipv6\n if ip.startswith('fe80:'):\n # ipv6 link local\n return False\n return True\n addr = ip_to_int(ip)\n if 167772160 < addr < 184549375:\n # 10.0.0.0/8\n return False\n elif 3232235520 < addr < 3232301055:\n # 192.168.0.0/16\n return False\n elif 2886729728 < addr < 2887778303:\n # 172.16.0.0/12\n return False\n elif 2130706432 < addr < 2147483647:\n # 127.0.0.0/8\n return False\n return True\n",
"def run_stdout(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.run_stdout <salt.modules.cmdmod.run_stdout>` 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\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.run_stdout mycontainer 'ifconfig -a'\n '''\n return _run(name,\n cmd,\n path=path,\n output='stdout',\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 run_all(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.run_all <salt.modules.cmdmod.run_all>` within a container\n\n .. note::\n\n While the command is run within the container, it is initiated from the\n host. Therefore, the PID in the return dict is from the host, not from\n the 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.\n\n name\n Name of the container in which to run the command\n\n path\n path to the container parent\n default: /var/lib/lxc (system default)\n\n .. versionadded:: 2015.8.0\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 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.run_all mycontainer 'ip addr show'\n '''\n return _run(name,\n cmd,\n output='all',\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 path=path,\n ignore_retcode=ignore_retcode,\n chroot_fallback=chroot_fallback,\n keep_env=keep_env)\n",
"def ip_addrs(interface=None, include_loopback=False, interface_data=None):\n '''\n Returns a list of IPv4 addresses assigned to the host. 127.0.0.1 is\n ignored, unless 'include_loopback=True' is indicated. If 'interface' is\n provided, then only IP addresses from that interface will be returned.\n '''\n return _ip_addrs(interface, include_loopback, interface_data, 'inet')\n",
"def ip_addrs6(interface=None, include_loopback=False, interface_data=None):\n '''\n Returns a list of IPv6 addresses assigned to the host. ::1 is ignored,\n unless 'include_loopback=True' is indicated. If 'interface' is provided,\n then only IP addresses from that interface will be returned.\n '''\n return _ip_addrs(interface, include_loopback, interface_data, 'inet6')\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",
"def _interfaces_ip(out):\n '''\n Uses ip to return a dictionary of interfaces with various information about\n each (up/down state, ip address, netmask, and hwaddr)\n '''\n ret = dict()\n\n def parse_network(value, cols):\n '''\n Return a tuple of ip, netmask, broadcast\n based on the current set of cols\n '''\n brd = None\n scope = None\n if '/' in value: # we have a CIDR in this address\n ip, cidr = value.split('/') # pylint: disable=C0103\n else:\n ip = value # pylint: disable=C0103\n cidr = 32\n\n if type_ == 'inet':\n mask = cidr_to_ipv4_netmask(int(cidr))\n if 'brd' in cols:\n brd = cols[cols.index('brd') + 1]\n elif type_ == 'inet6':\n mask = cidr\n if 'scope' in cols:\n scope = cols[cols.index('scope') + 1]\n return (ip, mask, brd, scope)\n\n groups = re.compile('\\r?\\n\\\\d').split(out)\n for group in groups:\n iface = None\n data = dict()\n\n for line in group.splitlines():\n if ' ' not in line:\n continue\n match = re.match(r'^\\d*:\\s+([\\w.\\-]+)(?:@)?([\\w.\\-]+)?:\\s+<(.+)>', line)\n if match:\n iface, parent, attrs = match.groups()\n if 'UP' in attrs.split(','):\n data['up'] = True\n else:\n data['up'] = False\n if parent:\n data['parent'] = parent\n continue\n\n cols = line.split()\n if len(cols) >= 2:\n type_, value = tuple(cols[0:2])\n iflabel = cols[-1:][0]\n if type_ in ('inet', 'inet6'):\n if 'secondary' not in cols:\n ipaddr, netmask, broadcast, scope = parse_network(value, cols)\n if type_ == 'inet':\n if 'inet' not in data:\n data['inet'] = list()\n addr_obj = dict()\n addr_obj['address'] = ipaddr\n addr_obj['netmask'] = netmask\n addr_obj['broadcast'] = broadcast\n addr_obj['label'] = iflabel\n data['inet'].append(addr_obj)\n elif type_ == 'inet6':\n if 'inet6' not in data:\n data['inet6'] = list()\n addr_obj = dict()\n addr_obj['address'] = ipaddr\n addr_obj['prefixlen'] = netmask\n addr_obj['scope'] = scope\n data['inet6'].append(addr_obj)\n else:\n if 'secondary' not in data:\n data['secondary'] = list()\n ip_, mask, brd, scp = parse_network(value, cols)\n data['secondary'].append({\n 'type': type_,\n 'address': ip_,\n 'netmask': mask,\n 'broadcast': brd,\n 'label': iflabel,\n })\n del ip_, mask, brd, scp\n elif type_.startswith('link'):\n data['hwaddr'] = value\n if iface:\n ret[iface] = data\n del iface, data\n return ret\n",
"def _interfaces_ifconfig(out):\n '''\n Uses ifconfig to return a dictionary of interfaces with various information\n about each (up/down state, ip address, netmask, and hwaddr)\n '''\n ret = dict()\n\n piface = re.compile(r'^([^\\s:]+)')\n pmac = re.compile('.*?(?:HWaddr|ether|address:|lladdr) ([0-9a-fA-F:]+)')\n if salt.utils.platform.is_sunos():\n pip = re.compile(r'.*?(?:inet\\s+)([0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+)(.*)')\n pip6 = re.compile('.*?(?:inet6 )([0-9a-fA-F:]+)')\n pmask6 = re.compile(r'.*?(?:inet6 [0-9a-fA-F:]+/(\\d+)).*')\n else:\n pip = re.compile(r'.*?(?:inet addr:|inet [^\\d]*)(.*?)\\s')\n pip6 = re.compile('.*?(?:inet6 addr: (.*?)/|inet6 )([0-9a-fA-F:]+)')\n pmask6 = re.compile(r'.*?(?:inet6 addr: [0-9a-fA-F:]+/(\\d+)|prefixlen (\\d+))(?: Scope:([a-zA-Z]+)| scopeid (0x[0-9a-fA-F]))?')\n pmask = re.compile(r'.*?(?:Mask:|netmask )(?:((?:0x)?[0-9a-fA-F]{8})|([\\d\\.]+))')\n pupdown = re.compile('UP')\n pbcast = re.compile(r'.*?(?:Bcast:|broadcast )([\\d\\.]+)')\n\n groups = re.compile('\\r?\\n(?=\\\\S)').split(out)\n for group in groups:\n data = dict()\n iface = ''\n updown = False\n for line in group.splitlines():\n miface = piface.match(line)\n mmac = pmac.match(line)\n mip = pip.match(line)\n mip6 = pip6.match(line)\n mupdown = pupdown.search(line)\n if miface:\n iface = miface.group(1)\n if mmac:\n data['hwaddr'] = mmac.group(1)\n if salt.utils.platform.is_sunos():\n expand_mac = []\n for chunk in data['hwaddr'].split(':'):\n expand_mac.append('0{0}'.format(chunk) if len(chunk) < 2 else '{0}'.format(chunk))\n data['hwaddr'] = ':'.join(expand_mac)\n if mip:\n if 'inet' not in data:\n data['inet'] = list()\n addr_obj = dict()\n addr_obj['address'] = mip.group(1)\n mmask = pmask.match(line)\n if mmask:\n if mmask.group(1):\n mmask = _number_of_set_bits_to_ipv4_netmask(\n int(mmask.group(1), 16))\n else:\n mmask = mmask.group(2)\n addr_obj['netmask'] = mmask\n mbcast = pbcast.match(line)\n if mbcast:\n addr_obj['broadcast'] = mbcast.group(1)\n data['inet'].append(addr_obj)\n if mupdown:\n updown = True\n if mip6:\n if 'inet6' not in data:\n data['inet6'] = list()\n addr_obj = dict()\n addr_obj['address'] = mip6.group(1) or mip6.group(2)\n mmask6 = pmask6.match(line)\n if mmask6:\n addr_obj['prefixlen'] = mmask6.group(1) or mmask6.group(2)\n if not salt.utils.platform.is_sunos():\n ipv6scope = mmask6.group(3) or mmask6.group(4)\n addr_obj['scope'] = ipv6scope.lower() if ipv6scope is not None else ipv6scope\n # SunOS sometimes has ::/0 as inet6 addr when using addrconf\n if not salt.utils.platform.is_sunos() \\\n or addr_obj['address'] != '::' \\\n and addr_obj['prefixlen'] != 0:\n data['inet6'].append(addr_obj)\n data['up'] = updown\n if iface in ret:\n # SunOS optimization, where interfaces occur twice in 'ifconfig -a'\n # output with the same name: for ipv4 and then for ipv6 addr family.\n # Every instance has it's own 'UP' status and we assume that ipv4\n # status determines global interface status.\n #\n # merge items with higher priority for older values\n # after that merge the inet and inet6 sub items for both\n ret[iface] = dict(list(data.items()) + list(ret[iface].items()))\n if 'inet' in data:\n ret[iface]['inet'].extend(x for x in data['inet'] if x not in ret[iface]['inet'])\n if 'inet6' in data:\n ret[iface]['inet6'].extend(x for x in data['inet6'] if x not in ret[iface]['inet6'])\n else:\n ret[iface] = data\n del data\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 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 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
|
set_password
|
python
|
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
|
.. 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
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/lxc.py#L2882-L2945
|
[
"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 _bad_user_input():\n raise SaltInvocationError('Invalid input for \\'users\\' parameter')\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 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]
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
|
update_lxc_conf
|
python
|
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
|
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']"
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/lxc.py#L2951-L3051
|
[
"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 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 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 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
|
set_dns
|
python
|
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
|
.. 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']"
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/lxc.py#L3054-L3147
|
[
"def run_all(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.run_all <salt.modules.cmdmod.run_all>` within a container\n\n .. note::\n\n While the command is run within the container, it is initiated from the\n host. Therefore, the PID in the return dict is from the host, not from\n the 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.\n\n name\n Name of the container in which to run the command\n\n path\n path to the container parent\n default: /var/lib/lxc (system default)\n\n .. versionadded:: 2015.8.0\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 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.run_all mycontainer 'ip addr show'\n '''\n return _run(name,\n cmd,\n output='all',\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 path=path,\n ignore_retcode=ignore_retcode,\n chroot_fallback=chroot_fallback,\n keep_env=keep_env)\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 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 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
|
running_systemd
|
python
|
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
|
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
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/lxc.py#L3150-L3224
|
[
"def run_all(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.run_all <salt.modules.cmdmod.run_all>` within a container\n\n .. note::\n\n While the command is run within the container, it is initiated from the\n host. Therefore, the PID in the return dict is from the host, not from\n the 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.\n\n name\n Name of the container in which to run the command\n\n path\n path to the container parent\n default: /var/lib/lxc (system default)\n\n .. versionadded:: 2015.8.0\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 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.run_all mycontainer 'ip addr show'\n '''\n return _run(name,\n cmd,\n output='all',\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 path=path,\n ignore_retcode=ignore_retcode,\n chroot_fallback=chroot_fallback,\n keep_env=keep_env)\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 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 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
|
systemd_running_state
|
python
|
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
|
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
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/lxc.py#L3227-L3251
|
[
"def run_all(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.run_all <salt.modules.cmdmod.run_all>` within a container\n\n .. note::\n\n While the command is run within the container, it is initiated from the\n host. Therefore, the PID in the return dict is from the host, not from\n the 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.\n\n name\n Name of the container in which to run the command\n\n path\n path to the container parent\n default: /var/lib/lxc (system default)\n\n .. versionadded:: 2015.8.0\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 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.run_all mycontainer 'ip addr show'\n '''\n return _run(name,\n cmd,\n output='all',\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 path=path,\n ignore_retcode=ignore_retcode,\n chroot_fallback=chroot_fallback,\n keep_env=keep_env)\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 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 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
|
wait_started
|
python
|
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
|
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
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/lxc.py#L3311-L3359
|
[
"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 running_systemd(name, cache=True, path=None):\n '''\n Determine if systemD is running\n\n path\n path to the container parent\n\n .. versionadded:: 2015.8.0\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' lxc.running_systemd ubuntu\n\n '''\n k = 'lxc.systemd.test.{0}{1}'.format(name, path)\n ret = __context__.get(k, None)\n if ret is None or not cache:\n rstr = __salt__['test.random_hash']()\n # no tmp here, apparmor won't let us execute !\n script = '/sbin/{0}_testsystemd.sh'.format(rstr)\n # ubuntu already had since trusty some bits of systemd but was\n # still using upstart ...\n # we need to be a bit more careful that just testing that systemd\n # is present\n _script = textwrap.dedent(\n '''\\\n #!/usr/bin/env bash\n set -x\n if ! command -v systemctl 1>/dev/null 2>/dev/null;then exit 2;fi\n for i in \\\\\n /run/systemd/journal/dev-log\\\\\n /run/systemd/journal/flushed\\\\\n /run/systemd/journal/kernel-seqnum\\\\\n /run/systemd/journal/socket\\\\\n /run/systemd/journal/stdout\\\\\n /var/run/systemd/journal/dev-log\\\\\n /var/run/systemd/journal/flushed\\\\\n /var/run/systemd/journal/kernel-seqnum\\\\\n /var/run/systemd/journal/socket\\\\\n /var/run/systemd/journal/stdout\\\\\n ;do\\\\\n if test -e ${i};then exit 0;fi\n done\n if test -d /var/systemd/system;then exit 0;fi\n exit 2\n ''')\n result = run_all(\n name, 'tee {0}'.format(script), path=path,\n stdin=_script, python_shell=True)\n if result['retcode'] == 0:\n result = run_all(name,\n 'sh -c \"chmod +x {0};{0}\"'''.format(script),\n path=path,\n python_shell=True)\n else:\n raise CommandExecutionError(\n 'lxc {0} failed to copy initd tester'.format(name))\n run_all(name,\n 'sh -c \\'if [ -f \"{0}\" ];then rm -f \"{0}\";fi\\''\n ''.format(script),\n path=path,\n ignore_retcode=True,\n python_shell=True)\n if result['retcode'] != 0:\n error = ('Unable to determine if the container \\'{0}\\''\n ' was running systemd, assmuming it is not.'\n ''.format(name))\n if result['stderr']:\n error += ': {0}'.format(result['stderr'])\n # only cache result if we got a known exit code\n if result['retcode'] in (0, 2):\n __context__[k] = ret = not result['retcode']\n return ret\n",
"def test_sd_started_state(name, path=None):\n\n '''\n Test if a systemd container is fully started\n\n path\n path to the container parent\n default: /var/lib/lxc (system default)\n\n .. versionadded:: 2015.8.0\n\n\n CLI Example:\n\n\n .. code-block:: bash\n\n salt myminion lxc.test_sd_started_state ubuntu\n\n '''\n qstate = systemd_running_state(name, path=path)\n if qstate in ('initializing', 'starting'):\n return False\n elif qstate == '':\n return None\n else:\n return True\n",
"def test_bare_started_state(name, path=None):\n '''\n Test if a non systemd container is fully started\n For now, it consists only to test if the container is attachable\n\n path\n path to the container parent\n default: /var/lib/lxc (system default)\n\n .. versionadded:: 2015.8.0\n\n\n CLI Example:\n\n .. code-block:: bash\n\n salt myminion lxc.test_bare_started_state ubuntu\n\n '''\n try:\n ret = run_all(\n name, 'ls', path=path, ignore_retcode=True\n )['retcode'] == 0\n except (CommandExecutionError,):\n ret = None\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 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 _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
|
attachable
|
python
|
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]
|
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
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/lxc.py#L3586-L3620
|
[
"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)
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 _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
|
_run
|
python
|
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]
|
Common logic for lxc.run functions
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/lxc.py#L3623-L3691
|
[
"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 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 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 freeze(name, **kwargs):\n '''\n Freeze 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 start : False\n If ``True`` and the container is stopped, the container will be started\n before attempting to freeze.\n\n .. versionadded:: 2015.5.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.freeze name\n '''\n use_vt = kwargs.get('use_vt', None)\n path = kwargs.get('path', None)\n _ensure_exists(name, path=path)\n orig_state = state(name, path=path)\n start_ = kwargs.get('start', False)\n if orig_state == 'stopped':\n if not start_:\n raise CommandExecutionError(\n 'Container \\'{0}\\' is stopped'.format(name)\n )\n start(name, path=path)\n cmd = 'lxc-freeze'\n if path:\n cmd += ' -P {0}'.format(pipes.quote(path))\n ret = _change_state(cmd, name, 'frozen', use_vt=use_vt, path=path)\n if orig_state == 'stopped' and start_:\n ret['state']['old'] = orig_state\n ret['started'] = True\n ret['state']['new'] = state(name, path=path)\n return ret\n",
"def attachable(name, path=None):\n '''\n Return True if the named container can be attached to via the lxc-attach\n command\n\n path\n path to the container parent\n default: /var/lib/lxc (system default)\n\n .. versionadded:: 2015.8.0\n\n CLI Example:\n\n .. code-block:: bash\n\n salt 'minion' lxc.attachable ubuntu\n '''\n cachekey = 'lxc.attachable{0}{1}'.format(name, path)\n try:\n return __context__[cachekey]\n except KeyError:\n _ensure_exists(name, path=path)\n # Can't use run() here because it uses attachable() and would\n # endlessly recurse, resulting in a traceback\n log.debug('Checking if LXC container %s is attachable', name)\n cmd = 'lxc-attach'\n if path:\n cmd += ' -P {0}'.format(pipes.quote(path))\n cmd += ' --clear-env -n {0} -- /usr/bin/env'.format(name)\n result = __salt__['cmd.retcode'](cmd,\n python_shell=False,\n output_loglevel='quiet',\n ignore_retcode=True) == 0\n __context__[cachekey] = result\n return __context__[cachekey]\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 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,
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
|
run
|
python
|
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)
|
.. 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'
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/lxc.py#L3694-L3780
|
[
"def _run(name,\n cmd,\n output=None,\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=None,\n keep_env='http_proxy,https_proxy,no_proxy'):\n '''\n Common logic for lxc.run functions\n\n path\n path to the container parent\n default: /var/lib/lxc (system default)\n\n .. versionadded:: 2015.8.0\n\n '''\n orig_state = state(name, path=path)\n try:\n if attachable(name, path=path):\n ret = __salt__['container_resource.run'](\n name,\n cmd,\n path=path,\n container_type=__virtualname__,\n exec_driver=EXEC_DRIVER,\n output=output,\n no_start=no_start,\n stdin=stdin,\n python_shell=python_shell,\n output_loglevel=output_loglevel,\n ignore_retcode=ignore_retcode,\n use_vt=use_vt,\n keep_env=keep_env)\n else:\n if not chroot_fallback:\n raise CommandExecutionError(\n '{0} is not attachable.'.format(name))\n rootfs = info(name, path=path).get('rootfs')\n # Set context var to make cmd.run_chroot run cmd.run instead of\n # cmd.run_all.\n __context__['cmd.run_chroot.func'] = __salt__['cmd.run']\n ret = __salt__['cmd.run_chroot'](rootfs,\n cmd,\n stdin=stdin,\n python_shell=python_shell,\n output_loglevel=output_loglevel,\n ignore_retcode=ignore_retcode)\n except Exception:\n raise\n finally:\n # Make sure we honor preserve_state, even if there was an exception\n new_state = state(name, path=path)\n if preserve_state:\n if orig_state == 'stopped' and new_state != 'stopped':\n stop(name, path=path)\n elif orig_state == 'frozen' and new_state != 'frozen':\n freeze(name, start=True, path=path)\n\n if output in (None, 'all'):\n return ret\n else:\n return ret[output]\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 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_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_md5
|
python
|
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
|
Get the MD5 checksum of a file from a container
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/lxc.py#L4141-L4152
| 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 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 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
|
copy_to
|
python
|
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)
|
.. 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
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/lxc.py#L4155-L4212
|
[
"def _ensure_running(name, no_start=False, path=None):\n '''\n If the container is not currently running, start it. This function returns\n the state that the container was in before changing\n\n path\n path to the container parent directory\n default: /var/lib/lxc (system)\n\n .. versionadded:: 2015.8.0\n '''\n _ensure_exists(name, path=path)\n pre = state(name, path=path)\n if pre == 'running':\n # This will be a no-op but running the function will give us a pretty\n # return dict.\n return start(name, path=path)\n elif pre == 'stopped':\n if no_start:\n raise CommandExecutionError(\n 'Container \\'{0}\\' is not running'.format(name)\n )\n return start(name, path=path)\n elif pre == 'frozen':\n if no_start:\n raise CommandExecutionError(\n 'Container \\'{0}\\' is not running'.format(name)\n )\n return unfreeze(name, path=path)\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 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
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
|
read_conf
|
python
|
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
|
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
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/lxc.py#L4218-L4259
|
[
"def decode(data, encoding=None, errors='strict', keep=False,\n normalize=False, preserve_dict_class=False, preserve_tuples=False,\n to_str=False):\n '''\n Generic function which will decode whichever type is passed, if necessary.\n Optionally use to_str=True to ensure strings are str types and not unicode\n on Python 2.\n\n If `strict` is True, and `keep` is False, and we fail to decode, a\n UnicodeDecodeError will be raised. Passing `keep` as True allows for the\n original value to silently be returned in cases where decoding fails. This\n can be useful for cases where the data passed to this function is likely to\n contain binary blobs, such as in the case of cp.recv.\n\n If `normalize` is True, then unicodedata.normalize() will be used to\n normalize unicode strings down to a single code point per glyph. It is\n recommended not to normalize unless you know what you're doing. For\n instance, if `data` contains a dictionary, it is possible that normalizing\n will lead to data loss because the following two strings will normalize to\n the same value:\n\n - u'\\\\u044f\\\\u0438\\\\u0306\\\\u0446\\\\u0430.txt'\n - u'\\\\u044f\\\\u0439\\\\u0446\\\\u0430.txt'\n\n One good use case for normalization is in the test suite. For example, on\n some platforms such as Mac OS, os.listdir() will produce the first of the\n two strings above, in which \"й\" is represented as two code points (i.e. one\n for the base character, and one for the breve mark). Normalizing allows for\n a more reliable test case.\n '''\n _decode_func = salt.utils.stringutils.to_unicode \\\n if not to_str \\\n else salt.utils.stringutils.to_str\n if isinstance(data, Mapping):\n return decode_dict(data, encoding, errors, keep, normalize,\n preserve_dict_class, preserve_tuples, to_str)\n elif isinstance(data, list):\n return decode_list(data, encoding, errors, keep, normalize,\n preserve_dict_class, preserve_tuples, to_str)\n elif isinstance(data, tuple):\n return decode_tuple(data, encoding, errors, keep, normalize,\n preserve_dict_class, to_str) \\\n if preserve_tuples \\\n else decode_list(data, encoding, errors, keep, normalize,\n preserve_dict_class, preserve_tuples, to_str)\n else:\n try:\n data = _decode_func(data, 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 means we\n # are going to leave the value as-is.\n pass\n except UnicodeDecodeError:\n if not keep:\n raise\n return data\n",
"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"
] |
# -*- 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 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 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
|
write_conf
|
python
|
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 {}
|
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
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/lxc.py#L4262-L4323
|
[
"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_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 -*-
'''
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 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 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
|
edit_conf
|
python
|
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)
|
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'}]"
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/lxc.py#L4326-L4436
|
[
"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 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 write_conf(conf_file, conf):\n '''\n Write out an LXC configuration file\n\n This is normally only used internally. The format of the data structure\n must match that which is returned from ``lxc.read_conf()``, with\n ``out_format`` set to ``commented``.\n\n An example might look like:\n\n .. code-block:: python\n\n [\n {'lxc.utsname': '$CONTAINER_NAME'},\n '# This is a commented line\\\\n',\n '\\\\n',\n {'lxc.mount': '$CONTAINER_FSTAB'},\n {'lxc.rootfs': {'comment': 'This is another test',\n 'value': 'This is another test'}},\n '\\\\n',\n {'lxc.network.type': 'veth'},\n {'lxc.network.flags': 'up'},\n {'lxc.network.link': 'br0'},\n {'lxc.network.mac': '$CONTAINER_MACADDR'},\n {'lxc.network.ipv4': '$CONTAINER_IPADDR'},\n {'lxc.network.name': '$CONTAINER_DEVICENAME'},\n ]\n\n CLI Example:\n\n .. code-block:: bash\n\n salt 'minion' lxc.write_conf /etc/lxc/mycontainer.conf \\\\\n out_format=commented\n '''\n if not isinstance(conf, list):\n raise SaltInvocationError('Configuration must be passed as a list')\n\n # construct the content prior to write to the file\n # to avoid half written configs\n content = ''\n for line in conf:\n if isinstance(line, (six.text_type, six.string_types)):\n content += line\n elif isinstance(line, dict):\n for key in list(line.keys()):\n out_line = None\n if isinstance(\n line[key],\n (six.text_type, six.string_types, six.integer_types, float)\n ):\n out_line = ' = '.join((key, \"{0}\".format(line[key])))\n elif isinstance(line[key], dict):\n out_line = ' = '.join((key, line[key]['value']))\n if 'comment' in line[key]:\n out_line = ' # '.join((out_line, line[key]['comment']))\n if out_line:\n content += out_line\n content += '\\n'\n with salt.utils.files.fopen(conf_file, 'w') as fp_:\n fp_.write(salt.utils.stringutils.to_str(content))\n return {}\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 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 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
|
reboot
|
python
|
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
|
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
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/lxc.py#L4439-L4476
|
[
"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 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_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 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
|
reconfigure
|
python
|
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
|
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
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/lxc.py#L4479-L4608
|
[
"def iteritems(d, **kw):\n return d.iteritems(**kw)\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 reboot(name, path=None):\n '''\n Reboot a container.\n\n\n path\n path to the container parent\n default: /var/lib/lxc (system default)\n\n .. versionadded:: 2015.8.0\n\n CLI Examples:\n\n .. code-block:: bash\n\n salt 'minion' lxc.reboot myvm\n\n '''\n ret = {'result': True,\n 'changes': {},\n 'comment': '{0} rebooted'.format(name)}\n does_exist = exists(name, path=path)\n if does_exist and (state(name, path=path) == 'running'):\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 return ret\n if 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 ret['result'] = False\n return ret\n ret['changes'][name] = 'rebooted'\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 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 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"
] |
# -*- 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 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 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
|
apply_network_profile
|
python
|
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
|
.. 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}}"
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/lxc.py#L4611-L4678
|
[
"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 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 _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",
"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 _filter_data(self, pattern):\n '''\n Removes parameters which match the pattern from the config data\n '''\n removed = []\n filtered = []\n for param in self.data:\n if not param[0].startswith(pattern):\n filtered.append(param)\n else:\n removed.append(param)\n self.data = filtered\n return removed\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 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 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_pid
|
python
|
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
|
Returns a container pid.
Throw an exception if the container isn't running.
CLI Example:
.. code-block:: bash
salt '*' lxc.get_pid name
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/lxc.py#L4681-L4696
|
[
"def list_(extra=False, limit=None, path=None):\n '''\n List containers classified by state\n\n extra\n Also get per-container specific info. This will change the return data.\n Instead of returning a list of containers, a dictionary of containers\n and each container's output from :mod:`lxc.info\n <salt.modules.lxc.info>`.\n\n path\n path to the container parent directory\n default: /var/lib/lxc (system)\n\n .. versionadded:: 2015.8.0\n\n limit\n Return output matching a specific state (**frozen**, **running**, or\n **stopped**).\n\n .. versionadded:: 2015.5.0\n\n CLI Examples:\n\n .. code-block:: bash\n\n salt '*' lxc.list\n salt '*' lxc.list extra=True\n salt '*' lxc.list limit=running\n '''\n ctnrs = ls_(path=path)\n\n if extra:\n stopped = {}\n frozen = {}\n running = {}\n else:\n stopped = []\n frozen = []\n running = []\n\n ret = {'running': running,\n 'stopped': stopped,\n 'frozen': frozen}\n\n for container in ctnrs:\n cmd = 'lxc-info'\n if path:\n cmd += ' -P {0}'.format(pipes.quote(path))\n cmd += ' -n {0}'.format(container)\n c_info = __salt__['cmd.run'](\n cmd,\n python_shell=False,\n output_loglevel='debug'\n )\n c_state = None\n for line in c_info.splitlines():\n stat = line.split(':')\n if stat[0] in ('State', 'state'):\n c_state = stat[1].strip()\n break\n\n if not c_state or (limit is not None and c_state.lower() != limit):\n continue\n\n if extra:\n infos = info(container, path=path)\n method = 'update'\n value = {container: infos}\n else:\n method = 'append'\n value = container\n\n if c_state == 'STOPPED':\n getattr(stopped, method)(value)\n continue\n if c_state == 'FROZEN':\n getattr(frozen, method)(value)\n continue\n if c_state == 'RUNNING':\n getattr(running, method)(value)\n continue\n\n if limit is not None:\n return ret.get(limit, {} if extra else [])\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 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 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
|
add_veth
|
python
|
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)
|
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
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/lxc.py#L4699-L4778
|
[
"def get_pid(name, path=None):\n '''\n Returns a container pid.\n Throw an exception if the container isn't running.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' lxc.get_pid name\n '''\n if name not in list_(limit='running', path=path):\n raise CommandExecutionError('Container {0} is not running, can\\'t determine PID'.format(name))\n info = __salt__['cmd.run']('lxc-info -n {0}'.format(name)).split(\"\\n\")\n pid = [line.split(':')[1].strip() for line in info if re.match(r'\\s*PID', line)][0]\n return pid\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 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
|
saltstack/salt
|
salt/modules/lxc.py
|
_LXCConfig._filter_data
|
python
|
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
|
Removes parameters which match the pattern from the config data
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/lxc.py#L1055-L1067
| null |
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
|
saltstack/salt
|
salt/engines/script.py
|
_get_serializer
|
python
|
def _get_serializer(output):
'''
Helper to return known serializer based on
pass output argument
'''
serializers = salt.loader.serializers(__opts__)
try:
return getattr(serializers, output)
except AttributeError:
raise CommandExecutionError(
"Unknown serializer '{0}' found for output option".format(output)
)
|
Helper to return known serializer based on
pass output argument
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/engines/script.py#L51-L62
| null |
# -*- coding: utf-8 -*-
'''
Send events based on a script's stdout
.. versionadded:: Neon
Example Config
.. code-block:: yaml
engines:
- script:
cmd: /some/script.py -a 1 -b 2
output: json
interval: 5
Script engine configs:
cmd: Script or command to execute
output: Any available saltstack deserializer
interval: How often in seconds to execute the command
'''
from __future__ import absolute_import, print_function
import logging
import shlex
import time
import subprocess
# import salt libs
import salt.utils.event
import salt.utils.process
import salt.loader
from salt.exceptions import CommandExecutionError
from salt.ext import six
log = logging.getLogger(__name__)
def _read_stdout(proc):
'''
Generator that returns stdout
'''
for line in iter(proc.stdout.readline, ""):
yield line
def start(cmd, output='json', interval=1):
'''
Parse stdout of a command and generate an event
The script engine will scrap stdout of the
given script and generate an event based on the
presence of the 'tag' key and it's value.
If there is a data obj available, that will also
be fired along with the tag.
Example:
Given the following json output from a script:
{ "tag" : "lots/of/tacos",
"data" : { "toppings" : "cilantro" }
}
This will fire the event 'lots/of/tacos'
on the event bus with the data obj as is.
:param cmd: The command to execute
:param output: How to deserialize stdout of the script
:param interval: How often to execute the script.
'''
try:
cmd = shlex.split(cmd)
except AttributeError:
cmd = shlex.split(six.text_type(cmd))
log.debug("script engine using command %s", cmd)
serializer = _get_serializer(output)
if __opts__.get('__role') == 'master':
fire_master = salt.utils.event.get_master_event(
__opts__,
__opts__['sock_dir']).fire_event
else:
fire_master = __salt__['event.send']
while True:
try:
proc = subprocess.Popen(cmd,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
log.debug("Starting script with pid %d", proc.pid)
for raw_event in _read_stdout(proc):
log.debug(raw_event)
event = serializer.deserialize(raw_event)
tag = event.get('tag', None)
data = event.get('data', {})
if data and 'id' not in data:
data['id'] = __opts__['id']
if tag:
log.info("script engine firing event with tag %s", tag)
fire_master(tag=tag, data=data)
log.debug("Closing script with pid %d", proc.pid)
proc.stdout.close()
rc = proc.wait()
if rc:
raise subprocess.CalledProcessError(rc, cmd)
except subprocess.CalledProcessError as e:
log.error(e)
finally:
if proc.poll is None:
proc.terminate()
time.sleep(interval)
|
saltstack/salt
|
salt/engines/script.py
|
start
|
python
|
def start(cmd, output='json', interval=1):
'''
Parse stdout of a command and generate an event
The script engine will scrap stdout of the
given script and generate an event based on the
presence of the 'tag' key and it's value.
If there is a data obj available, that will also
be fired along with the tag.
Example:
Given the following json output from a script:
{ "tag" : "lots/of/tacos",
"data" : { "toppings" : "cilantro" }
}
This will fire the event 'lots/of/tacos'
on the event bus with the data obj as is.
:param cmd: The command to execute
:param output: How to deserialize stdout of the script
:param interval: How often to execute the script.
'''
try:
cmd = shlex.split(cmd)
except AttributeError:
cmd = shlex.split(six.text_type(cmd))
log.debug("script engine using command %s", cmd)
serializer = _get_serializer(output)
if __opts__.get('__role') == 'master':
fire_master = salt.utils.event.get_master_event(
__opts__,
__opts__['sock_dir']).fire_event
else:
fire_master = __salt__['event.send']
while True:
try:
proc = subprocess.Popen(cmd,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
log.debug("Starting script with pid %d", proc.pid)
for raw_event in _read_stdout(proc):
log.debug(raw_event)
event = serializer.deserialize(raw_event)
tag = event.get('tag', None)
data = event.get('data', {})
if data and 'id' not in data:
data['id'] = __opts__['id']
if tag:
log.info("script engine firing event with tag %s", tag)
fire_master(tag=tag, data=data)
log.debug("Closing script with pid %d", proc.pid)
proc.stdout.close()
rc = proc.wait()
if rc:
raise subprocess.CalledProcessError(rc, cmd)
except subprocess.CalledProcessError as e:
log.error(e)
finally:
if proc.poll is None:
proc.terminate()
time.sleep(interval)
|
Parse stdout of a command and generate an event
The script engine will scrap stdout of the
given script and generate an event based on the
presence of the 'tag' key and it's value.
If there is a data obj available, that will also
be fired along with the tag.
Example:
Given the following json output from a script:
{ "tag" : "lots/of/tacos",
"data" : { "toppings" : "cilantro" }
}
This will fire the event 'lots/of/tacos'
on the event bus with the data obj as is.
:param cmd: The command to execute
:param output: How to deserialize stdout of the script
:param interval: How often to execute the script.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/engines/script.py#L65-L141
|
[
"def get_master_event(opts, sock_dir, listen=True, io_loop=None, raise_errors=False, keep_loop=False):\n '''\n Return an event object suitable for the named transport\n '''\n # TODO: AIO core is separate from transport\n if opts['transport'] in ('zeromq', 'tcp', 'detect'):\n return MasterEvent(sock_dir, opts, listen=listen, io_loop=io_loop, raise_errors=raise_errors, keep_loop=keep_loop)\n",
"def _read_stdout(proc):\n '''\n Generator that returns stdout\n '''\n for line in iter(proc.stdout.readline, \"\"):\n yield line\n",
"def _get_serializer(output):\n '''\n Helper to return known serializer based on\n pass output argument\n '''\n serializers = salt.loader.serializers(__opts__)\n try:\n return getattr(serializers, output)\n except AttributeError:\n raise CommandExecutionError(\n \"Unknown serializer '{0}' found for output option\".format(output)\n )\n"
] |
# -*- coding: utf-8 -*-
'''
Send events based on a script's stdout
.. versionadded:: Neon
Example Config
.. code-block:: yaml
engines:
- script:
cmd: /some/script.py -a 1 -b 2
output: json
interval: 5
Script engine configs:
cmd: Script or command to execute
output: Any available saltstack deserializer
interval: How often in seconds to execute the command
'''
from __future__ import absolute_import, print_function
import logging
import shlex
import time
import subprocess
# import salt libs
import salt.utils.event
import salt.utils.process
import salt.loader
from salt.exceptions import CommandExecutionError
from salt.ext import six
log = logging.getLogger(__name__)
def _read_stdout(proc):
'''
Generator that returns stdout
'''
for line in iter(proc.stdout.readline, ""):
yield line
def _get_serializer(output):
'''
Helper to return known serializer based on
pass output argument
'''
serializers = salt.loader.serializers(__opts__)
try:
return getattr(serializers, output)
except AttributeError:
raise CommandExecutionError(
"Unknown serializer '{0}' found for output option".format(output)
)
|
saltstack/salt
|
salt/modules/bluez_bluetooth.py
|
version
|
python
|
def version():
'''
Return Bluez version from bluetoothd -v
CLI Example:
.. code-block:: bash
salt '*' bluetoothd.version
'''
cmd = 'bluetoothctl -v'
out = __salt__['cmd.run'](cmd).splitlines()
bluez_version = out[0]
pybluez_version = '<= 0.18 (Unknown, but installed)'
try:
pybluez_version = bluetooth.__version__
except Exception as exc:
pass
return {'Bluez': bluez_version, 'PyBluez': pybluez_version}
|
Return Bluez version from bluetoothd -v
CLI Example:
.. code-block:: bash
salt '*' bluetoothd.version
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/bluez_bluetooth.py#L48-L66
| null |
# -*- coding: utf-8 -*-
'''
Support for Bluetooth (using BlueZ in Linux).
The following packages are required packages for this module:
bluez >= 5.7
bluez-libs >= 5.7
bluez-utils >= 5.7
pybluez >= 0.18
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import 3rd-party libs
# pylint: disable=import-error
from salt.ext.six.moves import shlex_quote as _cmd_quote
# pylint: enable=import-error
# Import salt libs
import salt.utils.validate.net
from salt.exceptions import CommandExecutionError
HAS_PYBLUEZ = False
try:
import bluetooth # pylint: disable=import-error
HAS_PYBLUEZ = True
except ImportError:
pass
__func_alias__ = {
'address_': 'address'
}
# Define the module's virtual name
__virtualname__ = 'bluetooth'
def __virtual__():
'''
Only load the module if bluetooth is installed
'''
if HAS_PYBLUEZ:
return __virtualname__
return (False, 'The bluetooth execution module cannot be loaded: bluetooth not installed.')
def address_():
'''
Get the many addresses of the Bluetooth adapter
CLI Example:
.. code-block:: bash
salt '*' bluetooth.address
'''
ret = {}
cmd = 'hciconfig'
out = __salt__['cmd.run'](cmd).splitlines()
dev = ''
for line in out:
if line.startswith('hci'):
comps = line.split(':')
dev = comps[0]
ret[dev] = {
'device': dev,
'path': '/sys/class/bluetooth/{0}'.format(dev),
}
if 'BD Address' in line:
comps = line.split()
ret[dev]['address'] = comps[2]
if 'DOWN' in line:
ret[dev]['power'] = 'off'
if 'UP RUNNING' in line:
ret[dev]['power'] = 'on'
return ret
def power(dev, mode):
'''
Power a bluetooth device on or off
CLI Examples:
.. code-block:: bash
salt '*' bluetooth.power hci0 on
salt '*' bluetooth.power hci0 off
'''
if dev not in address_():
raise CommandExecutionError('Invalid dev passed to bluetooth.power')
if mode == 'on' or mode is True:
state = 'up'
mode = 'on'
else:
state = 'down'
mode = 'off'
cmd = 'hciconfig {0} {1}'.format(dev, state)
__salt__['cmd.run'](cmd).splitlines()
info = address_()
if info[dev]['power'] == mode:
return True
return False
def discoverable(dev):
'''
Enable this bluetooth device to be discoverable.
CLI Example:
.. code-block:: bash
salt '*' bluetooth.discoverable hci0
'''
if dev not in address_():
raise CommandExecutionError(
'Invalid dev passed to bluetooth.discoverable'
)
cmd = 'hciconfig {0} iscan'.format(dev)
__salt__['cmd.run'](cmd).splitlines()
cmd = 'hciconfig {0}'.format(dev)
out = __salt__['cmd.run'](cmd)
if 'UP RUNNING ISCAN' in out:
return True
return False
def noscan(dev):
'''
Turn off scanning modes on this device.
CLI Example:
.. code-block:: bash
salt '*' bluetooth.noscan hci0
'''
if dev not in address_():
raise CommandExecutionError('Invalid dev passed to bluetooth.noscan')
cmd = 'hciconfig {0} noscan'.format(dev)
__salt__['cmd.run'](cmd).splitlines()
cmd = 'hciconfig {0}'.format(dev)
out = __salt__['cmd.run'](cmd)
if 'SCAN' in out:
return False
return True
def scan():
'''
Scan for bluetooth devices in the area
CLI Example:
.. code-block:: bash
salt '*' bluetooth.scan
'''
ret = []
devices = bluetooth.discover_devices(lookup_names=True)
for device in devices:
ret.append({device[0]: device[1]})
return ret
def block(bdaddr):
'''
Block a specific bluetooth device by BD Address
CLI Example:
.. code-block:: bash
salt '*' bluetooth.block DE:AD:BE:EF:CA:FE
'''
if not salt.utils.validate.net.mac(bdaddr):
raise CommandExecutionError(
'Invalid BD address passed to bluetooth.block'
)
cmd = 'hciconfig {0} block'.format(bdaddr)
__salt__['cmd.run'](cmd).splitlines()
def unblock(bdaddr):
'''
Unblock a specific bluetooth device by BD Address
CLI Example:
.. code-block:: bash
salt '*' bluetooth.unblock DE:AD:BE:EF:CA:FE
'''
if not salt.utils.validate.net.mac(bdaddr):
raise CommandExecutionError(
'Invalid BD address passed to bluetooth.unblock'
)
cmd = 'hciconfig {0} unblock'.format(bdaddr)
__salt__['cmd.run'](cmd).splitlines()
def pair(address, key):
'''
Pair the bluetooth adapter with a device
CLI Example:
.. code-block:: bash
salt '*' bluetooth.pair DE:AD:BE:EF:CA:FE 1234
Where DE:AD:BE:EF:CA:FE is the address of the device to pair with, and 1234
is the passphrase.
TODO: This function is currently broken, as the bluez-simple-agent program
no longer ships with BlueZ >= 5.0. It needs to be refactored.
'''
if not salt.utils.validate.net.mac(address):
raise CommandExecutionError(
'Invalid BD address passed to bluetooth.pair'
)
try:
int(key)
except Exception:
raise CommandExecutionError(
'bluetooth.pair requires a numerical key to be used'
)
addy = address_()
cmd = 'echo {0} | bluez-simple-agent {1} {2}'.format(
_cmd_quote(addy['device']), _cmd_quote(address), _cmd_quote(key)
)
out = __salt__['cmd.run'](cmd, python_shell=True).splitlines()
return out
def unpair(address):
'''
Unpair the bluetooth adapter from a device
CLI Example:
.. code-block:: bash
salt '*' bluetooth.unpair DE:AD:BE:EF:CA:FE
Where DE:AD:BE:EF:CA:FE is the address of the device to unpair.
TODO: This function is currently broken, as the bluez-simple-agent program
no longer ships with BlueZ >= 5.0. It needs to be refactored.
'''
if not salt.utils.validate.net.mac(address):
raise CommandExecutionError(
'Invalid BD address passed to bluetooth.unpair'
)
cmd = 'bluez-test-device remove {0}'.format(address)
out = __salt__['cmd.run'](cmd).splitlines()
return out
def start():
'''
Start the bluetooth service.
CLI Example:
.. code-block:: bash
salt '*' bluetooth.start
'''
out = __salt__['service.start']('bluetooth')
return out
def stop():
'''
Stop the bluetooth service.
CLI Example:
.. code-block:: bash
salt '*' bluetooth.stop
'''
out = __salt__['service.stop']('bluetooth')
return out
|
saltstack/salt
|
salt/modules/bluez_bluetooth.py
|
address_
|
python
|
def address_():
'''
Get the many addresses of the Bluetooth adapter
CLI Example:
.. code-block:: bash
salt '*' bluetooth.address
'''
ret = {}
cmd = 'hciconfig'
out = __salt__['cmd.run'](cmd).splitlines()
dev = ''
for line in out:
if line.startswith('hci'):
comps = line.split(':')
dev = comps[0]
ret[dev] = {
'device': dev,
'path': '/sys/class/bluetooth/{0}'.format(dev),
}
if 'BD Address' in line:
comps = line.split()
ret[dev]['address'] = comps[2]
if 'DOWN' in line:
ret[dev]['power'] = 'off'
if 'UP RUNNING' in line:
ret[dev]['power'] = 'on'
return ret
|
Get the many addresses of the Bluetooth adapter
CLI Example:
.. code-block:: bash
salt '*' bluetooth.address
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/bluez_bluetooth.py#L69-L98
| null |
# -*- coding: utf-8 -*-
'''
Support for Bluetooth (using BlueZ in Linux).
The following packages are required packages for this module:
bluez >= 5.7
bluez-libs >= 5.7
bluez-utils >= 5.7
pybluez >= 0.18
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import 3rd-party libs
# pylint: disable=import-error
from salt.ext.six.moves import shlex_quote as _cmd_quote
# pylint: enable=import-error
# Import salt libs
import salt.utils.validate.net
from salt.exceptions import CommandExecutionError
HAS_PYBLUEZ = False
try:
import bluetooth # pylint: disable=import-error
HAS_PYBLUEZ = True
except ImportError:
pass
__func_alias__ = {
'address_': 'address'
}
# Define the module's virtual name
__virtualname__ = 'bluetooth'
def __virtual__():
'''
Only load the module if bluetooth is installed
'''
if HAS_PYBLUEZ:
return __virtualname__
return (False, 'The bluetooth execution module cannot be loaded: bluetooth not installed.')
def version():
'''
Return Bluez version from bluetoothd -v
CLI Example:
.. code-block:: bash
salt '*' bluetoothd.version
'''
cmd = 'bluetoothctl -v'
out = __salt__['cmd.run'](cmd).splitlines()
bluez_version = out[0]
pybluez_version = '<= 0.18 (Unknown, but installed)'
try:
pybluez_version = bluetooth.__version__
except Exception as exc:
pass
return {'Bluez': bluez_version, 'PyBluez': pybluez_version}
def power(dev, mode):
'''
Power a bluetooth device on or off
CLI Examples:
.. code-block:: bash
salt '*' bluetooth.power hci0 on
salt '*' bluetooth.power hci0 off
'''
if dev not in address_():
raise CommandExecutionError('Invalid dev passed to bluetooth.power')
if mode == 'on' or mode is True:
state = 'up'
mode = 'on'
else:
state = 'down'
mode = 'off'
cmd = 'hciconfig {0} {1}'.format(dev, state)
__salt__['cmd.run'](cmd).splitlines()
info = address_()
if info[dev]['power'] == mode:
return True
return False
def discoverable(dev):
'''
Enable this bluetooth device to be discoverable.
CLI Example:
.. code-block:: bash
salt '*' bluetooth.discoverable hci0
'''
if dev not in address_():
raise CommandExecutionError(
'Invalid dev passed to bluetooth.discoverable'
)
cmd = 'hciconfig {0} iscan'.format(dev)
__salt__['cmd.run'](cmd).splitlines()
cmd = 'hciconfig {0}'.format(dev)
out = __salt__['cmd.run'](cmd)
if 'UP RUNNING ISCAN' in out:
return True
return False
def noscan(dev):
'''
Turn off scanning modes on this device.
CLI Example:
.. code-block:: bash
salt '*' bluetooth.noscan hci0
'''
if dev not in address_():
raise CommandExecutionError('Invalid dev passed to bluetooth.noscan')
cmd = 'hciconfig {0} noscan'.format(dev)
__salt__['cmd.run'](cmd).splitlines()
cmd = 'hciconfig {0}'.format(dev)
out = __salt__['cmd.run'](cmd)
if 'SCAN' in out:
return False
return True
def scan():
'''
Scan for bluetooth devices in the area
CLI Example:
.. code-block:: bash
salt '*' bluetooth.scan
'''
ret = []
devices = bluetooth.discover_devices(lookup_names=True)
for device in devices:
ret.append({device[0]: device[1]})
return ret
def block(bdaddr):
'''
Block a specific bluetooth device by BD Address
CLI Example:
.. code-block:: bash
salt '*' bluetooth.block DE:AD:BE:EF:CA:FE
'''
if not salt.utils.validate.net.mac(bdaddr):
raise CommandExecutionError(
'Invalid BD address passed to bluetooth.block'
)
cmd = 'hciconfig {0} block'.format(bdaddr)
__salt__['cmd.run'](cmd).splitlines()
def unblock(bdaddr):
'''
Unblock a specific bluetooth device by BD Address
CLI Example:
.. code-block:: bash
salt '*' bluetooth.unblock DE:AD:BE:EF:CA:FE
'''
if not salt.utils.validate.net.mac(bdaddr):
raise CommandExecutionError(
'Invalid BD address passed to bluetooth.unblock'
)
cmd = 'hciconfig {0} unblock'.format(bdaddr)
__salt__['cmd.run'](cmd).splitlines()
def pair(address, key):
'''
Pair the bluetooth adapter with a device
CLI Example:
.. code-block:: bash
salt '*' bluetooth.pair DE:AD:BE:EF:CA:FE 1234
Where DE:AD:BE:EF:CA:FE is the address of the device to pair with, and 1234
is the passphrase.
TODO: This function is currently broken, as the bluez-simple-agent program
no longer ships with BlueZ >= 5.0. It needs to be refactored.
'''
if not salt.utils.validate.net.mac(address):
raise CommandExecutionError(
'Invalid BD address passed to bluetooth.pair'
)
try:
int(key)
except Exception:
raise CommandExecutionError(
'bluetooth.pair requires a numerical key to be used'
)
addy = address_()
cmd = 'echo {0} | bluez-simple-agent {1} {2}'.format(
_cmd_quote(addy['device']), _cmd_quote(address), _cmd_quote(key)
)
out = __salt__['cmd.run'](cmd, python_shell=True).splitlines()
return out
def unpair(address):
'''
Unpair the bluetooth adapter from a device
CLI Example:
.. code-block:: bash
salt '*' bluetooth.unpair DE:AD:BE:EF:CA:FE
Where DE:AD:BE:EF:CA:FE is the address of the device to unpair.
TODO: This function is currently broken, as the bluez-simple-agent program
no longer ships with BlueZ >= 5.0. It needs to be refactored.
'''
if not salt.utils.validate.net.mac(address):
raise CommandExecutionError(
'Invalid BD address passed to bluetooth.unpair'
)
cmd = 'bluez-test-device remove {0}'.format(address)
out = __salt__['cmd.run'](cmd).splitlines()
return out
def start():
'''
Start the bluetooth service.
CLI Example:
.. code-block:: bash
salt '*' bluetooth.start
'''
out = __salt__['service.start']('bluetooth')
return out
def stop():
'''
Stop the bluetooth service.
CLI Example:
.. code-block:: bash
salt '*' bluetooth.stop
'''
out = __salt__['service.stop']('bluetooth')
return out
|
saltstack/salt
|
salt/modules/bluez_bluetooth.py
|
power
|
python
|
def power(dev, mode):
'''
Power a bluetooth device on or off
CLI Examples:
.. code-block:: bash
salt '*' bluetooth.power hci0 on
salt '*' bluetooth.power hci0 off
'''
if dev not in address_():
raise CommandExecutionError('Invalid dev passed to bluetooth.power')
if mode == 'on' or mode is True:
state = 'up'
mode = 'on'
else:
state = 'down'
mode = 'off'
cmd = 'hciconfig {0} {1}'.format(dev, state)
__salt__['cmd.run'](cmd).splitlines()
info = address_()
if info[dev]['power'] == mode:
return True
return False
|
Power a bluetooth device on or off
CLI Examples:
.. code-block:: bash
salt '*' bluetooth.power hci0 on
salt '*' bluetooth.power hci0 off
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/bluez_bluetooth.py#L101-L126
|
[
"def address_():\n '''\n Get the many addresses of the Bluetooth adapter\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' bluetooth.address\n '''\n ret = {}\n cmd = 'hciconfig'\n out = __salt__['cmd.run'](cmd).splitlines()\n dev = ''\n for line in out:\n if line.startswith('hci'):\n comps = line.split(':')\n dev = comps[0]\n ret[dev] = {\n 'device': dev,\n 'path': '/sys/class/bluetooth/{0}'.format(dev),\n }\n if 'BD Address' in line:\n comps = line.split()\n ret[dev]['address'] = comps[2]\n if 'DOWN' in line:\n ret[dev]['power'] = 'off'\n if 'UP RUNNING' in line:\n ret[dev]['power'] = 'on'\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Support for Bluetooth (using BlueZ in Linux).
The following packages are required packages for this module:
bluez >= 5.7
bluez-libs >= 5.7
bluez-utils >= 5.7
pybluez >= 0.18
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import 3rd-party libs
# pylint: disable=import-error
from salt.ext.six.moves import shlex_quote as _cmd_quote
# pylint: enable=import-error
# Import salt libs
import salt.utils.validate.net
from salt.exceptions import CommandExecutionError
HAS_PYBLUEZ = False
try:
import bluetooth # pylint: disable=import-error
HAS_PYBLUEZ = True
except ImportError:
pass
__func_alias__ = {
'address_': 'address'
}
# Define the module's virtual name
__virtualname__ = 'bluetooth'
def __virtual__():
'''
Only load the module if bluetooth is installed
'''
if HAS_PYBLUEZ:
return __virtualname__
return (False, 'The bluetooth execution module cannot be loaded: bluetooth not installed.')
def version():
'''
Return Bluez version from bluetoothd -v
CLI Example:
.. code-block:: bash
salt '*' bluetoothd.version
'''
cmd = 'bluetoothctl -v'
out = __salt__['cmd.run'](cmd).splitlines()
bluez_version = out[0]
pybluez_version = '<= 0.18 (Unknown, but installed)'
try:
pybluez_version = bluetooth.__version__
except Exception as exc:
pass
return {'Bluez': bluez_version, 'PyBluez': pybluez_version}
def address_():
'''
Get the many addresses of the Bluetooth adapter
CLI Example:
.. code-block:: bash
salt '*' bluetooth.address
'''
ret = {}
cmd = 'hciconfig'
out = __salt__['cmd.run'](cmd).splitlines()
dev = ''
for line in out:
if line.startswith('hci'):
comps = line.split(':')
dev = comps[0]
ret[dev] = {
'device': dev,
'path': '/sys/class/bluetooth/{0}'.format(dev),
}
if 'BD Address' in line:
comps = line.split()
ret[dev]['address'] = comps[2]
if 'DOWN' in line:
ret[dev]['power'] = 'off'
if 'UP RUNNING' in line:
ret[dev]['power'] = 'on'
return ret
def discoverable(dev):
'''
Enable this bluetooth device to be discoverable.
CLI Example:
.. code-block:: bash
salt '*' bluetooth.discoverable hci0
'''
if dev not in address_():
raise CommandExecutionError(
'Invalid dev passed to bluetooth.discoverable'
)
cmd = 'hciconfig {0} iscan'.format(dev)
__salt__['cmd.run'](cmd).splitlines()
cmd = 'hciconfig {0}'.format(dev)
out = __salt__['cmd.run'](cmd)
if 'UP RUNNING ISCAN' in out:
return True
return False
def noscan(dev):
'''
Turn off scanning modes on this device.
CLI Example:
.. code-block:: bash
salt '*' bluetooth.noscan hci0
'''
if dev not in address_():
raise CommandExecutionError('Invalid dev passed to bluetooth.noscan')
cmd = 'hciconfig {0} noscan'.format(dev)
__salt__['cmd.run'](cmd).splitlines()
cmd = 'hciconfig {0}'.format(dev)
out = __salt__['cmd.run'](cmd)
if 'SCAN' in out:
return False
return True
def scan():
'''
Scan for bluetooth devices in the area
CLI Example:
.. code-block:: bash
salt '*' bluetooth.scan
'''
ret = []
devices = bluetooth.discover_devices(lookup_names=True)
for device in devices:
ret.append({device[0]: device[1]})
return ret
def block(bdaddr):
'''
Block a specific bluetooth device by BD Address
CLI Example:
.. code-block:: bash
salt '*' bluetooth.block DE:AD:BE:EF:CA:FE
'''
if not salt.utils.validate.net.mac(bdaddr):
raise CommandExecutionError(
'Invalid BD address passed to bluetooth.block'
)
cmd = 'hciconfig {0} block'.format(bdaddr)
__salt__['cmd.run'](cmd).splitlines()
def unblock(bdaddr):
'''
Unblock a specific bluetooth device by BD Address
CLI Example:
.. code-block:: bash
salt '*' bluetooth.unblock DE:AD:BE:EF:CA:FE
'''
if not salt.utils.validate.net.mac(bdaddr):
raise CommandExecutionError(
'Invalid BD address passed to bluetooth.unblock'
)
cmd = 'hciconfig {0} unblock'.format(bdaddr)
__salt__['cmd.run'](cmd).splitlines()
def pair(address, key):
'''
Pair the bluetooth adapter with a device
CLI Example:
.. code-block:: bash
salt '*' bluetooth.pair DE:AD:BE:EF:CA:FE 1234
Where DE:AD:BE:EF:CA:FE is the address of the device to pair with, and 1234
is the passphrase.
TODO: This function is currently broken, as the bluez-simple-agent program
no longer ships with BlueZ >= 5.0. It needs to be refactored.
'''
if not salt.utils.validate.net.mac(address):
raise CommandExecutionError(
'Invalid BD address passed to bluetooth.pair'
)
try:
int(key)
except Exception:
raise CommandExecutionError(
'bluetooth.pair requires a numerical key to be used'
)
addy = address_()
cmd = 'echo {0} | bluez-simple-agent {1} {2}'.format(
_cmd_quote(addy['device']), _cmd_quote(address), _cmd_quote(key)
)
out = __salt__['cmd.run'](cmd, python_shell=True).splitlines()
return out
def unpair(address):
'''
Unpair the bluetooth adapter from a device
CLI Example:
.. code-block:: bash
salt '*' bluetooth.unpair DE:AD:BE:EF:CA:FE
Where DE:AD:BE:EF:CA:FE is the address of the device to unpair.
TODO: This function is currently broken, as the bluez-simple-agent program
no longer ships with BlueZ >= 5.0. It needs to be refactored.
'''
if not salt.utils.validate.net.mac(address):
raise CommandExecutionError(
'Invalid BD address passed to bluetooth.unpair'
)
cmd = 'bluez-test-device remove {0}'.format(address)
out = __salt__['cmd.run'](cmd).splitlines()
return out
def start():
'''
Start the bluetooth service.
CLI Example:
.. code-block:: bash
salt '*' bluetooth.start
'''
out = __salt__['service.start']('bluetooth')
return out
def stop():
'''
Stop the bluetooth service.
CLI Example:
.. code-block:: bash
salt '*' bluetooth.stop
'''
out = __salt__['service.stop']('bluetooth')
return out
|
saltstack/salt
|
salt/modules/bluez_bluetooth.py
|
discoverable
|
python
|
def discoverable(dev):
'''
Enable this bluetooth device to be discoverable.
CLI Example:
.. code-block:: bash
salt '*' bluetooth.discoverable hci0
'''
if dev not in address_():
raise CommandExecutionError(
'Invalid dev passed to bluetooth.discoverable'
)
cmd = 'hciconfig {0} iscan'.format(dev)
__salt__['cmd.run'](cmd).splitlines()
cmd = 'hciconfig {0}'.format(dev)
out = __salt__['cmd.run'](cmd)
if 'UP RUNNING ISCAN' in out:
return True
return False
|
Enable this bluetooth device to be discoverable.
CLI Example:
.. code-block:: bash
salt '*' bluetooth.discoverable hci0
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/bluez_bluetooth.py#L129-L150
|
[
"def address_():\n '''\n Get the many addresses of the Bluetooth adapter\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' bluetooth.address\n '''\n ret = {}\n cmd = 'hciconfig'\n out = __salt__['cmd.run'](cmd).splitlines()\n dev = ''\n for line in out:\n if line.startswith('hci'):\n comps = line.split(':')\n dev = comps[0]\n ret[dev] = {\n 'device': dev,\n 'path': '/sys/class/bluetooth/{0}'.format(dev),\n }\n if 'BD Address' in line:\n comps = line.split()\n ret[dev]['address'] = comps[2]\n if 'DOWN' in line:\n ret[dev]['power'] = 'off'\n if 'UP RUNNING' in line:\n ret[dev]['power'] = 'on'\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Support for Bluetooth (using BlueZ in Linux).
The following packages are required packages for this module:
bluez >= 5.7
bluez-libs >= 5.7
bluez-utils >= 5.7
pybluez >= 0.18
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import 3rd-party libs
# pylint: disable=import-error
from salt.ext.six.moves import shlex_quote as _cmd_quote
# pylint: enable=import-error
# Import salt libs
import salt.utils.validate.net
from salt.exceptions import CommandExecutionError
HAS_PYBLUEZ = False
try:
import bluetooth # pylint: disable=import-error
HAS_PYBLUEZ = True
except ImportError:
pass
__func_alias__ = {
'address_': 'address'
}
# Define the module's virtual name
__virtualname__ = 'bluetooth'
def __virtual__():
'''
Only load the module if bluetooth is installed
'''
if HAS_PYBLUEZ:
return __virtualname__
return (False, 'The bluetooth execution module cannot be loaded: bluetooth not installed.')
def version():
'''
Return Bluez version from bluetoothd -v
CLI Example:
.. code-block:: bash
salt '*' bluetoothd.version
'''
cmd = 'bluetoothctl -v'
out = __salt__['cmd.run'](cmd).splitlines()
bluez_version = out[0]
pybluez_version = '<= 0.18 (Unknown, but installed)'
try:
pybluez_version = bluetooth.__version__
except Exception as exc:
pass
return {'Bluez': bluez_version, 'PyBluez': pybluez_version}
def address_():
'''
Get the many addresses of the Bluetooth adapter
CLI Example:
.. code-block:: bash
salt '*' bluetooth.address
'''
ret = {}
cmd = 'hciconfig'
out = __salt__['cmd.run'](cmd).splitlines()
dev = ''
for line in out:
if line.startswith('hci'):
comps = line.split(':')
dev = comps[0]
ret[dev] = {
'device': dev,
'path': '/sys/class/bluetooth/{0}'.format(dev),
}
if 'BD Address' in line:
comps = line.split()
ret[dev]['address'] = comps[2]
if 'DOWN' in line:
ret[dev]['power'] = 'off'
if 'UP RUNNING' in line:
ret[dev]['power'] = 'on'
return ret
def power(dev, mode):
'''
Power a bluetooth device on or off
CLI Examples:
.. code-block:: bash
salt '*' bluetooth.power hci0 on
salt '*' bluetooth.power hci0 off
'''
if dev not in address_():
raise CommandExecutionError('Invalid dev passed to bluetooth.power')
if mode == 'on' or mode is True:
state = 'up'
mode = 'on'
else:
state = 'down'
mode = 'off'
cmd = 'hciconfig {0} {1}'.format(dev, state)
__salt__['cmd.run'](cmd).splitlines()
info = address_()
if info[dev]['power'] == mode:
return True
return False
def noscan(dev):
'''
Turn off scanning modes on this device.
CLI Example:
.. code-block:: bash
salt '*' bluetooth.noscan hci0
'''
if dev not in address_():
raise CommandExecutionError('Invalid dev passed to bluetooth.noscan')
cmd = 'hciconfig {0} noscan'.format(dev)
__salt__['cmd.run'](cmd).splitlines()
cmd = 'hciconfig {0}'.format(dev)
out = __salt__['cmd.run'](cmd)
if 'SCAN' in out:
return False
return True
def scan():
'''
Scan for bluetooth devices in the area
CLI Example:
.. code-block:: bash
salt '*' bluetooth.scan
'''
ret = []
devices = bluetooth.discover_devices(lookup_names=True)
for device in devices:
ret.append({device[0]: device[1]})
return ret
def block(bdaddr):
'''
Block a specific bluetooth device by BD Address
CLI Example:
.. code-block:: bash
salt '*' bluetooth.block DE:AD:BE:EF:CA:FE
'''
if not salt.utils.validate.net.mac(bdaddr):
raise CommandExecutionError(
'Invalid BD address passed to bluetooth.block'
)
cmd = 'hciconfig {0} block'.format(bdaddr)
__salt__['cmd.run'](cmd).splitlines()
def unblock(bdaddr):
'''
Unblock a specific bluetooth device by BD Address
CLI Example:
.. code-block:: bash
salt '*' bluetooth.unblock DE:AD:BE:EF:CA:FE
'''
if not salt.utils.validate.net.mac(bdaddr):
raise CommandExecutionError(
'Invalid BD address passed to bluetooth.unblock'
)
cmd = 'hciconfig {0} unblock'.format(bdaddr)
__salt__['cmd.run'](cmd).splitlines()
def pair(address, key):
'''
Pair the bluetooth adapter with a device
CLI Example:
.. code-block:: bash
salt '*' bluetooth.pair DE:AD:BE:EF:CA:FE 1234
Where DE:AD:BE:EF:CA:FE is the address of the device to pair with, and 1234
is the passphrase.
TODO: This function is currently broken, as the bluez-simple-agent program
no longer ships with BlueZ >= 5.0. It needs to be refactored.
'''
if not salt.utils.validate.net.mac(address):
raise CommandExecutionError(
'Invalid BD address passed to bluetooth.pair'
)
try:
int(key)
except Exception:
raise CommandExecutionError(
'bluetooth.pair requires a numerical key to be used'
)
addy = address_()
cmd = 'echo {0} | bluez-simple-agent {1} {2}'.format(
_cmd_quote(addy['device']), _cmd_quote(address), _cmd_quote(key)
)
out = __salt__['cmd.run'](cmd, python_shell=True).splitlines()
return out
def unpair(address):
'''
Unpair the bluetooth adapter from a device
CLI Example:
.. code-block:: bash
salt '*' bluetooth.unpair DE:AD:BE:EF:CA:FE
Where DE:AD:BE:EF:CA:FE is the address of the device to unpair.
TODO: This function is currently broken, as the bluez-simple-agent program
no longer ships with BlueZ >= 5.0. It needs to be refactored.
'''
if not salt.utils.validate.net.mac(address):
raise CommandExecutionError(
'Invalid BD address passed to bluetooth.unpair'
)
cmd = 'bluez-test-device remove {0}'.format(address)
out = __salt__['cmd.run'](cmd).splitlines()
return out
def start():
'''
Start the bluetooth service.
CLI Example:
.. code-block:: bash
salt '*' bluetooth.start
'''
out = __salt__['service.start']('bluetooth')
return out
def stop():
'''
Stop the bluetooth service.
CLI Example:
.. code-block:: bash
salt '*' bluetooth.stop
'''
out = __salt__['service.stop']('bluetooth')
return out
|
saltstack/salt
|
salt/modules/bluez_bluetooth.py
|
scan
|
python
|
def scan():
'''
Scan for bluetooth devices in the area
CLI Example:
.. code-block:: bash
salt '*' bluetooth.scan
'''
ret = []
devices = bluetooth.discover_devices(lookup_names=True)
for device in devices:
ret.append({device[0]: device[1]})
return ret
|
Scan for bluetooth devices in the area
CLI Example:
.. code-block:: bash
salt '*' bluetooth.scan
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/bluez_bluetooth.py#L175-L189
| null |
# -*- coding: utf-8 -*-
'''
Support for Bluetooth (using BlueZ in Linux).
The following packages are required packages for this module:
bluez >= 5.7
bluez-libs >= 5.7
bluez-utils >= 5.7
pybluez >= 0.18
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import 3rd-party libs
# pylint: disable=import-error
from salt.ext.six.moves import shlex_quote as _cmd_quote
# pylint: enable=import-error
# Import salt libs
import salt.utils.validate.net
from salt.exceptions import CommandExecutionError
HAS_PYBLUEZ = False
try:
import bluetooth # pylint: disable=import-error
HAS_PYBLUEZ = True
except ImportError:
pass
__func_alias__ = {
'address_': 'address'
}
# Define the module's virtual name
__virtualname__ = 'bluetooth'
def __virtual__():
'''
Only load the module if bluetooth is installed
'''
if HAS_PYBLUEZ:
return __virtualname__
return (False, 'The bluetooth execution module cannot be loaded: bluetooth not installed.')
def version():
'''
Return Bluez version from bluetoothd -v
CLI Example:
.. code-block:: bash
salt '*' bluetoothd.version
'''
cmd = 'bluetoothctl -v'
out = __salt__['cmd.run'](cmd).splitlines()
bluez_version = out[0]
pybluez_version = '<= 0.18 (Unknown, but installed)'
try:
pybluez_version = bluetooth.__version__
except Exception as exc:
pass
return {'Bluez': bluez_version, 'PyBluez': pybluez_version}
def address_():
'''
Get the many addresses of the Bluetooth adapter
CLI Example:
.. code-block:: bash
salt '*' bluetooth.address
'''
ret = {}
cmd = 'hciconfig'
out = __salt__['cmd.run'](cmd).splitlines()
dev = ''
for line in out:
if line.startswith('hci'):
comps = line.split(':')
dev = comps[0]
ret[dev] = {
'device': dev,
'path': '/sys/class/bluetooth/{0}'.format(dev),
}
if 'BD Address' in line:
comps = line.split()
ret[dev]['address'] = comps[2]
if 'DOWN' in line:
ret[dev]['power'] = 'off'
if 'UP RUNNING' in line:
ret[dev]['power'] = 'on'
return ret
def power(dev, mode):
'''
Power a bluetooth device on or off
CLI Examples:
.. code-block:: bash
salt '*' bluetooth.power hci0 on
salt '*' bluetooth.power hci0 off
'''
if dev not in address_():
raise CommandExecutionError('Invalid dev passed to bluetooth.power')
if mode == 'on' or mode is True:
state = 'up'
mode = 'on'
else:
state = 'down'
mode = 'off'
cmd = 'hciconfig {0} {1}'.format(dev, state)
__salt__['cmd.run'](cmd).splitlines()
info = address_()
if info[dev]['power'] == mode:
return True
return False
def discoverable(dev):
'''
Enable this bluetooth device to be discoverable.
CLI Example:
.. code-block:: bash
salt '*' bluetooth.discoverable hci0
'''
if dev not in address_():
raise CommandExecutionError(
'Invalid dev passed to bluetooth.discoverable'
)
cmd = 'hciconfig {0} iscan'.format(dev)
__salt__['cmd.run'](cmd).splitlines()
cmd = 'hciconfig {0}'.format(dev)
out = __salt__['cmd.run'](cmd)
if 'UP RUNNING ISCAN' in out:
return True
return False
def noscan(dev):
'''
Turn off scanning modes on this device.
CLI Example:
.. code-block:: bash
salt '*' bluetooth.noscan hci0
'''
if dev not in address_():
raise CommandExecutionError('Invalid dev passed to bluetooth.noscan')
cmd = 'hciconfig {0} noscan'.format(dev)
__salt__['cmd.run'](cmd).splitlines()
cmd = 'hciconfig {0}'.format(dev)
out = __salt__['cmd.run'](cmd)
if 'SCAN' in out:
return False
return True
def block(bdaddr):
'''
Block a specific bluetooth device by BD Address
CLI Example:
.. code-block:: bash
salt '*' bluetooth.block DE:AD:BE:EF:CA:FE
'''
if not salt.utils.validate.net.mac(bdaddr):
raise CommandExecutionError(
'Invalid BD address passed to bluetooth.block'
)
cmd = 'hciconfig {0} block'.format(bdaddr)
__salt__['cmd.run'](cmd).splitlines()
def unblock(bdaddr):
'''
Unblock a specific bluetooth device by BD Address
CLI Example:
.. code-block:: bash
salt '*' bluetooth.unblock DE:AD:BE:EF:CA:FE
'''
if not salt.utils.validate.net.mac(bdaddr):
raise CommandExecutionError(
'Invalid BD address passed to bluetooth.unblock'
)
cmd = 'hciconfig {0} unblock'.format(bdaddr)
__salt__['cmd.run'](cmd).splitlines()
def pair(address, key):
'''
Pair the bluetooth adapter with a device
CLI Example:
.. code-block:: bash
salt '*' bluetooth.pair DE:AD:BE:EF:CA:FE 1234
Where DE:AD:BE:EF:CA:FE is the address of the device to pair with, and 1234
is the passphrase.
TODO: This function is currently broken, as the bluez-simple-agent program
no longer ships with BlueZ >= 5.0. It needs to be refactored.
'''
if not salt.utils.validate.net.mac(address):
raise CommandExecutionError(
'Invalid BD address passed to bluetooth.pair'
)
try:
int(key)
except Exception:
raise CommandExecutionError(
'bluetooth.pair requires a numerical key to be used'
)
addy = address_()
cmd = 'echo {0} | bluez-simple-agent {1} {2}'.format(
_cmd_quote(addy['device']), _cmd_quote(address), _cmd_quote(key)
)
out = __salt__['cmd.run'](cmd, python_shell=True).splitlines()
return out
def unpair(address):
'''
Unpair the bluetooth adapter from a device
CLI Example:
.. code-block:: bash
salt '*' bluetooth.unpair DE:AD:BE:EF:CA:FE
Where DE:AD:BE:EF:CA:FE is the address of the device to unpair.
TODO: This function is currently broken, as the bluez-simple-agent program
no longer ships with BlueZ >= 5.0. It needs to be refactored.
'''
if not salt.utils.validate.net.mac(address):
raise CommandExecutionError(
'Invalid BD address passed to bluetooth.unpair'
)
cmd = 'bluez-test-device remove {0}'.format(address)
out = __salt__['cmd.run'](cmd).splitlines()
return out
def start():
'''
Start the bluetooth service.
CLI Example:
.. code-block:: bash
salt '*' bluetooth.start
'''
out = __salt__['service.start']('bluetooth')
return out
def stop():
'''
Stop the bluetooth service.
CLI Example:
.. code-block:: bash
salt '*' bluetooth.stop
'''
out = __salt__['service.stop']('bluetooth')
return out
|
saltstack/salt
|
salt/modules/bluez_bluetooth.py
|
block
|
python
|
def block(bdaddr):
'''
Block a specific bluetooth device by BD Address
CLI Example:
.. code-block:: bash
salt '*' bluetooth.block DE:AD:BE:EF:CA:FE
'''
if not salt.utils.validate.net.mac(bdaddr):
raise CommandExecutionError(
'Invalid BD address passed to bluetooth.block'
)
cmd = 'hciconfig {0} block'.format(bdaddr)
__salt__['cmd.run'](cmd).splitlines()
|
Block a specific bluetooth device by BD Address
CLI Example:
.. code-block:: bash
salt '*' bluetooth.block DE:AD:BE:EF:CA:FE
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/bluez_bluetooth.py#L192-L208
|
[
"def mac(addr):\n '''\n Validates a mac address\n '''\n valid = re.compile(r'''\n (^([0-9A-F]{1,2}[-]){5}([0-9A-F]{1,2})$\n |^([0-9A-F]{1,2}[:]){5}([0-9A-F]{1,2})$\n |^([0-9A-F]{1,2}[.]){5}([0-9A-F]{1,2})$)\n ''',\n re.VERBOSE | re.IGNORECASE)\n return valid.match(addr) is not None\n"
] |
# -*- coding: utf-8 -*-
'''
Support for Bluetooth (using BlueZ in Linux).
The following packages are required packages for this module:
bluez >= 5.7
bluez-libs >= 5.7
bluez-utils >= 5.7
pybluez >= 0.18
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import 3rd-party libs
# pylint: disable=import-error
from salt.ext.six.moves import shlex_quote as _cmd_quote
# pylint: enable=import-error
# Import salt libs
import salt.utils.validate.net
from salt.exceptions import CommandExecutionError
HAS_PYBLUEZ = False
try:
import bluetooth # pylint: disable=import-error
HAS_PYBLUEZ = True
except ImportError:
pass
__func_alias__ = {
'address_': 'address'
}
# Define the module's virtual name
__virtualname__ = 'bluetooth'
def __virtual__():
'''
Only load the module if bluetooth is installed
'''
if HAS_PYBLUEZ:
return __virtualname__
return (False, 'The bluetooth execution module cannot be loaded: bluetooth not installed.')
def version():
'''
Return Bluez version from bluetoothd -v
CLI Example:
.. code-block:: bash
salt '*' bluetoothd.version
'''
cmd = 'bluetoothctl -v'
out = __salt__['cmd.run'](cmd).splitlines()
bluez_version = out[0]
pybluez_version = '<= 0.18 (Unknown, but installed)'
try:
pybluez_version = bluetooth.__version__
except Exception as exc:
pass
return {'Bluez': bluez_version, 'PyBluez': pybluez_version}
def address_():
'''
Get the many addresses of the Bluetooth adapter
CLI Example:
.. code-block:: bash
salt '*' bluetooth.address
'''
ret = {}
cmd = 'hciconfig'
out = __salt__['cmd.run'](cmd).splitlines()
dev = ''
for line in out:
if line.startswith('hci'):
comps = line.split(':')
dev = comps[0]
ret[dev] = {
'device': dev,
'path': '/sys/class/bluetooth/{0}'.format(dev),
}
if 'BD Address' in line:
comps = line.split()
ret[dev]['address'] = comps[2]
if 'DOWN' in line:
ret[dev]['power'] = 'off'
if 'UP RUNNING' in line:
ret[dev]['power'] = 'on'
return ret
def power(dev, mode):
'''
Power a bluetooth device on or off
CLI Examples:
.. code-block:: bash
salt '*' bluetooth.power hci0 on
salt '*' bluetooth.power hci0 off
'''
if dev not in address_():
raise CommandExecutionError('Invalid dev passed to bluetooth.power')
if mode == 'on' or mode is True:
state = 'up'
mode = 'on'
else:
state = 'down'
mode = 'off'
cmd = 'hciconfig {0} {1}'.format(dev, state)
__salt__['cmd.run'](cmd).splitlines()
info = address_()
if info[dev]['power'] == mode:
return True
return False
def discoverable(dev):
'''
Enable this bluetooth device to be discoverable.
CLI Example:
.. code-block:: bash
salt '*' bluetooth.discoverable hci0
'''
if dev not in address_():
raise CommandExecutionError(
'Invalid dev passed to bluetooth.discoverable'
)
cmd = 'hciconfig {0} iscan'.format(dev)
__salt__['cmd.run'](cmd).splitlines()
cmd = 'hciconfig {0}'.format(dev)
out = __salt__['cmd.run'](cmd)
if 'UP RUNNING ISCAN' in out:
return True
return False
def noscan(dev):
'''
Turn off scanning modes on this device.
CLI Example:
.. code-block:: bash
salt '*' bluetooth.noscan hci0
'''
if dev not in address_():
raise CommandExecutionError('Invalid dev passed to bluetooth.noscan')
cmd = 'hciconfig {0} noscan'.format(dev)
__salt__['cmd.run'](cmd).splitlines()
cmd = 'hciconfig {0}'.format(dev)
out = __salt__['cmd.run'](cmd)
if 'SCAN' in out:
return False
return True
def scan():
'''
Scan for bluetooth devices in the area
CLI Example:
.. code-block:: bash
salt '*' bluetooth.scan
'''
ret = []
devices = bluetooth.discover_devices(lookup_names=True)
for device in devices:
ret.append({device[0]: device[1]})
return ret
def unblock(bdaddr):
'''
Unblock a specific bluetooth device by BD Address
CLI Example:
.. code-block:: bash
salt '*' bluetooth.unblock DE:AD:BE:EF:CA:FE
'''
if not salt.utils.validate.net.mac(bdaddr):
raise CommandExecutionError(
'Invalid BD address passed to bluetooth.unblock'
)
cmd = 'hciconfig {0} unblock'.format(bdaddr)
__salt__['cmd.run'](cmd).splitlines()
def pair(address, key):
'''
Pair the bluetooth adapter with a device
CLI Example:
.. code-block:: bash
salt '*' bluetooth.pair DE:AD:BE:EF:CA:FE 1234
Where DE:AD:BE:EF:CA:FE is the address of the device to pair with, and 1234
is the passphrase.
TODO: This function is currently broken, as the bluez-simple-agent program
no longer ships with BlueZ >= 5.0. It needs to be refactored.
'''
if not salt.utils.validate.net.mac(address):
raise CommandExecutionError(
'Invalid BD address passed to bluetooth.pair'
)
try:
int(key)
except Exception:
raise CommandExecutionError(
'bluetooth.pair requires a numerical key to be used'
)
addy = address_()
cmd = 'echo {0} | bluez-simple-agent {1} {2}'.format(
_cmd_quote(addy['device']), _cmd_quote(address), _cmd_quote(key)
)
out = __salt__['cmd.run'](cmd, python_shell=True).splitlines()
return out
def unpair(address):
'''
Unpair the bluetooth adapter from a device
CLI Example:
.. code-block:: bash
salt '*' bluetooth.unpair DE:AD:BE:EF:CA:FE
Where DE:AD:BE:EF:CA:FE is the address of the device to unpair.
TODO: This function is currently broken, as the bluez-simple-agent program
no longer ships with BlueZ >= 5.0. It needs to be refactored.
'''
if not salt.utils.validate.net.mac(address):
raise CommandExecutionError(
'Invalid BD address passed to bluetooth.unpair'
)
cmd = 'bluez-test-device remove {0}'.format(address)
out = __salt__['cmd.run'](cmd).splitlines()
return out
def start():
'''
Start the bluetooth service.
CLI Example:
.. code-block:: bash
salt '*' bluetooth.start
'''
out = __salt__['service.start']('bluetooth')
return out
def stop():
'''
Stop the bluetooth service.
CLI Example:
.. code-block:: bash
salt '*' bluetooth.stop
'''
out = __salt__['service.stop']('bluetooth')
return out
|
saltstack/salt
|
salt/modules/bluez_bluetooth.py
|
pair
|
python
|
def pair(address, key):
'''
Pair the bluetooth adapter with a device
CLI Example:
.. code-block:: bash
salt '*' bluetooth.pair DE:AD:BE:EF:CA:FE 1234
Where DE:AD:BE:EF:CA:FE is the address of the device to pair with, and 1234
is the passphrase.
TODO: This function is currently broken, as the bluez-simple-agent program
no longer ships with BlueZ >= 5.0. It needs to be refactored.
'''
if not salt.utils.validate.net.mac(address):
raise CommandExecutionError(
'Invalid BD address passed to bluetooth.pair'
)
try:
int(key)
except Exception:
raise CommandExecutionError(
'bluetooth.pair requires a numerical key to be used'
)
addy = address_()
cmd = 'echo {0} | bluez-simple-agent {1} {2}'.format(
_cmd_quote(addy['device']), _cmd_quote(address), _cmd_quote(key)
)
out = __salt__['cmd.run'](cmd, python_shell=True).splitlines()
return out
|
Pair the bluetooth adapter with a device
CLI Example:
.. code-block:: bash
salt '*' bluetooth.pair DE:AD:BE:EF:CA:FE 1234
Where DE:AD:BE:EF:CA:FE is the address of the device to pair with, and 1234
is the passphrase.
TODO: This function is currently broken, as the bluez-simple-agent program
no longer ships with BlueZ >= 5.0. It needs to be refactored.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/bluez_bluetooth.py#L230-L263
|
[
"def mac(addr):\n '''\n Validates a mac address\n '''\n valid = re.compile(r'''\n (^([0-9A-F]{1,2}[-]){5}([0-9A-F]{1,2})$\n |^([0-9A-F]{1,2}[:]){5}([0-9A-F]{1,2})$\n |^([0-9A-F]{1,2}[.]){5}([0-9A-F]{1,2})$)\n ''',\n re.VERBOSE | re.IGNORECASE)\n return valid.match(addr) is not None\n",
"def address_():\n '''\n Get the many addresses of the Bluetooth adapter\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' bluetooth.address\n '''\n ret = {}\n cmd = 'hciconfig'\n out = __salt__['cmd.run'](cmd).splitlines()\n dev = ''\n for line in out:\n if line.startswith('hci'):\n comps = line.split(':')\n dev = comps[0]\n ret[dev] = {\n 'device': dev,\n 'path': '/sys/class/bluetooth/{0}'.format(dev),\n }\n if 'BD Address' in line:\n comps = line.split()\n ret[dev]['address'] = comps[2]\n if 'DOWN' in line:\n ret[dev]['power'] = 'off'\n if 'UP RUNNING' in line:\n ret[dev]['power'] = 'on'\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Support for Bluetooth (using BlueZ in Linux).
The following packages are required packages for this module:
bluez >= 5.7
bluez-libs >= 5.7
bluez-utils >= 5.7
pybluez >= 0.18
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import 3rd-party libs
# pylint: disable=import-error
from salt.ext.six.moves import shlex_quote as _cmd_quote
# pylint: enable=import-error
# Import salt libs
import salt.utils.validate.net
from salt.exceptions import CommandExecutionError
HAS_PYBLUEZ = False
try:
import bluetooth # pylint: disable=import-error
HAS_PYBLUEZ = True
except ImportError:
pass
__func_alias__ = {
'address_': 'address'
}
# Define the module's virtual name
__virtualname__ = 'bluetooth'
def __virtual__():
'''
Only load the module if bluetooth is installed
'''
if HAS_PYBLUEZ:
return __virtualname__
return (False, 'The bluetooth execution module cannot be loaded: bluetooth not installed.')
def version():
'''
Return Bluez version from bluetoothd -v
CLI Example:
.. code-block:: bash
salt '*' bluetoothd.version
'''
cmd = 'bluetoothctl -v'
out = __salt__['cmd.run'](cmd).splitlines()
bluez_version = out[0]
pybluez_version = '<= 0.18 (Unknown, but installed)'
try:
pybluez_version = bluetooth.__version__
except Exception as exc:
pass
return {'Bluez': bluez_version, 'PyBluez': pybluez_version}
def address_():
'''
Get the many addresses of the Bluetooth adapter
CLI Example:
.. code-block:: bash
salt '*' bluetooth.address
'''
ret = {}
cmd = 'hciconfig'
out = __salt__['cmd.run'](cmd).splitlines()
dev = ''
for line in out:
if line.startswith('hci'):
comps = line.split(':')
dev = comps[0]
ret[dev] = {
'device': dev,
'path': '/sys/class/bluetooth/{0}'.format(dev),
}
if 'BD Address' in line:
comps = line.split()
ret[dev]['address'] = comps[2]
if 'DOWN' in line:
ret[dev]['power'] = 'off'
if 'UP RUNNING' in line:
ret[dev]['power'] = 'on'
return ret
def power(dev, mode):
'''
Power a bluetooth device on or off
CLI Examples:
.. code-block:: bash
salt '*' bluetooth.power hci0 on
salt '*' bluetooth.power hci0 off
'''
if dev not in address_():
raise CommandExecutionError('Invalid dev passed to bluetooth.power')
if mode == 'on' or mode is True:
state = 'up'
mode = 'on'
else:
state = 'down'
mode = 'off'
cmd = 'hciconfig {0} {1}'.format(dev, state)
__salt__['cmd.run'](cmd).splitlines()
info = address_()
if info[dev]['power'] == mode:
return True
return False
def discoverable(dev):
'''
Enable this bluetooth device to be discoverable.
CLI Example:
.. code-block:: bash
salt '*' bluetooth.discoverable hci0
'''
if dev not in address_():
raise CommandExecutionError(
'Invalid dev passed to bluetooth.discoverable'
)
cmd = 'hciconfig {0} iscan'.format(dev)
__salt__['cmd.run'](cmd).splitlines()
cmd = 'hciconfig {0}'.format(dev)
out = __salt__['cmd.run'](cmd)
if 'UP RUNNING ISCAN' in out:
return True
return False
def noscan(dev):
'''
Turn off scanning modes on this device.
CLI Example:
.. code-block:: bash
salt '*' bluetooth.noscan hci0
'''
if dev not in address_():
raise CommandExecutionError('Invalid dev passed to bluetooth.noscan')
cmd = 'hciconfig {0} noscan'.format(dev)
__salt__['cmd.run'](cmd).splitlines()
cmd = 'hciconfig {0}'.format(dev)
out = __salt__['cmd.run'](cmd)
if 'SCAN' in out:
return False
return True
def scan():
'''
Scan for bluetooth devices in the area
CLI Example:
.. code-block:: bash
salt '*' bluetooth.scan
'''
ret = []
devices = bluetooth.discover_devices(lookup_names=True)
for device in devices:
ret.append({device[0]: device[1]})
return ret
def block(bdaddr):
'''
Block a specific bluetooth device by BD Address
CLI Example:
.. code-block:: bash
salt '*' bluetooth.block DE:AD:BE:EF:CA:FE
'''
if not salt.utils.validate.net.mac(bdaddr):
raise CommandExecutionError(
'Invalid BD address passed to bluetooth.block'
)
cmd = 'hciconfig {0} block'.format(bdaddr)
__salt__['cmd.run'](cmd).splitlines()
def unblock(bdaddr):
'''
Unblock a specific bluetooth device by BD Address
CLI Example:
.. code-block:: bash
salt '*' bluetooth.unblock DE:AD:BE:EF:CA:FE
'''
if not salt.utils.validate.net.mac(bdaddr):
raise CommandExecutionError(
'Invalid BD address passed to bluetooth.unblock'
)
cmd = 'hciconfig {0} unblock'.format(bdaddr)
__salt__['cmd.run'](cmd).splitlines()
def unpair(address):
'''
Unpair the bluetooth adapter from a device
CLI Example:
.. code-block:: bash
salt '*' bluetooth.unpair DE:AD:BE:EF:CA:FE
Where DE:AD:BE:EF:CA:FE is the address of the device to unpair.
TODO: This function is currently broken, as the bluez-simple-agent program
no longer ships with BlueZ >= 5.0. It needs to be refactored.
'''
if not salt.utils.validate.net.mac(address):
raise CommandExecutionError(
'Invalid BD address passed to bluetooth.unpair'
)
cmd = 'bluez-test-device remove {0}'.format(address)
out = __salt__['cmd.run'](cmd).splitlines()
return out
def start():
'''
Start the bluetooth service.
CLI Example:
.. code-block:: bash
salt '*' bluetooth.start
'''
out = __salt__['service.start']('bluetooth')
return out
def stop():
'''
Stop the bluetooth service.
CLI Example:
.. code-block:: bash
salt '*' bluetooth.stop
'''
out = __salt__['service.stop']('bluetooth')
return out
|
saltstack/salt
|
salt/modules/bluez_bluetooth.py
|
unpair
|
python
|
def unpair(address):
'''
Unpair the bluetooth adapter from a device
CLI Example:
.. code-block:: bash
salt '*' bluetooth.unpair DE:AD:BE:EF:CA:FE
Where DE:AD:BE:EF:CA:FE is the address of the device to unpair.
TODO: This function is currently broken, as the bluez-simple-agent program
no longer ships with BlueZ >= 5.0. It needs to be refactored.
'''
if not salt.utils.validate.net.mac(address):
raise CommandExecutionError(
'Invalid BD address passed to bluetooth.unpair'
)
cmd = 'bluez-test-device remove {0}'.format(address)
out = __salt__['cmd.run'](cmd).splitlines()
return out
|
Unpair the bluetooth adapter from a device
CLI Example:
.. code-block:: bash
salt '*' bluetooth.unpair DE:AD:BE:EF:CA:FE
Where DE:AD:BE:EF:CA:FE is the address of the device to unpair.
TODO: This function is currently broken, as the bluez-simple-agent program
no longer ships with BlueZ >= 5.0. It needs to be refactored.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/bluez_bluetooth.py#L266-L288
|
[
"def mac(addr):\n '''\n Validates a mac address\n '''\n valid = re.compile(r'''\n (^([0-9A-F]{1,2}[-]){5}([0-9A-F]{1,2})$\n |^([0-9A-F]{1,2}[:]){5}([0-9A-F]{1,2})$\n |^([0-9A-F]{1,2}[.]){5}([0-9A-F]{1,2})$)\n ''',\n re.VERBOSE | re.IGNORECASE)\n return valid.match(addr) is not None\n"
] |
# -*- coding: utf-8 -*-
'''
Support for Bluetooth (using BlueZ in Linux).
The following packages are required packages for this module:
bluez >= 5.7
bluez-libs >= 5.7
bluez-utils >= 5.7
pybluez >= 0.18
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import 3rd-party libs
# pylint: disable=import-error
from salt.ext.six.moves import shlex_quote as _cmd_quote
# pylint: enable=import-error
# Import salt libs
import salt.utils.validate.net
from salt.exceptions import CommandExecutionError
HAS_PYBLUEZ = False
try:
import bluetooth # pylint: disable=import-error
HAS_PYBLUEZ = True
except ImportError:
pass
__func_alias__ = {
'address_': 'address'
}
# Define the module's virtual name
__virtualname__ = 'bluetooth'
def __virtual__():
'''
Only load the module if bluetooth is installed
'''
if HAS_PYBLUEZ:
return __virtualname__
return (False, 'The bluetooth execution module cannot be loaded: bluetooth not installed.')
def version():
'''
Return Bluez version from bluetoothd -v
CLI Example:
.. code-block:: bash
salt '*' bluetoothd.version
'''
cmd = 'bluetoothctl -v'
out = __salt__['cmd.run'](cmd).splitlines()
bluez_version = out[0]
pybluez_version = '<= 0.18 (Unknown, but installed)'
try:
pybluez_version = bluetooth.__version__
except Exception as exc:
pass
return {'Bluez': bluez_version, 'PyBluez': pybluez_version}
def address_():
'''
Get the many addresses of the Bluetooth adapter
CLI Example:
.. code-block:: bash
salt '*' bluetooth.address
'''
ret = {}
cmd = 'hciconfig'
out = __salt__['cmd.run'](cmd).splitlines()
dev = ''
for line in out:
if line.startswith('hci'):
comps = line.split(':')
dev = comps[0]
ret[dev] = {
'device': dev,
'path': '/sys/class/bluetooth/{0}'.format(dev),
}
if 'BD Address' in line:
comps = line.split()
ret[dev]['address'] = comps[2]
if 'DOWN' in line:
ret[dev]['power'] = 'off'
if 'UP RUNNING' in line:
ret[dev]['power'] = 'on'
return ret
def power(dev, mode):
'''
Power a bluetooth device on or off
CLI Examples:
.. code-block:: bash
salt '*' bluetooth.power hci0 on
salt '*' bluetooth.power hci0 off
'''
if dev not in address_():
raise CommandExecutionError('Invalid dev passed to bluetooth.power')
if mode == 'on' or mode is True:
state = 'up'
mode = 'on'
else:
state = 'down'
mode = 'off'
cmd = 'hciconfig {0} {1}'.format(dev, state)
__salt__['cmd.run'](cmd).splitlines()
info = address_()
if info[dev]['power'] == mode:
return True
return False
def discoverable(dev):
'''
Enable this bluetooth device to be discoverable.
CLI Example:
.. code-block:: bash
salt '*' bluetooth.discoverable hci0
'''
if dev not in address_():
raise CommandExecutionError(
'Invalid dev passed to bluetooth.discoverable'
)
cmd = 'hciconfig {0} iscan'.format(dev)
__salt__['cmd.run'](cmd).splitlines()
cmd = 'hciconfig {0}'.format(dev)
out = __salt__['cmd.run'](cmd)
if 'UP RUNNING ISCAN' in out:
return True
return False
def noscan(dev):
'''
Turn off scanning modes on this device.
CLI Example:
.. code-block:: bash
salt '*' bluetooth.noscan hci0
'''
if dev not in address_():
raise CommandExecutionError('Invalid dev passed to bluetooth.noscan')
cmd = 'hciconfig {0} noscan'.format(dev)
__salt__['cmd.run'](cmd).splitlines()
cmd = 'hciconfig {0}'.format(dev)
out = __salt__['cmd.run'](cmd)
if 'SCAN' in out:
return False
return True
def scan():
'''
Scan for bluetooth devices in the area
CLI Example:
.. code-block:: bash
salt '*' bluetooth.scan
'''
ret = []
devices = bluetooth.discover_devices(lookup_names=True)
for device in devices:
ret.append({device[0]: device[1]})
return ret
def block(bdaddr):
'''
Block a specific bluetooth device by BD Address
CLI Example:
.. code-block:: bash
salt '*' bluetooth.block DE:AD:BE:EF:CA:FE
'''
if not salt.utils.validate.net.mac(bdaddr):
raise CommandExecutionError(
'Invalid BD address passed to bluetooth.block'
)
cmd = 'hciconfig {0} block'.format(bdaddr)
__salt__['cmd.run'](cmd).splitlines()
def unblock(bdaddr):
'''
Unblock a specific bluetooth device by BD Address
CLI Example:
.. code-block:: bash
salt '*' bluetooth.unblock DE:AD:BE:EF:CA:FE
'''
if not salt.utils.validate.net.mac(bdaddr):
raise CommandExecutionError(
'Invalid BD address passed to bluetooth.unblock'
)
cmd = 'hciconfig {0} unblock'.format(bdaddr)
__salt__['cmd.run'](cmd).splitlines()
def pair(address, key):
'''
Pair the bluetooth adapter with a device
CLI Example:
.. code-block:: bash
salt '*' bluetooth.pair DE:AD:BE:EF:CA:FE 1234
Where DE:AD:BE:EF:CA:FE is the address of the device to pair with, and 1234
is the passphrase.
TODO: This function is currently broken, as the bluez-simple-agent program
no longer ships with BlueZ >= 5.0. It needs to be refactored.
'''
if not salt.utils.validate.net.mac(address):
raise CommandExecutionError(
'Invalid BD address passed to bluetooth.pair'
)
try:
int(key)
except Exception:
raise CommandExecutionError(
'bluetooth.pair requires a numerical key to be used'
)
addy = address_()
cmd = 'echo {0} | bluez-simple-agent {1} {2}'.format(
_cmd_quote(addy['device']), _cmd_quote(address), _cmd_quote(key)
)
out = __salt__['cmd.run'](cmd, python_shell=True).splitlines()
return out
def start():
'''
Start the bluetooth service.
CLI Example:
.. code-block:: bash
salt '*' bluetooth.start
'''
out = __salt__['service.start']('bluetooth')
return out
def stop():
'''
Stop the bluetooth service.
CLI Example:
.. code-block:: bash
salt '*' bluetooth.stop
'''
out = __salt__['service.stop']('bluetooth')
return out
|
saltstack/salt
|
salt/modules/msteams.py
|
post_card
|
python
|
def post_card(message,
hook_url=None,
title=None,
theme_color=None):
'''
Send a message to an MS Teams channel.
:param message: The message to send to the MS Teams channel.
:param hook_url: The Teams webhook URL, if not specified in the configuration.
:param title: Optional title for the posted card
:param theme_color: Optional hex color highlight for the posted card
:return: Boolean if message was sent successfully.
CLI Example:
.. code-block:: bash
salt '*' msteams.post_card message="Build is done"
'''
if not hook_url:
hook_url = _get_hook_url()
if not message:
log.error('message is a required option.')
payload = {
"text": message,
"title": title,
"themeColor": theme_color
}
result = salt.utils.http.query(hook_url,
method='POST',
data=salt.utils.json.dumps(payload),
status=True)
if result['status'] <= 201:
return True
else:
return {
'res': False,
'message': result.get('body', result['status'])
}
|
Send a message to an MS Teams channel.
:param message: The message to send to the MS Teams channel.
:param hook_url: The Teams webhook URL, if not specified in the configuration.
:param title: Optional title for the posted card
:param theme_color: Optional hex color highlight for the posted card
:return: Boolean if message was sent successfully.
CLI Example:
.. code-block:: bash
salt '*' msteams.post_card message="Build is done"
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/msteams.py#L54-L96
|
[
"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",
"def _get_hook_url():\n '''\n Return hook_url from minion/master config file\n or from pillar\n '''\n hook_url = __salt__['config.get']('msteams.hook_url') or \\\n __salt__['config.get']('msteams:hook_url')\n\n if not hook_url:\n raise SaltInvocationError('No MS Teams hook_url found.')\n\n return hook_url\n"
] |
# -*- coding: utf-8 -*-
'''
Module for sending messages to MS Teams
.. versionadded:: 2017.7.0
:configuration: This module can be used by either passing a hook_url
directly or by specifying it in a configuration profile in the salt
master/minion config. For example:
.. code-block:: yaml
msteams:
hook_url: https://outlook.office.com/webhook/837
'''
# 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 SaltInvocationError
# Import 3rd-party libs
import salt.ext.six.moves.http_client # pylint: disable=import-error,no-name-in-module,redefined-builtin
log = logging.getLogger(__name__)
__virtualname__ = 'msteams'
def __virtual__():
'''
Return virtual name of the module.
:return: The virtual name of the module.
'''
return __virtualname__
def _get_hook_url():
'''
Return hook_url from minion/master config file
or from pillar
'''
hook_url = __salt__['config.get']('msteams.hook_url') or \
__salt__['config.get']('msteams:hook_url')
if not hook_url:
raise SaltInvocationError('No MS Teams hook_url found.')
return hook_url
|
saltstack/salt
|
salt/beacons/ps.py
|
beacon
|
python
|
def beacon(config):
'''
Scan for processes and fire events
Example Config
.. code-block:: yaml
beacons:
ps:
- processes:
salt-master: running
mysql: stopped
The config above sets up beacons to check that
processes are running or stopped.
'''
ret = []
procs = []
for proc in psutil.process_iter():
_name = proc.name()
if _name not in procs:
procs.append(_name)
_config = {}
list(map(_config.update, config))
for process in _config.get('processes', {}):
ret_dict = {}
if _config['processes'][process] == 'running':
if process in procs:
ret_dict[process] = 'Running'
ret.append(ret_dict)
elif _config['processes'][process] == 'stopped':
if process not in procs:
ret_dict[process] = 'Stopped'
ret.append(ret_dict)
else:
if process not in procs:
ret_dict[process] = False
ret.append(ret_dict)
return ret
|
Scan for processes and fire events
Example Config
.. code-block:: yaml
beacons:
ps:
- processes:
salt-master: running
mysql: stopped
The config above sets up beacons to check that
processes are running or stopped.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/beacons/ps.py#L53-L94
| null |
# -*- coding: utf-8 -*-
'''
Send events covering process status
'''
# Import Python Libs
from __future__ import absolute_import, unicode_literals
import logging
# Import third party libs
# pylint: disable=import-error
try:
import salt.utils.psutil_compat as psutil
HAS_PSUTIL = True
except ImportError:
HAS_PSUTIL = False
from salt.ext.six.moves import map
# pylint: enable=import-error
log = logging.getLogger(__name__) # pylint: disable=invalid-name
__virtualname__ = 'ps'
def __virtual__():
if not HAS_PSUTIL:
return (False, 'cannot load ps beacon: psutil not available')
return __virtualname__
def validate(config):
'''
Validate the beacon configuration
'''
# Configuration for ps beacon should be a list of dicts
if not isinstance(config, list):
return False, ('Configuration for ps beacon must be a list.')
else:
_config = {}
list(map(_config.update, config))
if 'processes' not in _config:
return False, ('Configuration for ps beacon requires processes.')
else:
if not isinstance(_config['processes'], dict):
return False, ('Processes for ps beacon must be a dictionary.')
return True, 'Valid beacon configuration'
|
saltstack/salt
|
salt/cloud/clouds/vagrant.py
|
list_nodes_full
|
python
|
def list_nodes_full(call=None):
'''
List the nodes, ask all 'vagrant' minions, return dict of grains (enhanced).
CLI Example:
.. code-block:: bash
salt-call -F
'''
ret = _list_nodes(call)
for key, grains in ret.items(): # clean up some hyperverbose grains -- everything is too much
try:
del grains['cpu_flags'], grains['disks'], grains['pythonpath'], grains['dns'], grains['gpus']
except KeyError:
pass # ignore absence of things we are eliminating
except TypeError:
del ret[key] # eliminate all reference to unexpected (None) values.
reqs = _build_required_items(ret)
for name in ret:
ret[name].update(reqs[name])
return ret
|
List the nodes, ask all 'vagrant' minions, return dict of grains (enhanced).
CLI Example:
.. code-block:: bash
salt-call -F
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/vagrant.py#L125-L148
|
[
"def _list_nodes(call=None):\n '''\n List the nodes, ask all 'vagrant' minions, return dict of grains.\n '''\n local = salt.client.LocalClient()\n ret = local.cmd('salt-cloud:driver:vagrant', 'grains.items', '', tgt_type='grain')\n return ret\n",
"def _build_required_items(nodes):\n ret = {}\n for name, grains in nodes.items():\n if grains:\n private_ips = []\n public_ips = []\n ips = grains['ipv4'] + grains['ipv6']\n for adrs in ips:\n ip_ = ipaddress.ip_address(adrs)\n if not ip_.is_loopback:\n if ip_.is_private:\n private_ips.append(adrs)\n else:\n public_ips.append(adrs)\n\n ret[name] = {\n 'id': grains['id'],\n 'image': grains['salt-cloud']['profile'],\n 'private_ips': private_ips,\n 'public_ips': public_ips,\n 'size': '',\n 'state': 'running'\n }\n\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Vagrant Cloud Driver
====================
The Vagrant cloud is designed to "vagrant up" a virtual machine as a
Salt minion.
Use of this module requires some configuration in cloud profile and provider
files as described in the
:ref:`Getting Started with Vagrant <getting-started-with-vagrant>` documentation.
.. versionadded:: 2018.3.0
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import os
import tempfile
# Import salt libs
import salt.utils
import salt.config as config
import salt.client
from salt._compat import ipaddress
from salt.exceptions import SaltCloudException, SaltCloudSystemExit, SaltInvocationError
# Get logging started
log = logging.getLogger(__name__)
def __virtual__():
'''
Needs no special configuration
'''
return True
def avail_locations(call=None):
r'''
This function returns a list of locations available.
CLI Example:
.. code-block:: bash
salt-cloud --list-locations my-cloud-provider
# \[ vagrant will always returns an empty dictionary \]
'''
return {}
def avail_images(call=None):
'''This function returns a list of images available for this cloud provider.
vagrant will return a list of profiles.
salt-cloud --list-images my-cloud-provider
'''
vm_ = get_configured_provider()
return {'Profiles': [profile for profile in vm_['profiles']]}
def avail_sizes(call=None):
r'''
This function returns a list of sizes available for this cloud provider.
CLI Example:
.. code-block:: bash
salt-cloud --list-sizes my-cloud-provider
# \[ vagrant always returns an empty dictionary \]
'''
return {}
def list_nodes(call=None):
'''
List the nodes which have salt-cloud:driver:vagrant grains.
CLI Example:
.. code-block:: bash
salt-cloud -Q
'''
nodes = _list_nodes(call)
return _build_required_items(nodes)
def _build_required_items(nodes):
ret = {}
for name, grains in nodes.items():
if grains:
private_ips = []
public_ips = []
ips = grains['ipv4'] + grains['ipv6']
for adrs in ips:
ip_ = ipaddress.ip_address(adrs)
if not ip_.is_loopback:
if ip_.is_private:
private_ips.append(adrs)
else:
public_ips.append(adrs)
ret[name] = {
'id': grains['id'],
'image': grains['salt-cloud']['profile'],
'private_ips': private_ips,
'public_ips': public_ips,
'size': '',
'state': 'running'
}
return ret
def _list_nodes(call=None):
'''
List the nodes, ask all 'vagrant' minions, return dict of grains.
'''
local = salt.client.LocalClient()
ret = local.cmd('salt-cloud:driver:vagrant', 'grains.items', '', tgt_type='grain')
return ret
def list_nodes_select(call=None):
'''
Return a list of the minions that have salt-cloud grains, with
select fields.
'''
return salt.utils.cloud.list_nodes_select(
list_nodes_full('function'), __opts__['query.selection'], call,
)
def show_instance(name, call=None):
'''
List the a single node, return dict of grains.
'''
local = salt.client.LocalClient()
ret = local.cmd(name, 'grains.items', '')
reqs = _build_required_items(ret)
ret[name].update(reqs[name])
return ret
def _get_my_info(name):
local = salt.client.LocalClient()
return local.cmd(name, 'grains.get', ['salt-cloud'])
def create(vm_):
'''
Provision a single machine
CLI Example:
.. code-block:: bash
salt-cloud -p my_profile new_node_1
'''
name = vm_['name']
machine = config.get_cloud_config_value(
'machine', vm_, __opts__, default='')
vm_['machine'] = machine
host = config.get_cloud_config_value(
'host', vm_, __opts__, default=NotImplemented)
vm_['cwd'] = config.get_cloud_config_value(
'cwd', vm_, __opts__, default='/')
vm_['runas'] = config.get_cloud_config_value(
'vagrant_runas', vm_, __opts__, default=os.getenv('SUDO_USER'))
vm_['timeout'] = config.get_cloud_config_value(
'vagrant_up_timeout', vm_, __opts__, default=300)
vm_['vagrant_provider'] = config.get_cloud_config_value(
'vagrant_provider', vm_, __opts__, default='')
vm_['grains'] = {'salt-cloud:vagrant': {'host': host, 'machine': machine}}
log.info('sending \'vagrant.init %s machine=%s\' command to %s', name, machine, host)
local = salt.client.LocalClient()
ret = local.cmd(host, 'vagrant.init', [name], kwarg={'vm': vm_, 'start': True})
log.info('response ==> %s', ret[host])
network_mask = config.get_cloud_config_value(
'network_mask', vm_, __opts__, default='')
if 'ssh_host' not in vm_:
ret = local.cmd(host,
'vagrant.get_ssh_config',
[name],
kwarg={'network_mask': network_mask,
'get_private_key': True})[host]
with tempfile.NamedTemporaryFile() as pks:
if 'private_key' not in vm_ and ret and ret.get('private_key', False):
pks.write(ret['private_key'])
pks.flush()
log.debug('wrote private key to %s', pks.name)
vm_['key_filename'] = pks.name
if 'ssh_host' not in vm_:
try:
vm_.setdefault('ssh_username', ret['ssh_username'])
if ret.get('ip_address'):
vm_['ssh_host'] = ret['ip_address']
else: # if probe failed or not used, use Vagrant's reported ssh info
vm_['ssh_host'] = ret['ssh_host']
vm_.setdefault('ssh_port', ret['ssh_port'])
except (KeyError, TypeError):
raise SaltInvocationError(
'Insufficient SSH addressing information for {}'.format(name))
log.info('Provisioning machine %s as node %s using ssh %s',
machine, name, vm_['ssh_host'])
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
return ret
def get_configured_provider():
'''
Return the first configured instance.
'''
ret = config.is_provider_configured(
__opts__,
__active_provider_name__ or 'vagrant',
''
)
return ret
# noinspection PyTypeChecker
def destroy(name, call=None):
'''
Destroy a node.
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.'
)
opts = __opts__
__utils__['cloud.fire_event'](
'event',
'destroying instance',
'salt/cloud/{0}/destroying'.format(name),
args={'name': name},
sock_dir=opts['sock_dir'],
transport=opts['transport']
)
my_info = _get_my_info(name)
if my_info:
profile_name = my_info[name]['profile']
profile = opts['profiles'][profile_name]
host = profile['host']
local = salt.client.LocalClient()
ret = local.cmd(host, 'vagrant.destroy', [name])
if ret[host]:
__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 {'Destroyed': '{0} was destroyed.'.format(name)}
else:
return {'Error': 'Error destroying {}'.format(name)}
else:
return {'Error': 'No response from {}. Cannot destroy.'.format(name)}
# noinspection PyTypeChecker
def reboot(name, call=None):
'''
Reboot a vagrant minion.
name
The name of the VM to reboot.
CLI Example:
.. code-block:: bash
salt-cloud -a reboot vm_name
'''
if call != 'action':
raise SaltCloudException(
'The reboot action must be called with -a or --action.'
)
my_info = _get_my_info(name)
profile_name = my_info[name]['profile']
profile = __opts__['profiles'][profile_name]
host = profile['host']
local = salt.client.LocalClient()
return local.cmd(host, 'vagrant.reboot', [name])
|
saltstack/salt
|
salt/cloud/clouds/vagrant.py
|
_list_nodes
|
python
|
def _list_nodes(call=None):
'''
List the nodes, ask all 'vagrant' minions, return dict of grains.
'''
local = salt.client.LocalClient()
ret = local.cmd('salt-cloud:driver:vagrant', 'grains.items', '', tgt_type='grain')
return ret
|
List the nodes, ask all 'vagrant' minions, return dict of grains.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/vagrant.py#L151-L157
|
[
"def cmd(self,\n tgt,\n fun,\n arg=(),\n timeout=None,\n tgt_type='glob',\n ret='',\n jid='',\n full_return=False,\n kwarg=None,\n **kwargs):\n '''\n Synchronously execute a command on targeted minions\n\n The cmd method will execute and wait for the timeout period for all\n minions to reply, then it will return all minion data at once.\n\n .. code-block:: python\n\n >>> import salt.client\n >>> local = salt.client.LocalClient()\n >>> local.cmd('*', 'cmd.run', ['whoami'])\n {'jerry': 'root'}\n\n With extra keyword arguments for the command function to be run:\n\n .. code-block:: python\n\n local.cmd('*', 'test.arg', ['arg1', 'arg2'], kwarg={'foo': 'bar'})\n\n Compound commands can be used for multiple executions in a single\n publish. Function names and function arguments are provided in separate\n lists but the index values must correlate and an empty list must be\n used if no arguments are required.\n\n .. code-block:: python\n\n >>> local.cmd('*', [\n 'grains.items',\n 'sys.doc',\n 'cmd.run',\n ],\n [\n [],\n [],\n ['uptime'],\n ])\n\n :param tgt: Which minions to target for the execution. Default is shell\n glob. Modified by the ``tgt_type`` option.\n :type tgt: string or list\n\n :param fun: The module and function to call on the specified minions of\n the form ``module.function``. For example ``test.ping`` or\n ``grains.items``.\n\n Compound commands\n Multiple functions may be called in a single publish by\n passing a list of commands. This can dramatically lower\n overhead and speed up the application communicating with Salt.\n\n This requires that the ``arg`` param is a list of lists. The\n ``fun`` list and the ``arg`` list must correlate by index\n meaning a function that does not take arguments must still have\n a corresponding empty list at the expected index.\n :type fun: string or list of strings\n\n :param arg: A list of arguments to pass to the remote function. If the\n function takes no arguments ``arg`` may be omitted except when\n executing a compound command.\n :type arg: list or list-of-lists\n\n :param timeout: Seconds to wait after the last minion returns but\n before all minions return.\n\n :param tgt_type: The type of ``tgt``. Allowed values:\n\n * ``glob`` - Bash glob completion - Default\n * ``pcre`` - Perl style regular expression\n * ``list`` - Python list of hosts\n * ``grain`` - Match based on a grain comparison\n * ``grain_pcre`` - Grain comparison with a regex\n * ``pillar`` - Pillar data comparison\n * ``pillar_pcre`` - Pillar data comparison with a regex\n * ``nodegroup`` - Match on nodegroup\n * ``range`` - Use a Range server for matching\n * ``compound`` - Pass a compound match string\n * ``ipcidr`` - Match based on Subnet (CIDR notation) or IPv4 address.\n\n .. versionchanged:: 2017.7.0\n Renamed from ``expr_form`` to ``tgt_type``\n\n :param ret: The returner to use. The value passed can be single\n returner, or a comma delimited list of returners to call in order\n on the minions\n\n :param kwarg: A dictionary with keyword arguments for the function.\n\n :param full_return: Output the job return only (default) or the full\n return including exit code and other job metadata.\n\n :param kwargs: Optional keyword arguments.\n Authentication credentials may be passed when using\n :conf_master:`external_auth`.\n\n For example: ``local.cmd('*', 'test.ping', username='saltdev',\n password='saltdev', eauth='pam')``.\n Or: ``local.cmd('*', 'test.ping',\n token='5871821ea51754fdcea8153c1c745433')``\n\n :returns: A dictionary with the result of the execution, keyed by\n minion ID. A compound command will return a sub-dictionary keyed by\n function name.\n '''\n was_listening = self.event.cpub\n\n try:\n pub_data = self.run_job(tgt,\n fun,\n arg,\n tgt_type,\n ret,\n timeout,\n jid,\n kwarg=kwarg,\n listen=True,\n **kwargs)\n\n if not pub_data:\n return pub_data\n\n ret = {}\n for fn_ret in self.get_cli_event_returns(\n pub_data['jid'],\n pub_data['minions'],\n self._get_timeout(timeout),\n tgt,\n tgt_type,\n **kwargs):\n\n if fn_ret:\n for mid, data in six.iteritems(fn_ret):\n ret[mid] = (data if full_return\n else data.get('ret', {}))\n\n for failed in list(set(pub_data['minions']) - set(ret)):\n ret[failed] = False\n return ret\n finally:\n if not was_listening:\n self.event.close_pub()\n"
] |
# -*- coding: utf-8 -*-
'''
Vagrant Cloud Driver
====================
The Vagrant cloud is designed to "vagrant up" a virtual machine as a
Salt minion.
Use of this module requires some configuration in cloud profile and provider
files as described in the
:ref:`Getting Started with Vagrant <getting-started-with-vagrant>` documentation.
.. versionadded:: 2018.3.0
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import os
import tempfile
# Import salt libs
import salt.utils
import salt.config as config
import salt.client
from salt._compat import ipaddress
from salt.exceptions import SaltCloudException, SaltCloudSystemExit, SaltInvocationError
# Get logging started
log = logging.getLogger(__name__)
def __virtual__():
'''
Needs no special configuration
'''
return True
def avail_locations(call=None):
r'''
This function returns a list of locations available.
CLI Example:
.. code-block:: bash
salt-cloud --list-locations my-cloud-provider
# \[ vagrant will always returns an empty dictionary \]
'''
return {}
def avail_images(call=None):
'''This function returns a list of images available for this cloud provider.
vagrant will return a list of profiles.
salt-cloud --list-images my-cloud-provider
'''
vm_ = get_configured_provider()
return {'Profiles': [profile for profile in vm_['profiles']]}
def avail_sizes(call=None):
r'''
This function returns a list of sizes available for this cloud provider.
CLI Example:
.. code-block:: bash
salt-cloud --list-sizes my-cloud-provider
# \[ vagrant always returns an empty dictionary \]
'''
return {}
def list_nodes(call=None):
'''
List the nodes which have salt-cloud:driver:vagrant grains.
CLI Example:
.. code-block:: bash
salt-cloud -Q
'''
nodes = _list_nodes(call)
return _build_required_items(nodes)
def _build_required_items(nodes):
ret = {}
for name, grains in nodes.items():
if grains:
private_ips = []
public_ips = []
ips = grains['ipv4'] + grains['ipv6']
for adrs in ips:
ip_ = ipaddress.ip_address(adrs)
if not ip_.is_loopback:
if ip_.is_private:
private_ips.append(adrs)
else:
public_ips.append(adrs)
ret[name] = {
'id': grains['id'],
'image': grains['salt-cloud']['profile'],
'private_ips': private_ips,
'public_ips': public_ips,
'size': '',
'state': 'running'
}
return ret
def list_nodes_full(call=None):
'''
List the nodes, ask all 'vagrant' minions, return dict of grains (enhanced).
CLI Example:
.. code-block:: bash
salt-call -F
'''
ret = _list_nodes(call)
for key, grains in ret.items(): # clean up some hyperverbose grains -- everything is too much
try:
del grains['cpu_flags'], grains['disks'], grains['pythonpath'], grains['dns'], grains['gpus']
except KeyError:
pass # ignore absence of things we are eliminating
except TypeError:
del ret[key] # eliminate all reference to unexpected (None) values.
reqs = _build_required_items(ret)
for name in ret:
ret[name].update(reqs[name])
return ret
def list_nodes_select(call=None):
'''
Return a list of the minions that have salt-cloud grains, with
select fields.
'''
return salt.utils.cloud.list_nodes_select(
list_nodes_full('function'), __opts__['query.selection'], call,
)
def show_instance(name, call=None):
'''
List the a single node, return dict of grains.
'''
local = salt.client.LocalClient()
ret = local.cmd(name, 'grains.items', '')
reqs = _build_required_items(ret)
ret[name].update(reqs[name])
return ret
def _get_my_info(name):
local = salt.client.LocalClient()
return local.cmd(name, 'grains.get', ['salt-cloud'])
def create(vm_):
'''
Provision a single machine
CLI Example:
.. code-block:: bash
salt-cloud -p my_profile new_node_1
'''
name = vm_['name']
machine = config.get_cloud_config_value(
'machine', vm_, __opts__, default='')
vm_['machine'] = machine
host = config.get_cloud_config_value(
'host', vm_, __opts__, default=NotImplemented)
vm_['cwd'] = config.get_cloud_config_value(
'cwd', vm_, __opts__, default='/')
vm_['runas'] = config.get_cloud_config_value(
'vagrant_runas', vm_, __opts__, default=os.getenv('SUDO_USER'))
vm_['timeout'] = config.get_cloud_config_value(
'vagrant_up_timeout', vm_, __opts__, default=300)
vm_['vagrant_provider'] = config.get_cloud_config_value(
'vagrant_provider', vm_, __opts__, default='')
vm_['grains'] = {'salt-cloud:vagrant': {'host': host, 'machine': machine}}
log.info('sending \'vagrant.init %s machine=%s\' command to %s', name, machine, host)
local = salt.client.LocalClient()
ret = local.cmd(host, 'vagrant.init', [name], kwarg={'vm': vm_, 'start': True})
log.info('response ==> %s', ret[host])
network_mask = config.get_cloud_config_value(
'network_mask', vm_, __opts__, default='')
if 'ssh_host' not in vm_:
ret = local.cmd(host,
'vagrant.get_ssh_config',
[name],
kwarg={'network_mask': network_mask,
'get_private_key': True})[host]
with tempfile.NamedTemporaryFile() as pks:
if 'private_key' not in vm_ and ret and ret.get('private_key', False):
pks.write(ret['private_key'])
pks.flush()
log.debug('wrote private key to %s', pks.name)
vm_['key_filename'] = pks.name
if 'ssh_host' not in vm_:
try:
vm_.setdefault('ssh_username', ret['ssh_username'])
if ret.get('ip_address'):
vm_['ssh_host'] = ret['ip_address']
else: # if probe failed or not used, use Vagrant's reported ssh info
vm_['ssh_host'] = ret['ssh_host']
vm_.setdefault('ssh_port', ret['ssh_port'])
except (KeyError, TypeError):
raise SaltInvocationError(
'Insufficient SSH addressing information for {}'.format(name))
log.info('Provisioning machine %s as node %s using ssh %s',
machine, name, vm_['ssh_host'])
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
return ret
def get_configured_provider():
'''
Return the first configured instance.
'''
ret = config.is_provider_configured(
__opts__,
__active_provider_name__ or 'vagrant',
''
)
return ret
# noinspection PyTypeChecker
def destroy(name, call=None):
'''
Destroy a node.
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.'
)
opts = __opts__
__utils__['cloud.fire_event'](
'event',
'destroying instance',
'salt/cloud/{0}/destroying'.format(name),
args={'name': name},
sock_dir=opts['sock_dir'],
transport=opts['transport']
)
my_info = _get_my_info(name)
if my_info:
profile_name = my_info[name]['profile']
profile = opts['profiles'][profile_name]
host = profile['host']
local = salt.client.LocalClient()
ret = local.cmd(host, 'vagrant.destroy', [name])
if ret[host]:
__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 {'Destroyed': '{0} was destroyed.'.format(name)}
else:
return {'Error': 'Error destroying {}'.format(name)}
else:
return {'Error': 'No response from {}. Cannot destroy.'.format(name)}
# noinspection PyTypeChecker
def reboot(name, call=None):
'''
Reboot a vagrant minion.
name
The name of the VM to reboot.
CLI Example:
.. code-block:: bash
salt-cloud -a reboot vm_name
'''
if call != 'action':
raise SaltCloudException(
'The reboot action must be called with -a or --action.'
)
my_info = _get_my_info(name)
profile_name = my_info[name]['profile']
profile = __opts__['profiles'][profile_name]
host = profile['host']
local = salt.client.LocalClient()
return local.cmd(host, 'vagrant.reboot', [name])
|
saltstack/salt
|
salt/cloud/clouds/vagrant.py
|
create
|
python
|
def create(vm_):
'''
Provision a single machine
CLI Example:
.. code-block:: bash
salt-cloud -p my_profile new_node_1
'''
name = vm_['name']
machine = config.get_cloud_config_value(
'machine', vm_, __opts__, default='')
vm_['machine'] = machine
host = config.get_cloud_config_value(
'host', vm_, __opts__, default=NotImplemented)
vm_['cwd'] = config.get_cloud_config_value(
'cwd', vm_, __opts__, default='/')
vm_['runas'] = config.get_cloud_config_value(
'vagrant_runas', vm_, __opts__, default=os.getenv('SUDO_USER'))
vm_['timeout'] = config.get_cloud_config_value(
'vagrant_up_timeout', vm_, __opts__, default=300)
vm_['vagrant_provider'] = config.get_cloud_config_value(
'vagrant_provider', vm_, __opts__, default='')
vm_['grains'] = {'salt-cloud:vagrant': {'host': host, 'machine': machine}}
log.info('sending \'vagrant.init %s machine=%s\' command to %s', name, machine, host)
local = salt.client.LocalClient()
ret = local.cmd(host, 'vagrant.init', [name], kwarg={'vm': vm_, 'start': True})
log.info('response ==> %s', ret[host])
network_mask = config.get_cloud_config_value(
'network_mask', vm_, __opts__, default='')
if 'ssh_host' not in vm_:
ret = local.cmd(host,
'vagrant.get_ssh_config',
[name],
kwarg={'network_mask': network_mask,
'get_private_key': True})[host]
with tempfile.NamedTemporaryFile() as pks:
if 'private_key' not in vm_ and ret and ret.get('private_key', False):
pks.write(ret['private_key'])
pks.flush()
log.debug('wrote private key to %s', pks.name)
vm_['key_filename'] = pks.name
if 'ssh_host' not in vm_:
try:
vm_.setdefault('ssh_username', ret['ssh_username'])
if ret.get('ip_address'):
vm_['ssh_host'] = ret['ip_address']
else: # if probe failed or not used, use Vagrant's reported ssh info
vm_['ssh_host'] = ret['ssh_host']
vm_.setdefault('ssh_port', ret['ssh_port'])
except (KeyError, TypeError):
raise SaltInvocationError(
'Insufficient SSH addressing information for {}'.format(name))
log.info('Provisioning machine %s as node %s using ssh %s',
machine, name, vm_['ssh_host'])
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
return ret
|
Provision a single machine
CLI Example:
.. code-block:: bash
salt-cloud -p my_profile new_node_1
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/vagrant.py#L186-L248
|
[
"def get_cloud_config_value(name, vm_, opts, default=None, search_global=True):\n '''\n Search and return a setting in a known order:\n\n 1. In the virtual machine's configuration\n 2. In the virtual machine's profile configuration\n 3. In the virtual machine's provider configuration\n 4. In the salt cloud configuration if global searching is enabled\n 5. Return the provided default\n '''\n\n # As a last resort, return the default\n value = default\n\n if search_global is True and opts.get(name, None) is not None:\n # The setting name exists in the cloud(global) configuration\n value = deepcopy(opts[name])\n\n if vm_ and name:\n # Let's get the value from the profile, if present\n if 'profile' in vm_ and vm_['profile'] is not None:\n if name in opts['profiles'][vm_['profile']]:\n if isinstance(value, dict):\n value.update(opts['profiles'][vm_['profile']][name].copy())\n else:\n value = deepcopy(opts['profiles'][vm_['profile']][name])\n\n # Let's get the value from the provider, if present.\n if ':' in vm_['driver']:\n # The provider is defined as <provider-alias>:<driver-name>\n alias, driver = vm_['driver'].split(':')\n if alias in opts['providers'] and \\\n driver in opts['providers'][alias]:\n details = opts['providers'][alias][driver]\n if name in details:\n if isinstance(value, dict):\n value.update(details[name].copy())\n else:\n value = deepcopy(details[name])\n elif len(opts['providers'].get(vm_['driver'], ())) > 1:\n # The provider is NOT defined as <provider-alias>:<driver-name>\n # and there's more than one entry under the alias.\n # WARN the user!!!!\n log.error(\n \"The '%s' cloud provider definition has more than one \"\n 'entry. Your VM configuration should be specifying the '\n \"provider as 'driver: %s:<driver-engine>'. Since \"\n \"it's not, we're returning the first definition which \"\n 'might not be what you intended.',\n vm_['driver'], vm_['driver']\n )\n\n if vm_['driver'] in opts['providers']:\n # There's only one driver defined for this provider. This is safe.\n alias_defs = opts['providers'].get(vm_['driver'])\n provider_driver_defs = alias_defs[next(iter(list(alias_defs.keys())))]\n if name in provider_driver_defs:\n # The setting name exists in the VM's provider configuration.\n # Return it!\n if isinstance(value, dict):\n value.update(provider_driver_defs[name].copy())\n else:\n value = deepcopy(provider_driver_defs[name])\n\n if name and vm_ and name in vm_:\n # The setting name exists in VM configuration.\n if isinstance(vm_[name], types.GeneratorType):\n value = next(vm_[name], '')\n else:\n if isinstance(value, dict) and isinstance(vm_[name], dict):\n value.update(vm_[name].copy())\n else:\n value = deepcopy(vm_[name])\n\n return value\n",
"def cmd(self,\n tgt,\n fun,\n arg=(),\n timeout=None,\n tgt_type='glob',\n ret='',\n jid='',\n full_return=False,\n kwarg=None,\n **kwargs):\n '''\n Synchronously execute a command on targeted minions\n\n The cmd method will execute and wait for the timeout period for all\n minions to reply, then it will return all minion data at once.\n\n .. code-block:: python\n\n >>> import salt.client\n >>> local = salt.client.LocalClient()\n >>> local.cmd('*', 'cmd.run', ['whoami'])\n {'jerry': 'root'}\n\n With extra keyword arguments for the command function to be run:\n\n .. code-block:: python\n\n local.cmd('*', 'test.arg', ['arg1', 'arg2'], kwarg={'foo': 'bar'})\n\n Compound commands can be used for multiple executions in a single\n publish. Function names and function arguments are provided in separate\n lists but the index values must correlate and an empty list must be\n used if no arguments are required.\n\n .. code-block:: python\n\n >>> local.cmd('*', [\n 'grains.items',\n 'sys.doc',\n 'cmd.run',\n ],\n [\n [],\n [],\n ['uptime'],\n ])\n\n :param tgt: Which minions to target for the execution. Default is shell\n glob. Modified by the ``tgt_type`` option.\n :type tgt: string or list\n\n :param fun: The module and function to call on the specified minions of\n the form ``module.function``. For example ``test.ping`` or\n ``grains.items``.\n\n Compound commands\n Multiple functions may be called in a single publish by\n passing a list of commands. This can dramatically lower\n overhead and speed up the application communicating with Salt.\n\n This requires that the ``arg`` param is a list of lists. The\n ``fun`` list and the ``arg`` list must correlate by index\n meaning a function that does not take arguments must still have\n a corresponding empty list at the expected index.\n :type fun: string or list of strings\n\n :param arg: A list of arguments to pass to the remote function. If the\n function takes no arguments ``arg`` may be omitted except when\n executing a compound command.\n :type arg: list or list-of-lists\n\n :param timeout: Seconds to wait after the last minion returns but\n before all minions return.\n\n :param tgt_type: The type of ``tgt``. Allowed values:\n\n * ``glob`` - Bash glob completion - Default\n * ``pcre`` - Perl style regular expression\n * ``list`` - Python list of hosts\n * ``grain`` - Match based on a grain comparison\n * ``grain_pcre`` - Grain comparison with a regex\n * ``pillar`` - Pillar data comparison\n * ``pillar_pcre`` - Pillar data comparison with a regex\n * ``nodegroup`` - Match on nodegroup\n * ``range`` - Use a Range server for matching\n * ``compound`` - Pass a compound match string\n * ``ipcidr`` - Match based on Subnet (CIDR notation) or IPv4 address.\n\n .. versionchanged:: 2017.7.0\n Renamed from ``expr_form`` to ``tgt_type``\n\n :param ret: The returner to use. The value passed can be single\n returner, or a comma delimited list of returners to call in order\n on the minions\n\n :param kwarg: A dictionary with keyword arguments for the function.\n\n :param full_return: Output the job return only (default) or the full\n return including exit code and other job metadata.\n\n :param kwargs: Optional keyword arguments.\n Authentication credentials may be passed when using\n :conf_master:`external_auth`.\n\n For example: ``local.cmd('*', 'test.ping', username='saltdev',\n password='saltdev', eauth='pam')``.\n Or: ``local.cmd('*', 'test.ping',\n token='5871821ea51754fdcea8153c1c745433')``\n\n :returns: A dictionary with the result of the execution, keyed by\n minion ID. A compound command will return a sub-dictionary keyed by\n function name.\n '''\n was_listening = self.event.cpub\n\n try:\n pub_data = self.run_job(tgt,\n fun,\n arg,\n tgt_type,\n ret,\n timeout,\n jid,\n kwarg=kwarg,\n listen=True,\n **kwargs)\n\n if not pub_data:\n return pub_data\n\n ret = {}\n for fn_ret in self.get_cli_event_returns(\n pub_data['jid'],\n pub_data['minions'],\n self._get_timeout(timeout),\n tgt,\n tgt_type,\n **kwargs):\n\n if fn_ret:\n for mid, data in six.iteritems(fn_ret):\n ret[mid] = (data if full_return\n else data.get('ret', {}))\n\n for failed in list(set(pub_data['minions']) - set(ret)):\n ret[failed] = False\n return ret\n finally:\n if not was_listening:\n self.event.close_pub()\n"
] |
# -*- coding: utf-8 -*-
'''
Vagrant Cloud Driver
====================
The Vagrant cloud is designed to "vagrant up" a virtual machine as a
Salt minion.
Use of this module requires some configuration in cloud profile and provider
files as described in the
:ref:`Getting Started with Vagrant <getting-started-with-vagrant>` documentation.
.. versionadded:: 2018.3.0
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import os
import tempfile
# Import salt libs
import salt.utils
import salt.config as config
import salt.client
from salt._compat import ipaddress
from salt.exceptions import SaltCloudException, SaltCloudSystemExit, SaltInvocationError
# Get logging started
log = logging.getLogger(__name__)
def __virtual__():
'''
Needs no special configuration
'''
return True
def avail_locations(call=None):
r'''
This function returns a list of locations available.
CLI Example:
.. code-block:: bash
salt-cloud --list-locations my-cloud-provider
# \[ vagrant will always returns an empty dictionary \]
'''
return {}
def avail_images(call=None):
'''This function returns a list of images available for this cloud provider.
vagrant will return a list of profiles.
salt-cloud --list-images my-cloud-provider
'''
vm_ = get_configured_provider()
return {'Profiles': [profile for profile in vm_['profiles']]}
def avail_sizes(call=None):
r'''
This function returns a list of sizes available for this cloud provider.
CLI Example:
.. code-block:: bash
salt-cloud --list-sizes my-cloud-provider
# \[ vagrant always returns an empty dictionary \]
'''
return {}
def list_nodes(call=None):
'''
List the nodes which have salt-cloud:driver:vagrant grains.
CLI Example:
.. code-block:: bash
salt-cloud -Q
'''
nodes = _list_nodes(call)
return _build_required_items(nodes)
def _build_required_items(nodes):
ret = {}
for name, grains in nodes.items():
if grains:
private_ips = []
public_ips = []
ips = grains['ipv4'] + grains['ipv6']
for adrs in ips:
ip_ = ipaddress.ip_address(adrs)
if not ip_.is_loopback:
if ip_.is_private:
private_ips.append(adrs)
else:
public_ips.append(adrs)
ret[name] = {
'id': grains['id'],
'image': grains['salt-cloud']['profile'],
'private_ips': private_ips,
'public_ips': public_ips,
'size': '',
'state': 'running'
}
return ret
def list_nodes_full(call=None):
'''
List the nodes, ask all 'vagrant' minions, return dict of grains (enhanced).
CLI Example:
.. code-block:: bash
salt-call -F
'''
ret = _list_nodes(call)
for key, grains in ret.items(): # clean up some hyperverbose grains -- everything is too much
try:
del grains['cpu_flags'], grains['disks'], grains['pythonpath'], grains['dns'], grains['gpus']
except KeyError:
pass # ignore absence of things we are eliminating
except TypeError:
del ret[key] # eliminate all reference to unexpected (None) values.
reqs = _build_required_items(ret)
for name in ret:
ret[name].update(reqs[name])
return ret
def _list_nodes(call=None):
'''
List the nodes, ask all 'vagrant' minions, return dict of grains.
'''
local = salt.client.LocalClient()
ret = local.cmd('salt-cloud:driver:vagrant', 'grains.items', '', tgt_type='grain')
return ret
def list_nodes_select(call=None):
'''
Return a list of the minions that have salt-cloud grains, with
select fields.
'''
return salt.utils.cloud.list_nodes_select(
list_nodes_full('function'), __opts__['query.selection'], call,
)
def show_instance(name, call=None):
'''
List the a single node, return dict of grains.
'''
local = salt.client.LocalClient()
ret = local.cmd(name, 'grains.items', '')
reqs = _build_required_items(ret)
ret[name].update(reqs[name])
return ret
def _get_my_info(name):
local = salt.client.LocalClient()
return local.cmd(name, 'grains.get', ['salt-cloud'])
def get_configured_provider():
'''
Return the first configured instance.
'''
ret = config.is_provider_configured(
__opts__,
__active_provider_name__ or 'vagrant',
''
)
return ret
# noinspection PyTypeChecker
def destroy(name, call=None):
'''
Destroy a node.
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.'
)
opts = __opts__
__utils__['cloud.fire_event'](
'event',
'destroying instance',
'salt/cloud/{0}/destroying'.format(name),
args={'name': name},
sock_dir=opts['sock_dir'],
transport=opts['transport']
)
my_info = _get_my_info(name)
if my_info:
profile_name = my_info[name]['profile']
profile = opts['profiles'][profile_name]
host = profile['host']
local = salt.client.LocalClient()
ret = local.cmd(host, 'vagrant.destroy', [name])
if ret[host]:
__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 {'Destroyed': '{0} was destroyed.'.format(name)}
else:
return {'Error': 'Error destroying {}'.format(name)}
else:
return {'Error': 'No response from {}. Cannot destroy.'.format(name)}
# noinspection PyTypeChecker
def reboot(name, call=None):
'''
Reboot a vagrant minion.
name
The name of the VM to reboot.
CLI Example:
.. code-block:: bash
salt-cloud -a reboot vm_name
'''
if call != 'action':
raise SaltCloudException(
'The reboot action must be called with -a or --action.'
)
my_info = _get_my_info(name)
profile_name = my_info[name]['profile']
profile = __opts__['profiles'][profile_name]
host = profile['host']
local = salt.client.LocalClient()
return local.cmd(host, 'vagrant.reboot', [name])
|
saltstack/salt
|
salt/cloud/clouds/vagrant.py
|
destroy
|
python
|
def destroy(name, call=None):
'''
Destroy a node.
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.'
)
opts = __opts__
__utils__['cloud.fire_event'](
'event',
'destroying instance',
'salt/cloud/{0}/destroying'.format(name),
args={'name': name},
sock_dir=opts['sock_dir'],
transport=opts['transport']
)
my_info = _get_my_info(name)
if my_info:
profile_name = my_info[name]['profile']
profile = opts['profiles'][profile_name]
host = profile['host']
local = salt.client.LocalClient()
ret = local.cmd(host, 'vagrant.destroy', [name])
if ret[host]:
__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 {'Destroyed': '{0} was destroyed.'.format(name)}
else:
return {'Error': 'Error destroying {}'.format(name)}
else:
return {'Error': 'No response from {}. Cannot destroy.'.format(name)}
|
Destroy a node.
CLI Example:
.. code-block:: bash
salt-cloud --destroy mymachine
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/vagrant.py#L264-L316
|
[
"def _get_my_info(name):\n local = salt.client.LocalClient()\n return local.cmd(name, 'grains.get', ['salt-cloud'])\n",
"def cmd(self,\n tgt,\n fun,\n arg=(),\n timeout=None,\n tgt_type='glob',\n ret='',\n jid='',\n full_return=False,\n kwarg=None,\n **kwargs):\n '''\n Synchronously execute a command on targeted minions\n\n The cmd method will execute and wait for the timeout period for all\n minions to reply, then it will return all minion data at once.\n\n .. code-block:: python\n\n >>> import salt.client\n >>> local = salt.client.LocalClient()\n >>> local.cmd('*', 'cmd.run', ['whoami'])\n {'jerry': 'root'}\n\n With extra keyword arguments for the command function to be run:\n\n .. code-block:: python\n\n local.cmd('*', 'test.arg', ['arg1', 'arg2'], kwarg={'foo': 'bar'})\n\n Compound commands can be used for multiple executions in a single\n publish. Function names and function arguments are provided in separate\n lists but the index values must correlate and an empty list must be\n used if no arguments are required.\n\n .. code-block:: python\n\n >>> local.cmd('*', [\n 'grains.items',\n 'sys.doc',\n 'cmd.run',\n ],\n [\n [],\n [],\n ['uptime'],\n ])\n\n :param tgt: Which minions to target for the execution. Default is shell\n glob. Modified by the ``tgt_type`` option.\n :type tgt: string or list\n\n :param fun: The module and function to call on the specified minions of\n the form ``module.function``. For example ``test.ping`` or\n ``grains.items``.\n\n Compound commands\n Multiple functions may be called in a single publish by\n passing a list of commands. This can dramatically lower\n overhead and speed up the application communicating with Salt.\n\n This requires that the ``arg`` param is a list of lists. The\n ``fun`` list and the ``arg`` list must correlate by index\n meaning a function that does not take arguments must still have\n a corresponding empty list at the expected index.\n :type fun: string or list of strings\n\n :param arg: A list of arguments to pass to the remote function. If the\n function takes no arguments ``arg`` may be omitted except when\n executing a compound command.\n :type arg: list or list-of-lists\n\n :param timeout: Seconds to wait after the last minion returns but\n before all minions return.\n\n :param tgt_type: The type of ``tgt``. Allowed values:\n\n * ``glob`` - Bash glob completion - Default\n * ``pcre`` - Perl style regular expression\n * ``list`` - Python list of hosts\n * ``grain`` - Match based on a grain comparison\n * ``grain_pcre`` - Grain comparison with a regex\n * ``pillar`` - Pillar data comparison\n * ``pillar_pcre`` - Pillar data comparison with a regex\n * ``nodegroup`` - Match on nodegroup\n * ``range`` - Use a Range server for matching\n * ``compound`` - Pass a compound match string\n * ``ipcidr`` - Match based on Subnet (CIDR notation) or IPv4 address.\n\n .. versionchanged:: 2017.7.0\n Renamed from ``expr_form`` to ``tgt_type``\n\n :param ret: The returner to use. The value passed can be single\n returner, or a comma delimited list of returners to call in order\n on the minions\n\n :param kwarg: A dictionary with keyword arguments for the function.\n\n :param full_return: Output the job return only (default) or the full\n return including exit code and other job metadata.\n\n :param kwargs: Optional keyword arguments.\n Authentication credentials may be passed when using\n :conf_master:`external_auth`.\n\n For example: ``local.cmd('*', 'test.ping', username='saltdev',\n password='saltdev', eauth='pam')``.\n Or: ``local.cmd('*', 'test.ping',\n token='5871821ea51754fdcea8153c1c745433')``\n\n :returns: A dictionary with the result of the execution, keyed by\n minion ID. A compound command will return a sub-dictionary keyed by\n function name.\n '''\n was_listening = self.event.cpub\n\n try:\n pub_data = self.run_job(tgt,\n fun,\n arg,\n tgt_type,\n ret,\n timeout,\n jid,\n kwarg=kwarg,\n listen=True,\n **kwargs)\n\n if not pub_data:\n return pub_data\n\n ret = {}\n for fn_ret in self.get_cli_event_returns(\n pub_data['jid'],\n pub_data['minions'],\n self._get_timeout(timeout),\n tgt,\n tgt_type,\n **kwargs):\n\n if fn_ret:\n for mid, data in six.iteritems(fn_ret):\n ret[mid] = (data if full_return\n else data.get('ret', {}))\n\n for failed in list(set(pub_data['minions']) - set(ret)):\n ret[failed] = False\n return ret\n finally:\n if not was_listening:\n self.event.close_pub()\n"
] |
# -*- coding: utf-8 -*-
'''
Vagrant Cloud Driver
====================
The Vagrant cloud is designed to "vagrant up" a virtual machine as a
Salt minion.
Use of this module requires some configuration in cloud profile and provider
files as described in the
:ref:`Getting Started with Vagrant <getting-started-with-vagrant>` documentation.
.. versionadded:: 2018.3.0
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import os
import tempfile
# Import salt libs
import salt.utils
import salt.config as config
import salt.client
from salt._compat import ipaddress
from salt.exceptions import SaltCloudException, SaltCloudSystemExit, SaltInvocationError
# Get logging started
log = logging.getLogger(__name__)
def __virtual__():
'''
Needs no special configuration
'''
return True
def avail_locations(call=None):
r'''
This function returns a list of locations available.
CLI Example:
.. code-block:: bash
salt-cloud --list-locations my-cloud-provider
# \[ vagrant will always returns an empty dictionary \]
'''
return {}
def avail_images(call=None):
'''This function returns a list of images available for this cloud provider.
vagrant will return a list of profiles.
salt-cloud --list-images my-cloud-provider
'''
vm_ = get_configured_provider()
return {'Profiles': [profile for profile in vm_['profiles']]}
def avail_sizes(call=None):
r'''
This function returns a list of sizes available for this cloud provider.
CLI Example:
.. code-block:: bash
salt-cloud --list-sizes my-cloud-provider
# \[ vagrant always returns an empty dictionary \]
'''
return {}
def list_nodes(call=None):
'''
List the nodes which have salt-cloud:driver:vagrant grains.
CLI Example:
.. code-block:: bash
salt-cloud -Q
'''
nodes = _list_nodes(call)
return _build_required_items(nodes)
def _build_required_items(nodes):
ret = {}
for name, grains in nodes.items():
if grains:
private_ips = []
public_ips = []
ips = grains['ipv4'] + grains['ipv6']
for adrs in ips:
ip_ = ipaddress.ip_address(adrs)
if not ip_.is_loopback:
if ip_.is_private:
private_ips.append(adrs)
else:
public_ips.append(adrs)
ret[name] = {
'id': grains['id'],
'image': grains['salt-cloud']['profile'],
'private_ips': private_ips,
'public_ips': public_ips,
'size': '',
'state': 'running'
}
return ret
def list_nodes_full(call=None):
'''
List the nodes, ask all 'vagrant' minions, return dict of grains (enhanced).
CLI Example:
.. code-block:: bash
salt-call -F
'''
ret = _list_nodes(call)
for key, grains in ret.items(): # clean up some hyperverbose grains -- everything is too much
try:
del grains['cpu_flags'], grains['disks'], grains['pythonpath'], grains['dns'], grains['gpus']
except KeyError:
pass # ignore absence of things we are eliminating
except TypeError:
del ret[key] # eliminate all reference to unexpected (None) values.
reqs = _build_required_items(ret)
for name in ret:
ret[name].update(reqs[name])
return ret
def _list_nodes(call=None):
'''
List the nodes, ask all 'vagrant' minions, return dict of grains.
'''
local = salt.client.LocalClient()
ret = local.cmd('salt-cloud:driver:vagrant', 'grains.items', '', tgt_type='grain')
return ret
def list_nodes_select(call=None):
'''
Return a list of the minions that have salt-cloud grains, with
select fields.
'''
return salt.utils.cloud.list_nodes_select(
list_nodes_full('function'), __opts__['query.selection'], call,
)
def show_instance(name, call=None):
'''
List the a single node, return dict of grains.
'''
local = salt.client.LocalClient()
ret = local.cmd(name, 'grains.items', '')
reqs = _build_required_items(ret)
ret[name].update(reqs[name])
return ret
def _get_my_info(name):
local = salt.client.LocalClient()
return local.cmd(name, 'grains.get', ['salt-cloud'])
def create(vm_):
'''
Provision a single machine
CLI Example:
.. code-block:: bash
salt-cloud -p my_profile new_node_1
'''
name = vm_['name']
machine = config.get_cloud_config_value(
'machine', vm_, __opts__, default='')
vm_['machine'] = machine
host = config.get_cloud_config_value(
'host', vm_, __opts__, default=NotImplemented)
vm_['cwd'] = config.get_cloud_config_value(
'cwd', vm_, __opts__, default='/')
vm_['runas'] = config.get_cloud_config_value(
'vagrant_runas', vm_, __opts__, default=os.getenv('SUDO_USER'))
vm_['timeout'] = config.get_cloud_config_value(
'vagrant_up_timeout', vm_, __opts__, default=300)
vm_['vagrant_provider'] = config.get_cloud_config_value(
'vagrant_provider', vm_, __opts__, default='')
vm_['grains'] = {'salt-cloud:vagrant': {'host': host, 'machine': machine}}
log.info('sending \'vagrant.init %s machine=%s\' command to %s', name, machine, host)
local = salt.client.LocalClient()
ret = local.cmd(host, 'vagrant.init', [name], kwarg={'vm': vm_, 'start': True})
log.info('response ==> %s', ret[host])
network_mask = config.get_cloud_config_value(
'network_mask', vm_, __opts__, default='')
if 'ssh_host' not in vm_:
ret = local.cmd(host,
'vagrant.get_ssh_config',
[name],
kwarg={'network_mask': network_mask,
'get_private_key': True})[host]
with tempfile.NamedTemporaryFile() as pks:
if 'private_key' not in vm_ and ret and ret.get('private_key', False):
pks.write(ret['private_key'])
pks.flush()
log.debug('wrote private key to %s', pks.name)
vm_['key_filename'] = pks.name
if 'ssh_host' not in vm_:
try:
vm_.setdefault('ssh_username', ret['ssh_username'])
if ret.get('ip_address'):
vm_['ssh_host'] = ret['ip_address']
else: # if probe failed or not used, use Vagrant's reported ssh info
vm_['ssh_host'] = ret['ssh_host']
vm_.setdefault('ssh_port', ret['ssh_port'])
except (KeyError, TypeError):
raise SaltInvocationError(
'Insufficient SSH addressing information for {}'.format(name))
log.info('Provisioning machine %s as node %s using ssh %s',
machine, name, vm_['ssh_host'])
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
return ret
def get_configured_provider():
'''
Return the first configured instance.
'''
ret = config.is_provider_configured(
__opts__,
__active_provider_name__ or 'vagrant',
''
)
return ret
# noinspection PyTypeChecker
# noinspection PyTypeChecker
def reboot(name, call=None):
'''
Reboot a vagrant minion.
name
The name of the VM to reboot.
CLI Example:
.. code-block:: bash
salt-cloud -a reboot vm_name
'''
if call != 'action':
raise SaltCloudException(
'The reboot action must be called with -a or --action.'
)
my_info = _get_my_info(name)
profile_name = my_info[name]['profile']
profile = __opts__['profiles'][profile_name]
host = profile['host']
local = salt.client.LocalClient()
return local.cmd(host, 'vagrant.reboot', [name])
|
saltstack/salt
|
salt/cloud/clouds/vagrant.py
|
reboot
|
python
|
def reboot(name, call=None):
'''
Reboot a vagrant minion.
name
The name of the VM to reboot.
CLI Example:
.. code-block:: bash
salt-cloud -a reboot vm_name
'''
if call != 'action':
raise SaltCloudException(
'The reboot action must be called with -a or --action.'
)
my_info = _get_my_info(name)
profile_name = my_info[name]['profile']
profile = __opts__['profiles'][profile_name]
host = profile['host']
local = salt.client.LocalClient()
return local.cmd(host, 'vagrant.reboot', [name])
|
Reboot a vagrant minion.
name
The name of the VM to reboot.
CLI Example:
.. code-block:: bash
salt-cloud -a reboot vm_name
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/vagrant.py#L320-L342
|
[
"def _get_my_info(name):\n local = salt.client.LocalClient()\n return local.cmd(name, 'grains.get', ['salt-cloud'])\n",
"def cmd(self,\n tgt,\n fun,\n arg=(),\n timeout=None,\n tgt_type='glob',\n ret='',\n jid='',\n full_return=False,\n kwarg=None,\n **kwargs):\n '''\n Synchronously execute a command on targeted minions\n\n The cmd method will execute and wait for the timeout period for all\n minions to reply, then it will return all minion data at once.\n\n .. code-block:: python\n\n >>> import salt.client\n >>> local = salt.client.LocalClient()\n >>> local.cmd('*', 'cmd.run', ['whoami'])\n {'jerry': 'root'}\n\n With extra keyword arguments for the command function to be run:\n\n .. code-block:: python\n\n local.cmd('*', 'test.arg', ['arg1', 'arg2'], kwarg={'foo': 'bar'})\n\n Compound commands can be used for multiple executions in a single\n publish. Function names and function arguments are provided in separate\n lists but the index values must correlate and an empty list must be\n used if no arguments are required.\n\n .. code-block:: python\n\n >>> local.cmd('*', [\n 'grains.items',\n 'sys.doc',\n 'cmd.run',\n ],\n [\n [],\n [],\n ['uptime'],\n ])\n\n :param tgt: Which minions to target for the execution. Default is shell\n glob. Modified by the ``tgt_type`` option.\n :type tgt: string or list\n\n :param fun: The module and function to call on the specified minions of\n the form ``module.function``. For example ``test.ping`` or\n ``grains.items``.\n\n Compound commands\n Multiple functions may be called in a single publish by\n passing a list of commands. This can dramatically lower\n overhead and speed up the application communicating with Salt.\n\n This requires that the ``arg`` param is a list of lists. The\n ``fun`` list and the ``arg`` list must correlate by index\n meaning a function that does not take arguments must still have\n a corresponding empty list at the expected index.\n :type fun: string or list of strings\n\n :param arg: A list of arguments to pass to the remote function. If the\n function takes no arguments ``arg`` may be omitted except when\n executing a compound command.\n :type arg: list or list-of-lists\n\n :param timeout: Seconds to wait after the last minion returns but\n before all minions return.\n\n :param tgt_type: The type of ``tgt``. Allowed values:\n\n * ``glob`` - Bash glob completion - Default\n * ``pcre`` - Perl style regular expression\n * ``list`` - Python list of hosts\n * ``grain`` - Match based on a grain comparison\n * ``grain_pcre`` - Grain comparison with a regex\n * ``pillar`` - Pillar data comparison\n * ``pillar_pcre`` - Pillar data comparison with a regex\n * ``nodegroup`` - Match on nodegroup\n * ``range`` - Use a Range server for matching\n * ``compound`` - Pass a compound match string\n * ``ipcidr`` - Match based on Subnet (CIDR notation) or IPv4 address.\n\n .. versionchanged:: 2017.7.0\n Renamed from ``expr_form`` to ``tgt_type``\n\n :param ret: The returner to use. The value passed can be single\n returner, or a comma delimited list of returners to call in order\n on the minions\n\n :param kwarg: A dictionary with keyword arguments for the function.\n\n :param full_return: Output the job return only (default) or the full\n return including exit code and other job metadata.\n\n :param kwargs: Optional keyword arguments.\n Authentication credentials may be passed when using\n :conf_master:`external_auth`.\n\n For example: ``local.cmd('*', 'test.ping', username='saltdev',\n password='saltdev', eauth='pam')``.\n Or: ``local.cmd('*', 'test.ping',\n token='5871821ea51754fdcea8153c1c745433')``\n\n :returns: A dictionary with the result of the execution, keyed by\n minion ID. A compound command will return a sub-dictionary keyed by\n function name.\n '''\n was_listening = self.event.cpub\n\n try:\n pub_data = self.run_job(tgt,\n fun,\n arg,\n tgt_type,\n ret,\n timeout,\n jid,\n kwarg=kwarg,\n listen=True,\n **kwargs)\n\n if not pub_data:\n return pub_data\n\n ret = {}\n for fn_ret in self.get_cli_event_returns(\n pub_data['jid'],\n pub_data['minions'],\n self._get_timeout(timeout),\n tgt,\n tgt_type,\n **kwargs):\n\n if fn_ret:\n for mid, data in six.iteritems(fn_ret):\n ret[mid] = (data if full_return\n else data.get('ret', {}))\n\n for failed in list(set(pub_data['minions']) - set(ret)):\n ret[failed] = False\n return ret\n finally:\n if not was_listening:\n self.event.close_pub()\n"
] |
# -*- coding: utf-8 -*-
'''
Vagrant Cloud Driver
====================
The Vagrant cloud is designed to "vagrant up" a virtual machine as a
Salt minion.
Use of this module requires some configuration in cloud profile and provider
files as described in the
:ref:`Getting Started with Vagrant <getting-started-with-vagrant>` documentation.
.. versionadded:: 2018.3.0
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import os
import tempfile
# Import salt libs
import salt.utils
import salt.config as config
import salt.client
from salt._compat import ipaddress
from salt.exceptions import SaltCloudException, SaltCloudSystemExit, SaltInvocationError
# Get logging started
log = logging.getLogger(__name__)
def __virtual__():
'''
Needs no special configuration
'''
return True
def avail_locations(call=None):
r'''
This function returns a list of locations available.
CLI Example:
.. code-block:: bash
salt-cloud --list-locations my-cloud-provider
# \[ vagrant will always returns an empty dictionary \]
'''
return {}
def avail_images(call=None):
'''This function returns a list of images available for this cloud provider.
vagrant will return a list of profiles.
salt-cloud --list-images my-cloud-provider
'''
vm_ = get_configured_provider()
return {'Profiles': [profile for profile in vm_['profiles']]}
def avail_sizes(call=None):
r'''
This function returns a list of sizes available for this cloud provider.
CLI Example:
.. code-block:: bash
salt-cloud --list-sizes my-cloud-provider
# \[ vagrant always returns an empty dictionary \]
'''
return {}
def list_nodes(call=None):
'''
List the nodes which have salt-cloud:driver:vagrant grains.
CLI Example:
.. code-block:: bash
salt-cloud -Q
'''
nodes = _list_nodes(call)
return _build_required_items(nodes)
def _build_required_items(nodes):
ret = {}
for name, grains in nodes.items():
if grains:
private_ips = []
public_ips = []
ips = grains['ipv4'] + grains['ipv6']
for adrs in ips:
ip_ = ipaddress.ip_address(adrs)
if not ip_.is_loopback:
if ip_.is_private:
private_ips.append(adrs)
else:
public_ips.append(adrs)
ret[name] = {
'id': grains['id'],
'image': grains['salt-cloud']['profile'],
'private_ips': private_ips,
'public_ips': public_ips,
'size': '',
'state': 'running'
}
return ret
def list_nodes_full(call=None):
'''
List the nodes, ask all 'vagrant' minions, return dict of grains (enhanced).
CLI Example:
.. code-block:: bash
salt-call -F
'''
ret = _list_nodes(call)
for key, grains in ret.items(): # clean up some hyperverbose grains -- everything is too much
try:
del grains['cpu_flags'], grains['disks'], grains['pythonpath'], grains['dns'], grains['gpus']
except KeyError:
pass # ignore absence of things we are eliminating
except TypeError:
del ret[key] # eliminate all reference to unexpected (None) values.
reqs = _build_required_items(ret)
for name in ret:
ret[name].update(reqs[name])
return ret
def _list_nodes(call=None):
'''
List the nodes, ask all 'vagrant' minions, return dict of grains.
'''
local = salt.client.LocalClient()
ret = local.cmd('salt-cloud:driver:vagrant', 'grains.items', '', tgt_type='grain')
return ret
def list_nodes_select(call=None):
'''
Return a list of the minions that have salt-cloud grains, with
select fields.
'''
return salt.utils.cloud.list_nodes_select(
list_nodes_full('function'), __opts__['query.selection'], call,
)
def show_instance(name, call=None):
'''
List the a single node, return dict of grains.
'''
local = salt.client.LocalClient()
ret = local.cmd(name, 'grains.items', '')
reqs = _build_required_items(ret)
ret[name].update(reqs[name])
return ret
def _get_my_info(name):
local = salt.client.LocalClient()
return local.cmd(name, 'grains.get', ['salt-cloud'])
def create(vm_):
'''
Provision a single machine
CLI Example:
.. code-block:: bash
salt-cloud -p my_profile new_node_1
'''
name = vm_['name']
machine = config.get_cloud_config_value(
'machine', vm_, __opts__, default='')
vm_['machine'] = machine
host = config.get_cloud_config_value(
'host', vm_, __opts__, default=NotImplemented)
vm_['cwd'] = config.get_cloud_config_value(
'cwd', vm_, __opts__, default='/')
vm_['runas'] = config.get_cloud_config_value(
'vagrant_runas', vm_, __opts__, default=os.getenv('SUDO_USER'))
vm_['timeout'] = config.get_cloud_config_value(
'vagrant_up_timeout', vm_, __opts__, default=300)
vm_['vagrant_provider'] = config.get_cloud_config_value(
'vagrant_provider', vm_, __opts__, default='')
vm_['grains'] = {'salt-cloud:vagrant': {'host': host, 'machine': machine}}
log.info('sending \'vagrant.init %s machine=%s\' command to %s', name, machine, host)
local = salt.client.LocalClient()
ret = local.cmd(host, 'vagrant.init', [name], kwarg={'vm': vm_, 'start': True})
log.info('response ==> %s', ret[host])
network_mask = config.get_cloud_config_value(
'network_mask', vm_, __opts__, default='')
if 'ssh_host' not in vm_:
ret = local.cmd(host,
'vagrant.get_ssh_config',
[name],
kwarg={'network_mask': network_mask,
'get_private_key': True})[host]
with tempfile.NamedTemporaryFile() as pks:
if 'private_key' not in vm_ and ret and ret.get('private_key', False):
pks.write(ret['private_key'])
pks.flush()
log.debug('wrote private key to %s', pks.name)
vm_['key_filename'] = pks.name
if 'ssh_host' not in vm_:
try:
vm_.setdefault('ssh_username', ret['ssh_username'])
if ret.get('ip_address'):
vm_['ssh_host'] = ret['ip_address']
else: # if probe failed or not used, use Vagrant's reported ssh info
vm_['ssh_host'] = ret['ssh_host']
vm_.setdefault('ssh_port', ret['ssh_port'])
except (KeyError, TypeError):
raise SaltInvocationError(
'Insufficient SSH addressing information for {}'.format(name))
log.info('Provisioning machine %s as node %s using ssh %s',
machine, name, vm_['ssh_host'])
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
return ret
def get_configured_provider():
'''
Return the first configured instance.
'''
ret = config.is_provider_configured(
__opts__,
__active_provider_name__ or 'vagrant',
''
)
return ret
# noinspection PyTypeChecker
def destroy(name, call=None):
'''
Destroy a node.
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.'
)
opts = __opts__
__utils__['cloud.fire_event'](
'event',
'destroying instance',
'salt/cloud/{0}/destroying'.format(name),
args={'name': name},
sock_dir=opts['sock_dir'],
transport=opts['transport']
)
my_info = _get_my_info(name)
if my_info:
profile_name = my_info[name]['profile']
profile = opts['profiles'][profile_name]
host = profile['host']
local = salt.client.LocalClient()
ret = local.cmd(host, 'vagrant.destroy', [name])
if ret[host]:
__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 {'Destroyed': '{0} was destroyed.'.format(name)}
else:
return {'Error': 'Error destroying {}'.format(name)}
else:
return {'Error': 'No response from {}. Cannot destroy.'.format(name)}
# noinspection PyTypeChecker
|
saltstack/salt
|
salt/utils/pkg/__init__.py
|
clear_rtag
|
python
|
def clear_rtag(opts):
'''
Remove the rtag file
'''
try:
os.remove(rtag(opts))
except OSError as exc:
if exc.errno != errno.ENOENT:
# Using __str__() here to get the fully-formatted error message
# (error number, error message, path)
log.warning('Encountered error removing rtag: %s', exc.__str__())
|
Remove the rtag file
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/pkg/__init__.py#L28-L38
|
[
"def rtag(opts):\n '''\n Return the rtag file location. This file is used to ensure that we don't\n refresh more than once (unless explicitly configured to do so).\n '''\n return os.path.join(opts['cachedir'], 'pkg_refresh')\n"
] |
# -*- coding: utf-8 -*-
'''
Common functions for managing package refreshes during states
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import errno
import logging
import os
import re
# Import Salt libs
import salt.utils.data
import salt.utils.files
import salt.utils.versions
log = logging.getLogger(__name__)
def rtag(opts):
'''
Return the rtag file location. This file is used to ensure that we don't
refresh more than once (unless explicitly configured to do so).
'''
return os.path.join(opts['cachedir'], 'pkg_refresh')
def write_rtag(opts):
'''
Write the rtag file
'''
rtag_file = rtag(opts)
if not os.path.exists(rtag_file):
try:
with salt.utils.files.fopen(rtag_file, 'w+'):
pass
except OSError as exc:
log.warning('Encountered error writing rtag: %s', exc.__str__())
def check_refresh(opts, refresh=None):
'''
Check whether or not a refresh is necessary
Returns:
- True if refresh evaluates as True
- False if refresh is False
- A boolean if refresh is not False and the rtag file exists
'''
return bool(
salt.utils.data.is_true(refresh) or
(os.path.isfile(rtag(opts)) and refresh is not False)
)
def split_comparison(version):
match = re.match(r'^(<=>|!=|>=|<=|>>|<<|<>|>|<|=)?\s?([^<>=]+)$', version)
if match:
comparison = match.group(1) or ''
version = match.group(2)
else:
comparison = ''
return comparison, version
def match_version(desired, available, cmp_func=None, ignore_epoch=False):
'''
Returns the first version of the list of available versions which matches
the desired version comparison expression, or None if no match is found.
'''
oper, version = split_comparison(desired)
if not oper:
oper = '=='
for candidate in available:
if salt.utils.versions.compare(ver1=candidate,
oper=oper,
ver2=version,
cmp_func=cmp_func,
ignore_epoch=ignore_epoch):
return candidate
return None
|
saltstack/salt
|
salt/utils/pkg/__init__.py
|
write_rtag
|
python
|
def write_rtag(opts):
'''
Write the rtag file
'''
rtag_file = rtag(opts)
if not os.path.exists(rtag_file):
try:
with salt.utils.files.fopen(rtag_file, 'w+'):
pass
except OSError as exc:
log.warning('Encountered error writing rtag: %s', exc.__str__())
|
Write the rtag file
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/pkg/__init__.py#L41-L51
|
[
"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 rtag(opts):\n '''\n Return the rtag file location. This file is used to ensure that we don't\n refresh more than once (unless explicitly configured to do so).\n '''\n return os.path.join(opts['cachedir'], 'pkg_refresh')\n"
] |
# -*- coding: utf-8 -*-
'''
Common functions for managing package refreshes during states
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import errno
import logging
import os
import re
# Import Salt libs
import salt.utils.data
import salt.utils.files
import salt.utils.versions
log = logging.getLogger(__name__)
def rtag(opts):
'''
Return the rtag file location. This file is used to ensure that we don't
refresh more than once (unless explicitly configured to do so).
'''
return os.path.join(opts['cachedir'], 'pkg_refresh')
def clear_rtag(opts):
'''
Remove the rtag file
'''
try:
os.remove(rtag(opts))
except OSError as exc:
if exc.errno != errno.ENOENT:
# Using __str__() here to get the fully-formatted error message
# (error number, error message, path)
log.warning('Encountered error removing rtag: %s', exc.__str__())
def check_refresh(opts, refresh=None):
'''
Check whether or not a refresh is necessary
Returns:
- True if refresh evaluates as True
- False if refresh is False
- A boolean if refresh is not False and the rtag file exists
'''
return bool(
salt.utils.data.is_true(refresh) or
(os.path.isfile(rtag(opts)) and refresh is not False)
)
def split_comparison(version):
match = re.match(r'^(<=>|!=|>=|<=|>>|<<|<>|>|<|=)?\s?([^<>=]+)$', version)
if match:
comparison = match.group(1) or ''
version = match.group(2)
else:
comparison = ''
return comparison, version
def match_version(desired, available, cmp_func=None, ignore_epoch=False):
'''
Returns the first version of the list of available versions which matches
the desired version comparison expression, or None if no match is found.
'''
oper, version = split_comparison(desired)
if not oper:
oper = '=='
for candidate in available:
if salt.utils.versions.compare(ver1=candidate,
oper=oper,
ver2=version,
cmp_func=cmp_func,
ignore_epoch=ignore_epoch):
return candidate
return None
|
saltstack/salt
|
salt/utils/pkg/__init__.py
|
check_refresh
|
python
|
def check_refresh(opts, refresh=None):
'''
Check whether or not a refresh is necessary
Returns:
- True if refresh evaluates as True
- False if refresh is False
- A boolean if refresh is not False and the rtag file exists
'''
return bool(
salt.utils.data.is_true(refresh) or
(os.path.isfile(rtag(opts)) and refresh is not False)
)
|
Check whether or not a refresh is necessary
Returns:
- True if refresh evaluates as True
- False if refresh is False
- A boolean if refresh is not False and the rtag file exists
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/pkg/__init__.py#L54-L67
|
[
"def is_true(value=None):\n '''\n Returns a boolean value representing the \"truth\" of the value passed. The\n rules for what is a \"True\" value are:\n\n 1. Integer/float values greater than 0\n 2. The string values \"True\" and \"true\"\n 3. Any object for which bool(obj) returns True\n '''\n # First, try int/float conversion\n try:\n value = int(value)\n except (ValueError, TypeError):\n pass\n try:\n value = float(value)\n except (ValueError, TypeError):\n pass\n\n # Now check for truthiness\n if isinstance(value, (six.integer_types, float)):\n return value > 0\n elif isinstance(value, six.string_types):\n return six.text_type(value).lower() == 'true'\n else:\n return bool(value)\n",
"def rtag(opts):\n '''\n Return the rtag file location. This file is used to ensure that we don't\n refresh more than once (unless explicitly configured to do so).\n '''\n return os.path.join(opts['cachedir'], 'pkg_refresh')\n"
] |
# -*- coding: utf-8 -*-
'''
Common functions for managing package refreshes during states
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import errno
import logging
import os
import re
# Import Salt libs
import salt.utils.data
import salt.utils.files
import salt.utils.versions
log = logging.getLogger(__name__)
def rtag(opts):
'''
Return the rtag file location. This file is used to ensure that we don't
refresh more than once (unless explicitly configured to do so).
'''
return os.path.join(opts['cachedir'], 'pkg_refresh')
def clear_rtag(opts):
'''
Remove the rtag file
'''
try:
os.remove(rtag(opts))
except OSError as exc:
if exc.errno != errno.ENOENT:
# Using __str__() here to get the fully-formatted error message
# (error number, error message, path)
log.warning('Encountered error removing rtag: %s', exc.__str__())
def write_rtag(opts):
'''
Write the rtag file
'''
rtag_file = rtag(opts)
if not os.path.exists(rtag_file):
try:
with salt.utils.files.fopen(rtag_file, 'w+'):
pass
except OSError as exc:
log.warning('Encountered error writing rtag: %s', exc.__str__())
def split_comparison(version):
match = re.match(r'^(<=>|!=|>=|<=|>>|<<|<>|>|<|=)?\s?([^<>=]+)$', version)
if match:
comparison = match.group(1) or ''
version = match.group(2)
else:
comparison = ''
return comparison, version
def match_version(desired, available, cmp_func=None, ignore_epoch=False):
'''
Returns the first version of the list of available versions which matches
the desired version comparison expression, or None if no match is found.
'''
oper, version = split_comparison(desired)
if not oper:
oper = '=='
for candidate in available:
if salt.utils.versions.compare(ver1=candidate,
oper=oper,
ver2=version,
cmp_func=cmp_func,
ignore_epoch=ignore_epoch):
return candidate
return None
|
saltstack/salt
|
salt/utils/pkg/__init__.py
|
match_version
|
python
|
def match_version(desired, available, cmp_func=None, ignore_epoch=False):
'''
Returns the first version of the list of available versions which matches
the desired version comparison expression, or None if no match is found.
'''
oper, version = split_comparison(desired)
if not oper:
oper = '=='
for candidate in available:
if salt.utils.versions.compare(ver1=candidate,
oper=oper,
ver2=version,
cmp_func=cmp_func,
ignore_epoch=ignore_epoch):
return candidate
return None
|
Returns the first version of the list of available versions which matches
the desired version comparison expression, or None if no match is found.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/pkg/__init__.py#L80-L95
|
[
"def split_comparison(version):\n match = re.match(r'^(<=>|!=|>=|<=|>>|<<|<>|>|<|=)?\\s?([^<>=]+)$', version)\n if match:\n comparison = match.group(1) or ''\n version = match.group(2)\n else:\n comparison = ''\n return comparison, 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"
] |
# -*- coding: utf-8 -*-
'''
Common functions for managing package refreshes during states
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import errno
import logging
import os
import re
# Import Salt libs
import salt.utils.data
import salt.utils.files
import salt.utils.versions
log = logging.getLogger(__name__)
def rtag(opts):
'''
Return the rtag file location. This file is used to ensure that we don't
refresh more than once (unless explicitly configured to do so).
'''
return os.path.join(opts['cachedir'], 'pkg_refresh')
def clear_rtag(opts):
'''
Remove the rtag file
'''
try:
os.remove(rtag(opts))
except OSError as exc:
if exc.errno != errno.ENOENT:
# Using __str__() here to get the fully-formatted error message
# (error number, error message, path)
log.warning('Encountered error removing rtag: %s', exc.__str__())
def write_rtag(opts):
'''
Write the rtag file
'''
rtag_file = rtag(opts)
if not os.path.exists(rtag_file):
try:
with salt.utils.files.fopen(rtag_file, 'w+'):
pass
except OSError as exc:
log.warning('Encountered error writing rtag: %s', exc.__str__())
def check_refresh(opts, refresh=None):
'''
Check whether or not a refresh is necessary
Returns:
- True if refresh evaluates as True
- False if refresh is False
- A boolean if refresh is not False and the rtag file exists
'''
return bool(
salt.utils.data.is_true(refresh) or
(os.path.isfile(rtag(opts)) and refresh is not False)
)
def split_comparison(version):
match = re.match(r'^(<=>|!=|>=|<=|>>|<<|<>|>|<|=)?\s?([^<>=]+)$', version)
if match:
comparison = match.group(1) or ''
version = match.group(2)
else:
comparison = ''
return comparison, version
|
saltstack/salt
|
salt/modules/swift.py
|
_auth
|
python
|
def _auth(profile=None):
'''
Set up openstack credentials
'''
if profile:
credentials = __salt__['config.option'](profile)
user = credentials['keystone.user']
password = credentials.get('keystone.password', None)
tenant = credentials['keystone.tenant']
auth_url = credentials['keystone.auth_url']
auth_version = credentials.get('keystone.auth_version', 2)
region_name = credentials.get('keystone.region_name', None)
api_key = credentials.get('keystone.api_key', None)
os_auth_system = credentials.get('keystone.os_auth_system', None)
else:
user = __salt__['config.option']('keystone.user')
password = __salt__['config.option']('keystone.password', None)
tenant = __salt__['config.option']('keystone.tenant')
auth_url = __salt__['config.option']('keystone.auth_url')
auth_version = __salt__['config.option']('keystone.auth_version', 2)
region_name = __salt__['config.option']('keystone.region_name')
api_key = __salt__['config.option']('keystone.api_key')
os_auth_system = __salt__['config.option']('keystone.os_auth_system')
kwargs = {
'user': user,
'password': password,
'key': api_key,
'tenant_name': tenant,
'auth_url': auth_url,
'auth_version': auth_version,
'region_name': region_name
}
return suos.SaltSwift(**kwargs)
|
Set up openstack credentials
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/swift.py#L71-L104
| null |
# -*- coding: utf-8 -*-
'''
Module for handling OpenStack Swift calls
Author: Anthony Stanton <anthony.stanton@gmail.com>
Inspired by the S3 and Nova modules
:depends: - swiftclient Python module
:configuration: This module is not usable until the user, tenant, auth URL, and password or auth_key
are specified either in a pillar or in the minion's config file.
For example::
keystone.user: admin
keystone.tenant: admin
keystone.auth_url: 'http://127.0.0.1:5000/v2.0/'
keystone.password: verybadpass
# or
keystone.auth_key: 203802934809284k2j34lkj2l3kj43k
If configuration for multiple OpenStack accounts is required, they can be
set up as different configuration profiles:
For example::
openstack1:
keystone.user: admin
keystone.tenant: admin
keystone.auth_url: 'http://127.0.0.1:5000/v2.0/'
keystone.password: verybadpass
# or
keystone.auth_key: 203802934809284k2j34lkj2l3kj43k
openstack2:
keystone.user: admin
keystone.tenant: admin
keystone.auth_url: 'http://127.0.0.2:5000/v2.0/'
keystone.password: verybadpass
# or
keystone.auth_key: 303802934809284k2j34lkj2l3kj43k
With this configuration in place, any of the swift functions can make use of
a configuration profile by declaring it explicitly.
For example::
salt '*' swift.get mycontainer myfile /tmp/file profile=openstack1
NOTE: For Rackspace cloud files setting keystone.auth_version = 1 is recommended.
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import python libs
import logging
# Import salt libs
import salt.utils.openstack.swift as suos
# Get logging started
log = logging.getLogger(__name__)
def __virtual__():
'''
Only load this module if swift
is installed on this minion.
'''
return suos.check_swift()
__opts__ = {}
def delete(cont, path=None, profile=None):
'''
Delete a container, or delete an object from a container.
CLI Example to delete a container::
salt myminion swift.delete mycontainer
CLI Example to delete an object from a container::
salt myminion swift.delete mycontainer remoteobject
'''
swift_conn = _auth(profile)
if path is None:
return swift_conn.delete_container(cont)
else:
return swift_conn.delete_object(cont, path)
def get(cont=None, path=None, local_file=None, return_bin=False, profile=None):
'''
List the contents of a container, or return an object from a container. Set
return_bin to True in order to retrieve an object wholesale. Otherwise,
Salt will attempt to parse an XML response.
CLI Example to list containers:
.. code-block:: bash
salt myminion swift.get
CLI Example to list the contents of a container:
.. code-block:: bash
salt myminion swift.get mycontainer
CLI Example to return the binary contents of an object:
.. code-block:: bash
salt myminion swift.get mycontainer myfile.png return_bin=True
CLI Example to save the binary contents of an object to a local file:
.. code-block:: bash
salt myminion swift.get mycontainer myfile.png local_file=/tmp/myfile.png
'''
swift_conn = _auth(profile)
if cont is None:
return swift_conn.get_account()
if path is None:
return swift_conn.get_container(cont)
if return_bin is True:
return swift_conn.get_object(cont, path, return_bin)
if local_file is not None:
return swift_conn.get_object(cont, path, local_file)
return False
def head():
pass
def put(cont, path=None, local_file=None, profile=None):
'''
Create a new container, or upload an object to a container.
CLI Example to create a container:
.. code-block:: bash
salt myminion swift.put mycontainer
CLI Example to upload an object to a container:
.. code-block:: bash
salt myminion swift.put mycontainer remotepath local_file=/path/to/file
'''
swift_conn = _auth(profile)
if path is None:
return swift_conn.put_container(cont)
elif local_file is not None:
return swift_conn.put_object(cont, path, local_file)
else:
return False
|
saltstack/salt
|
salt/modules/swift.py
|
delete
|
python
|
def delete(cont, path=None, profile=None):
'''
Delete a container, or delete an object from a container.
CLI Example to delete a container::
salt myminion swift.delete mycontainer
CLI Example to delete an object from a container::
salt myminion swift.delete mycontainer remoteobject
'''
swift_conn = _auth(profile)
if path is None:
return swift_conn.delete_container(cont)
else:
return swift_conn.delete_object(cont, path)
|
Delete a container, or delete an object from a container.
CLI Example to delete a container::
salt myminion swift.delete mycontainer
CLI Example to delete an object from a container::
salt myminion swift.delete mycontainer remoteobject
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/swift.py#L107-L124
|
[
"def _auth(profile=None):\n '''\n Set up openstack credentials\n '''\n if profile:\n credentials = __salt__['config.option'](profile)\n user = credentials['keystone.user']\n password = credentials.get('keystone.password', None)\n tenant = credentials['keystone.tenant']\n auth_url = credentials['keystone.auth_url']\n auth_version = credentials.get('keystone.auth_version', 2)\n region_name = credentials.get('keystone.region_name', None)\n api_key = credentials.get('keystone.api_key', None)\n os_auth_system = credentials.get('keystone.os_auth_system', None)\n else:\n user = __salt__['config.option']('keystone.user')\n password = __salt__['config.option']('keystone.password', None)\n tenant = __salt__['config.option']('keystone.tenant')\n auth_url = __salt__['config.option']('keystone.auth_url')\n auth_version = __salt__['config.option']('keystone.auth_version', 2)\n region_name = __salt__['config.option']('keystone.region_name')\n api_key = __salt__['config.option']('keystone.api_key')\n os_auth_system = __salt__['config.option']('keystone.os_auth_system')\n kwargs = {\n 'user': user,\n 'password': password,\n 'key': api_key,\n 'tenant_name': tenant,\n 'auth_url': auth_url,\n 'auth_version': auth_version,\n 'region_name': region_name\n }\n\n return suos.SaltSwift(**kwargs)\n",
"def delete_container(self, cont):\n '''\n Delete a Swift container\n '''\n try:\n self.conn.delete_container(cont)\n return True\n except Exception as exc:\n log.error('There was an error::')\n if hasattr(exc, 'code') and hasattr(exc, 'msg'):\n log.error(' Code: %s: %s', exc.code, exc.msg)\n log.error(' Content: \\n%s', getattr(exc, 'read', lambda: six.text_type(exc))())\n return False\n",
"def delete_object(self, cont, obj):\n '''\n Delete a file from Swift\n '''\n try:\n self.conn.delete_object(cont, obj)\n return True\n except Exception as exc:\n log.error('There was an error::')\n if hasattr(exc, 'code') and hasattr(exc, 'msg'):\n log.error(' Code: %s: %s', exc.code, exc.msg)\n log.error(' Content: \\n%s', getattr(exc, 'read', lambda: six.text_type(exc))())\n return False\n"
] |
# -*- coding: utf-8 -*-
'''
Module for handling OpenStack Swift calls
Author: Anthony Stanton <anthony.stanton@gmail.com>
Inspired by the S3 and Nova modules
:depends: - swiftclient Python module
:configuration: This module is not usable until the user, tenant, auth URL, and password or auth_key
are specified either in a pillar or in the minion's config file.
For example::
keystone.user: admin
keystone.tenant: admin
keystone.auth_url: 'http://127.0.0.1:5000/v2.0/'
keystone.password: verybadpass
# or
keystone.auth_key: 203802934809284k2j34lkj2l3kj43k
If configuration for multiple OpenStack accounts is required, they can be
set up as different configuration profiles:
For example::
openstack1:
keystone.user: admin
keystone.tenant: admin
keystone.auth_url: 'http://127.0.0.1:5000/v2.0/'
keystone.password: verybadpass
# or
keystone.auth_key: 203802934809284k2j34lkj2l3kj43k
openstack2:
keystone.user: admin
keystone.tenant: admin
keystone.auth_url: 'http://127.0.0.2:5000/v2.0/'
keystone.password: verybadpass
# or
keystone.auth_key: 303802934809284k2j34lkj2l3kj43k
With this configuration in place, any of the swift functions can make use of
a configuration profile by declaring it explicitly.
For example::
salt '*' swift.get mycontainer myfile /tmp/file profile=openstack1
NOTE: For Rackspace cloud files setting keystone.auth_version = 1 is recommended.
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import python libs
import logging
# Import salt libs
import salt.utils.openstack.swift as suos
# Get logging started
log = logging.getLogger(__name__)
def __virtual__():
'''
Only load this module if swift
is installed on this minion.
'''
return suos.check_swift()
__opts__ = {}
def _auth(profile=None):
'''
Set up openstack credentials
'''
if profile:
credentials = __salt__['config.option'](profile)
user = credentials['keystone.user']
password = credentials.get('keystone.password', None)
tenant = credentials['keystone.tenant']
auth_url = credentials['keystone.auth_url']
auth_version = credentials.get('keystone.auth_version', 2)
region_name = credentials.get('keystone.region_name', None)
api_key = credentials.get('keystone.api_key', None)
os_auth_system = credentials.get('keystone.os_auth_system', None)
else:
user = __salt__['config.option']('keystone.user')
password = __salt__['config.option']('keystone.password', None)
tenant = __salt__['config.option']('keystone.tenant')
auth_url = __salt__['config.option']('keystone.auth_url')
auth_version = __salt__['config.option']('keystone.auth_version', 2)
region_name = __salt__['config.option']('keystone.region_name')
api_key = __salt__['config.option']('keystone.api_key')
os_auth_system = __salt__['config.option']('keystone.os_auth_system')
kwargs = {
'user': user,
'password': password,
'key': api_key,
'tenant_name': tenant,
'auth_url': auth_url,
'auth_version': auth_version,
'region_name': region_name
}
return suos.SaltSwift(**kwargs)
def get(cont=None, path=None, local_file=None, return_bin=False, profile=None):
'''
List the contents of a container, or return an object from a container. Set
return_bin to True in order to retrieve an object wholesale. Otherwise,
Salt will attempt to parse an XML response.
CLI Example to list containers:
.. code-block:: bash
salt myminion swift.get
CLI Example to list the contents of a container:
.. code-block:: bash
salt myminion swift.get mycontainer
CLI Example to return the binary contents of an object:
.. code-block:: bash
salt myminion swift.get mycontainer myfile.png return_bin=True
CLI Example to save the binary contents of an object to a local file:
.. code-block:: bash
salt myminion swift.get mycontainer myfile.png local_file=/tmp/myfile.png
'''
swift_conn = _auth(profile)
if cont is None:
return swift_conn.get_account()
if path is None:
return swift_conn.get_container(cont)
if return_bin is True:
return swift_conn.get_object(cont, path, return_bin)
if local_file is not None:
return swift_conn.get_object(cont, path, local_file)
return False
def head():
pass
def put(cont, path=None, local_file=None, profile=None):
'''
Create a new container, or upload an object to a container.
CLI Example to create a container:
.. code-block:: bash
salt myminion swift.put mycontainer
CLI Example to upload an object to a container:
.. code-block:: bash
salt myminion swift.put mycontainer remotepath local_file=/path/to/file
'''
swift_conn = _auth(profile)
if path is None:
return swift_conn.put_container(cont)
elif local_file is not None:
return swift_conn.put_object(cont, path, local_file)
else:
return False
|
saltstack/salt
|
salt/modules/swift.py
|
get
|
python
|
def get(cont=None, path=None, local_file=None, return_bin=False, profile=None):
'''
List the contents of a container, or return an object from a container. Set
return_bin to True in order to retrieve an object wholesale. Otherwise,
Salt will attempt to parse an XML response.
CLI Example to list containers:
.. code-block:: bash
salt myminion swift.get
CLI Example to list the contents of a container:
.. code-block:: bash
salt myminion swift.get mycontainer
CLI Example to return the binary contents of an object:
.. code-block:: bash
salt myminion swift.get mycontainer myfile.png return_bin=True
CLI Example to save the binary contents of an object to a local file:
.. code-block:: bash
salt myminion swift.get mycontainer myfile.png local_file=/tmp/myfile.png
'''
swift_conn = _auth(profile)
if cont is None:
return swift_conn.get_account()
if path is None:
return swift_conn.get_container(cont)
if return_bin is True:
return swift_conn.get_object(cont, path, return_bin)
if local_file is not None:
return swift_conn.get_object(cont, path, local_file)
return False
|
List the contents of a container, or return an object from a container. Set
return_bin to True in order to retrieve an object wholesale. Otherwise,
Salt will attempt to parse an XML response.
CLI Example to list containers:
.. code-block:: bash
salt myminion swift.get
CLI Example to list the contents of a container:
.. code-block:: bash
salt myminion swift.get mycontainer
CLI Example to return the binary contents of an object:
.. code-block:: bash
salt myminion swift.get mycontainer myfile.png return_bin=True
CLI Example to save the binary contents of an object to a local file:
.. code-block:: bash
salt myminion swift.get mycontainer myfile.png local_file=/tmp/myfile.png
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/swift.py#L127-L172
|
[
"def _auth(profile=None):\n '''\n Set up openstack credentials\n '''\n if profile:\n credentials = __salt__['config.option'](profile)\n user = credentials['keystone.user']\n password = credentials.get('keystone.password', None)\n tenant = credentials['keystone.tenant']\n auth_url = credentials['keystone.auth_url']\n auth_version = credentials.get('keystone.auth_version', 2)\n region_name = credentials.get('keystone.region_name', None)\n api_key = credentials.get('keystone.api_key', None)\n os_auth_system = credentials.get('keystone.os_auth_system', None)\n else:\n user = __salt__['config.option']('keystone.user')\n password = __salt__['config.option']('keystone.password', None)\n tenant = __salt__['config.option']('keystone.tenant')\n auth_url = __salt__['config.option']('keystone.auth_url')\n auth_version = __salt__['config.option']('keystone.auth_version', 2)\n region_name = __salt__['config.option']('keystone.region_name')\n api_key = __salt__['config.option']('keystone.api_key')\n os_auth_system = __salt__['config.option']('keystone.os_auth_system')\n kwargs = {\n 'user': user,\n 'password': password,\n 'key': api_key,\n 'tenant_name': tenant,\n 'auth_url': auth_url,\n 'auth_version': auth_version,\n 'region_name': region_name\n }\n\n return suos.SaltSwift(**kwargs)\n"
] |
# -*- coding: utf-8 -*-
'''
Module for handling OpenStack Swift calls
Author: Anthony Stanton <anthony.stanton@gmail.com>
Inspired by the S3 and Nova modules
:depends: - swiftclient Python module
:configuration: This module is not usable until the user, tenant, auth URL, and password or auth_key
are specified either in a pillar or in the minion's config file.
For example::
keystone.user: admin
keystone.tenant: admin
keystone.auth_url: 'http://127.0.0.1:5000/v2.0/'
keystone.password: verybadpass
# or
keystone.auth_key: 203802934809284k2j34lkj2l3kj43k
If configuration for multiple OpenStack accounts is required, they can be
set up as different configuration profiles:
For example::
openstack1:
keystone.user: admin
keystone.tenant: admin
keystone.auth_url: 'http://127.0.0.1:5000/v2.0/'
keystone.password: verybadpass
# or
keystone.auth_key: 203802934809284k2j34lkj2l3kj43k
openstack2:
keystone.user: admin
keystone.tenant: admin
keystone.auth_url: 'http://127.0.0.2:5000/v2.0/'
keystone.password: verybadpass
# or
keystone.auth_key: 303802934809284k2j34lkj2l3kj43k
With this configuration in place, any of the swift functions can make use of
a configuration profile by declaring it explicitly.
For example::
salt '*' swift.get mycontainer myfile /tmp/file profile=openstack1
NOTE: For Rackspace cloud files setting keystone.auth_version = 1 is recommended.
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import python libs
import logging
# Import salt libs
import salt.utils.openstack.swift as suos
# Get logging started
log = logging.getLogger(__name__)
def __virtual__():
'''
Only load this module if swift
is installed on this minion.
'''
return suos.check_swift()
__opts__ = {}
def _auth(profile=None):
'''
Set up openstack credentials
'''
if profile:
credentials = __salt__['config.option'](profile)
user = credentials['keystone.user']
password = credentials.get('keystone.password', None)
tenant = credentials['keystone.tenant']
auth_url = credentials['keystone.auth_url']
auth_version = credentials.get('keystone.auth_version', 2)
region_name = credentials.get('keystone.region_name', None)
api_key = credentials.get('keystone.api_key', None)
os_auth_system = credentials.get('keystone.os_auth_system', None)
else:
user = __salt__['config.option']('keystone.user')
password = __salt__['config.option']('keystone.password', None)
tenant = __salt__['config.option']('keystone.tenant')
auth_url = __salt__['config.option']('keystone.auth_url')
auth_version = __salt__['config.option']('keystone.auth_version', 2)
region_name = __salt__['config.option']('keystone.region_name')
api_key = __salt__['config.option']('keystone.api_key')
os_auth_system = __salt__['config.option']('keystone.os_auth_system')
kwargs = {
'user': user,
'password': password,
'key': api_key,
'tenant_name': tenant,
'auth_url': auth_url,
'auth_version': auth_version,
'region_name': region_name
}
return suos.SaltSwift(**kwargs)
def delete(cont, path=None, profile=None):
'''
Delete a container, or delete an object from a container.
CLI Example to delete a container::
salt myminion swift.delete mycontainer
CLI Example to delete an object from a container::
salt myminion swift.delete mycontainer remoteobject
'''
swift_conn = _auth(profile)
if path is None:
return swift_conn.delete_container(cont)
else:
return swift_conn.delete_object(cont, path)
def head():
pass
def put(cont, path=None, local_file=None, profile=None):
'''
Create a new container, or upload an object to a container.
CLI Example to create a container:
.. code-block:: bash
salt myminion swift.put mycontainer
CLI Example to upload an object to a container:
.. code-block:: bash
salt myminion swift.put mycontainer remotepath local_file=/path/to/file
'''
swift_conn = _auth(profile)
if path is None:
return swift_conn.put_container(cont)
elif local_file is not None:
return swift_conn.put_object(cont, path, local_file)
else:
return False
|
saltstack/salt
|
salt/modules/swift.py
|
put
|
python
|
def put(cont, path=None, local_file=None, profile=None):
'''
Create a new container, or upload an object to a container.
CLI Example to create a container:
.. code-block:: bash
salt myminion swift.put mycontainer
CLI Example to upload an object to a container:
.. code-block:: bash
salt myminion swift.put mycontainer remotepath local_file=/path/to/file
'''
swift_conn = _auth(profile)
if path is None:
return swift_conn.put_container(cont)
elif local_file is not None:
return swift_conn.put_object(cont, path, local_file)
else:
return False
|
Create a new container, or upload an object to a container.
CLI Example to create a container:
.. code-block:: bash
salt myminion swift.put mycontainer
CLI Example to upload an object to a container:
.. code-block:: bash
salt myminion swift.put mycontainer remotepath local_file=/path/to/file
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/swift.py#L179-L202
|
[
"def _auth(profile=None):\n '''\n Set up openstack credentials\n '''\n if profile:\n credentials = __salt__['config.option'](profile)\n user = credentials['keystone.user']\n password = credentials.get('keystone.password', None)\n tenant = credentials['keystone.tenant']\n auth_url = credentials['keystone.auth_url']\n auth_version = credentials.get('keystone.auth_version', 2)\n region_name = credentials.get('keystone.region_name', None)\n api_key = credentials.get('keystone.api_key', None)\n os_auth_system = credentials.get('keystone.os_auth_system', None)\n else:\n user = __salt__['config.option']('keystone.user')\n password = __salt__['config.option']('keystone.password', None)\n tenant = __salt__['config.option']('keystone.tenant')\n auth_url = __salt__['config.option']('keystone.auth_url')\n auth_version = __salt__['config.option']('keystone.auth_version', 2)\n region_name = __salt__['config.option']('keystone.region_name')\n api_key = __salt__['config.option']('keystone.api_key')\n os_auth_system = __salt__['config.option']('keystone.os_auth_system')\n kwargs = {\n 'user': user,\n 'password': password,\n 'key': api_key,\n 'tenant_name': tenant,\n 'auth_url': auth_url,\n 'auth_version': auth_version,\n 'region_name': region_name\n }\n\n return suos.SaltSwift(**kwargs)\n",
"def put_container(self, cont):\n '''\n Create a new Swift container\n '''\n try:\n self.conn.put_container(cont)\n return True\n except Exception as exc:\n log.error('There was an error::')\n if hasattr(exc, 'code') and hasattr(exc, 'msg'):\n log.error(' Code: %s: %s', exc.code, exc.msg)\n log.error(' Content: \\n%s', getattr(exc, 'read', lambda: six.text_type(exc))())\n return False\n",
"def put_object(self, cont, obj, local_file):\n '''\n Upload a file to Swift\n '''\n try:\n with salt.utils.files.fopen(local_file, 'rb') as fp_:\n self.conn.put_object(cont, obj, fp_)\n return True\n except Exception as exc:\n log.error('There was an error::')\n if hasattr(exc, 'code') and hasattr(exc, 'msg'):\n log.error(' Code: %s: %s', exc.code, exc.msg)\n log.error(' Content: \\n%s', getattr(exc, 'read', lambda: six.text_type(exc))())\n return False\n"
] |
# -*- coding: utf-8 -*-
'''
Module for handling OpenStack Swift calls
Author: Anthony Stanton <anthony.stanton@gmail.com>
Inspired by the S3 and Nova modules
:depends: - swiftclient Python module
:configuration: This module is not usable until the user, tenant, auth URL, and password or auth_key
are specified either in a pillar or in the minion's config file.
For example::
keystone.user: admin
keystone.tenant: admin
keystone.auth_url: 'http://127.0.0.1:5000/v2.0/'
keystone.password: verybadpass
# or
keystone.auth_key: 203802934809284k2j34lkj2l3kj43k
If configuration for multiple OpenStack accounts is required, they can be
set up as different configuration profiles:
For example::
openstack1:
keystone.user: admin
keystone.tenant: admin
keystone.auth_url: 'http://127.0.0.1:5000/v2.0/'
keystone.password: verybadpass
# or
keystone.auth_key: 203802934809284k2j34lkj2l3kj43k
openstack2:
keystone.user: admin
keystone.tenant: admin
keystone.auth_url: 'http://127.0.0.2:5000/v2.0/'
keystone.password: verybadpass
# or
keystone.auth_key: 303802934809284k2j34lkj2l3kj43k
With this configuration in place, any of the swift functions can make use of
a configuration profile by declaring it explicitly.
For example::
salt '*' swift.get mycontainer myfile /tmp/file profile=openstack1
NOTE: For Rackspace cloud files setting keystone.auth_version = 1 is recommended.
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import python libs
import logging
# Import salt libs
import salt.utils.openstack.swift as suos
# Get logging started
log = logging.getLogger(__name__)
def __virtual__():
'''
Only load this module if swift
is installed on this minion.
'''
return suos.check_swift()
__opts__ = {}
def _auth(profile=None):
'''
Set up openstack credentials
'''
if profile:
credentials = __salt__['config.option'](profile)
user = credentials['keystone.user']
password = credentials.get('keystone.password', None)
tenant = credentials['keystone.tenant']
auth_url = credentials['keystone.auth_url']
auth_version = credentials.get('keystone.auth_version', 2)
region_name = credentials.get('keystone.region_name', None)
api_key = credentials.get('keystone.api_key', None)
os_auth_system = credentials.get('keystone.os_auth_system', None)
else:
user = __salt__['config.option']('keystone.user')
password = __salt__['config.option']('keystone.password', None)
tenant = __salt__['config.option']('keystone.tenant')
auth_url = __salt__['config.option']('keystone.auth_url')
auth_version = __salt__['config.option']('keystone.auth_version', 2)
region_name = __salt__['config.option']('keystone.region_name')
api_key = __salt__['config.option']('keystone.api_key')
os_auth_system = __salt__['config.option']('keystone.os_auth_system')
kwargs = {
'user': user,
'password': password,
'key': api_key,
'tenant_name': tenant,
'auth_url': auth_url,
'auth_version': auth_version,
'region_name': region_name
}
return suos.SaltSwift(**kwargs)
def delete(cont, path=None, profile=None):
'''
Delete a container, or delete an object from a container.
CLI Example to delete a container::
salt myminion swift.delete mycontainer
CLI Example to delete an object from a container::
salt myminion swift.delete mycontainer remoteobject
'''
swift_conn = _auth(profile)
if path is None:
return swift_conn.delete_container(cont)
else:
return swift_conn.delete_object(cont, path)
def get(cont=None, path=None, local_file=None, return_bin=False, profile=None):
'''
List the contents of a container, or return an object from a container. Set
return_bin to True in order to retrieve an object wholesale. Otherwise,
Salt will attempt to parse an XML response.
CLI Example to list containers:
.. code-block:: bash
salt myminion swift.get
CLI Example to list the contents of a container:
.. code-block:: bash
salt myminion swift.get mycontainer
CLI Example to return the binary contents of an object:
.. code-block:: bash
salt myminion swift.get mycontainer myfile.png return_bin=True
CLI Example to save the binary contents of an object to a local file:
.. code-block:: bash
salt myminion swift.get mycontainer myfile.png local_file=/tmp/myfile.png
'''
swift_conn = _auth(profile)
if cont is None:
return swift_conn.get_account()
if path is None:
return swift_conn.get_container(cont)
if return_bin is True:
return swift_conn.get_object(cont, path, return_bin)
if local_file is not None:
return swift_conn.get_object(cont, path, local_file)
return False
def head():
pass
|
saltstack/salt
|
salt/modules/mac_shadow.py
|
_get_account_policy
|
python
|
def _get_account_policy(name):
'''
Get the entire accountPolicy and return it as a dictionary. For use by this
module only
:param str name: The user name
:return: a dictionary containing all values for the accountPolicy
:rtype: dict
:raises: CommandExecutionError on user not found or any other unknown error
'''
cmd = 'pwpolicy -u {0} -getpolicy'.format(name)
try:
ret = salt.utils.mac_utils.execute_return_result(cmd)
except CommandExecutionError as exc:
if 'Error: user <{0}> not found'.format(name) in exc.strerror:
raise CommandExecutionError('User not found: {0}'.format(name))
raise CommandExecutionError('Unknown error: {0}'.format(exc.strerror))
try:
policy_list = ret.split('\n')[1].split(' ')
policy_dict = {}
for policy in policy_list:
if '=' in policy:
key, value = policy.split('=')
policy_dict[key] = value
return policy_dict
except IndexError:
return {}
|
Get the entire accountPolicy and return it as a dictionary. For use by this
module only
:param str name: The user name
:return: a dictionary containing all values for the accountPolicy
:rtype: dict
:raises: CommandExecutionError on user not found or any other unknown error
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_shadow.py#L45-L75
|
[
"def execute_return_result(cmd):\n '''\n Executes the passed command. Returns the standard out if successful\n\n :param str cmd: The command to run\n\n :return: The standard out of the command if successful, otherwise returns\n an error\n :rtype: str\n\n :raises: Error if command fails or is not supported\n '''\n ret = _run_all(cmd)\n\n if ret['retcode'] != 0 or 'not supported' in ret['stdout'].lower():\n msg = 'Command Failed: {0}\\n'.format(cmd)\n msg += 'Return Code: {0}\\n'.format(ret['retcode'])\n msg += 'Output: {0}\\n'.format(ret['stdout'])\n msg += 'Error: {0}\\n'.format(ret['stderr'])\n raise CommandExecutionError(msg)\n\n return ret['stdout']\n"
] |
# -*- coding: utf-8 -*-
'''
Manage macOS local directory passwords and policies
.. versionadded:: 2016.3.0
Note that it is usually better to apply password policies through the creation
of a configuration profile.
'''
# Authentication concepts reference:
# https://developer.apple.com/library/mac/documentation/Networking/Conceptual/Open_Directory/openDirectoryConcepts/openDirectoryConcepts.html#//apple_ref/doc/uid/TP40000917-CH3-CIFCAIBB
from __future__ import absolute_import, unicode_literals, print_function
from datetime import datetime
try:
import pwd
HAS_PWD = True
except ImportError:
HAS_PWD = False
# Import salt libs
import logging
import salt.utils.mac_utils
import salt.utils.platform
from salt.exceptions import CommandExecutionError
log = logging.getLogger(__name__) # Start logging
__virtualname__ = 'shadow'
def __virtual__():
# Is this macOS?
if not salt.utils.platform.is_darwin():
return False, 'Not macOS'
if HAS_PWD:
return __virtualname__
else:
return (False, 'The pwd module failed to load.')
def _set_account_policy(name, policy):
'''
Set a value in the user accountPolicy. For use by this module only
:param str name: The user name
:param str policy: The policy to apply
:return: True if success, otherwise False
:rtype: bool
:raises: CommandExecutionError on user not found or any other unknown error
'''
cmd = 'pwpolicy -u {0} -setpolicy "{1}"'.format(name, policy)
try:
return salt.utils.mac_utils.execute_return_success(cmd)
except CommandExecutionError as exc:
if 'Error: user <{0}> not found'.format(name) in exc.strerror:
raise CommandExecutionError('User not found: {0}'.format(name))
raise CommandExecutionError('Unknown error: {0}'.format(exc.strerror))
def _get_account_policy_data_value(name, key):
'''
Return the value for a key in the accountPolicy section of the user's plist
file. For use by this module only
:param str name: The username
:param str key: The accountPolicy key
:return: The value contained within the key
:rtype: str
:raises: CommandExecutionError on user not found or any other unknown error
'''
cmd = 'dscl . -readpl /Users/{0} accountPolicyData {1}'.format(name, key)
try:
ret = salt.utils.mac_utils.execute_return_result(cmd)
except CommandExecutionError as exc:
if 'eDSUnknownNodeName' in exc.strerror:
raise CommandExecutionError('User not found: {0}'.format(name))
raise CommandExecutionError('Unknown error: {0}'.format(exc.strerror))
return ret
def _convert_to_datetime(unix_timestamp):
'''
Converts a unix timestamp to a human readable date/time
:param float unix_timestamp: A unix timestamp
:return: A date/time in the format YYYY-mm-dd HH:MM:SS
:rtype: str
'''
try:
unix_timestamp = float(unix_timestamp)
return datetime.fromtimestamp(unix_timestamp).strftime('%Y-%m-%d %H:%M:%S')
except (ValueError, TypeError):
return 'Invalid Timestamp'
def info(name):
'''
Return information for the specified user
:param str name: The username
:return: A dictionary containing the user's shadow information
:rtype: dict
CLI Example:
.. code-block:: bash
salt '*' shadow.info admin
'''
try:
data = pwd.getpwnam(name)
return {'name': data.pw_name,
'passwd': data.pw_passwd,
'account_created': get_account_created(name),
'login_failed_count': get_login_failed_count(name),
'login_failed_last': get_login_failed_last(name),
'lstchg': get_last_change(name),
'max': get_maxdays(name),
'expire': get_expire(name),
'change': get_change(name),
'min': 'Unavailable',
'warn': 'Unavailable',
'inact': 'Unavailable'}
except KeyError:
log.debug('User not found: %s', name)
return {'name': '',
'passwd': '',
'account_created': '',
'login_failed_count': '',
'login_failed_last': '',
'lstchg': '',
'max': '',
'expire': '',
'change': '',
'min': '',
'warn': '',
'inact': ''}
def get_account_created(name):
'''
Get the date/time the account was created
:param str name: The username of the account
:return: The date/time the account was created (yyyy-mm-dd hh:mm:ss)
:rtype: str
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.get_account_created admin
'''
ret = _get_account_policy_data_value(name, 'creationTime')
unix_timestamp = salt.utils.mac_utils.parse_return(ret)
date_text = _convert_to_datetime(unix_timestamp)
return date_text
def get_last_change(name):
'''
Get the date/time the account was changed
:param str name: The username of the account
:return: The date/time the account was modified (yyyy-mm-dd hh:mm:ss)
:rtype: str
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.get_last_change admin
'''
ret = _get_account_policy_data_value(name, 'passwordLastSetTime')
unix_timestamp = salt.utils.mac_utils.parse_return(ret)
date_text = _convert_to_datetime(unix_timestamp)
return date_text
def get_login_failed_count(name):
'''
Get the the number of failed login attempts
:param str name: The username of the account
:return: The number of failed login attempts
:rtype: int
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.get_login_failed_count admin
'''
ret = _get_account_policy_data_value(name, 'failedLoginCount')
return salt.utils.mac_utils.parse_return(ret)
def get_login_failed_last(name):
'''
Get the date/time of the last failed login attempt
:param str name: The username of the account
:return: The date/time of the last failed login attempt on this account
(yyyy-mm-dd hh:mm:ss)
:rtype: str
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.get_login_failed_last admin
'''
ret = _get_account_policy_data_value(name, 'failedLoginTimestamp')
unix_timestamp = salt.utils.mac_utils.parse_return(ret)
date_text = _convert_to_datetime(unix_timestamp)
return date_text
def set_maxdays(name, days):
'''
Set the maximum age of the password in days
:param str name: The username of the account
:param int days: The maximum age of the account in days
:return: True if successful, False if not
:rtype: bool
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.set_maxdays admin 90
'''
minutes = days * 24 * 60
_set_account_policy(
name, 'maxMinutesUntilChangePassword={0}'.format(minutes))
return get_maxdays(name) == days
def get_maxdays(name):
'''
Get the maximum age of the password
:param str name: The username of the account
:return: The maximum age of the password in days
:rtype: int
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.get_maxdays admin 90
'''
policies = _get_account_policy(name)
if 'maxMinutesUntilChangePassword' in policies:
max_minutes = policies['maxMinutesUntilChangePassword']
return int(max_minutes) / 24 / 60
return 0
def set_mindays(name, days):
'''
Set the minimum password age in days. Not available in macOS.
:param str name: The user name
:param int days: The number of days
:return: Will always return False until macOS supports this feature.
:rtype: bool
CLI Example:
.. code-block:: bash
salt '*' shadow.set_mindays admin 90
'''
return False
def set_inactdays(name, days):
'''
Set the number if inactive days before the account is locked. Not available
in macOS
:param str name: The user name
:param int days: The number of days
:return: Will always return False until macOS supports this feature.
:rtype: bool
CLI Example:
.. code-block:: bash
salt '*' shadow.set_inactdays admin 90
'''
return False
def set_warndays(name, days):
'''
Set the number of days before the password expires that the user will start
to see a warning. Not available in macOS
:param str name: The user name
:param int days: The number of days
:return: Will always return False until macOS supports this feature.
:rtype: bool
CLI Example:
.. code-block:: bash
salt '*' shadow.set_warndays admin 90
'''
return False
def set_change(name, date):
'''
Sets the date on which the password expires. The user will be required to
change their password. Format is mm/dd/yyyy
:param str name: The name of the user account
:param date date: The date the password will expire. Must be in mm/dd/yyyy
format.
:return: True if successful, otherwise False
:rtype: bool
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.set_change username 09/21/2016
'''
_set_account_policy(
name, 'usingExpirationDate=1 expirationDateGMT={0}'.format(date))
return get_change(name) == date
def get_change(name):
'''
Gets the date on which the password expires
:param str name: The name of the user account
:return: The date the password will expire
:rtype: str
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.get_change username
'''
policies = _get_account_policy(name)
if 'expirationDateGMT' in policies:
return policies['expirationDateGMT']
return 'Value not set'
def set_expire(name, date):
'''
Sets the date on which the account expires. The user will not be able to
login after this date. Date format is mm/dd/yyyy
:param str name: The name of the user account
:param datetime date: The date the account will expire. Format must be
mm/dd/yyyy.
:return: True if successful, False if not
:rtype: bool
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.set_expire username 07/23/2015
'''
_set_account_policy(
name, 'usingHardExpirationDate=1 hardExpireDateGMT={0}'.format(date))
return get_expire(name) == date
def get_expire(name):
'''
Gets the date on which the account expires
:param str name: The name of the user account
:return: The date the account expires
:rtype: str
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.get_expire username
'''
policies = _get_account_policy(name)
if 'hardExpireDateGMT' in policies:
return policies['hardExpireDateGMT']
return 'Value not set'
def del_password(name):
'''
Deletes the account password
:param str name: The user name of the account
:return: True if successful, otherwise False
:rtype: bool
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.del_password username
'''
# This removes the password
cmd = "dscl . -passwd /Users/{0} ''".format(name)
try:
salt.utils.mac_utils.execute_return_success(cmd)
except CommandExecutionError as exc:
if 'eDSUnknownNodeName' in exc.strerror:
raise CommandExecutionError('User not found: {0}'.format(name))
raise CommandExecutionError('Unknown error: {0}'.format(exc.strerror))
# This is so it looks right in shadow.info
cmd = "dscl . -create /Users/{0} Password '*'".format(name)
salt.utils.mac_utils.execute_return_success(cmd)
return info(name)['passwd'] == '*'
def set_password(name, password):
'''
Set the password for a named user (insecure, the password will be in the
process list while the command is running)
:param str name: The name of the local user, which is assumed to be in the
local directory service
:param str password: The plaintext password to set
:return: True if successful, otherwise False
:rtype: bool
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' mac_shadow.set_password macuser macpassword
'''
cmd = "dscl . -passwd /Users/{0} '{1}'".format(name, password)
try:
salt.utils.mac_utils.execute_return_success(cmd)
except CommandExecutionError as exc:
if 'eDSUnknownNodeName' in exc.strerror:
raise CommandExecutionError('User not found: {0}'.format(name))
raise CommandExecutionError('Unknown error: {0}'.format(exc.strerror))
return True
|
saltstack/salt
|
salt/modules/mac_shadow.py
|
_set_account_policy
|
python
|
def _set_account_policy(name, policy):
'''
Set a value in the user accountPolicy. For use by this module only
:param str name: The user name
:param str policy: The policy to apply
:return: True if success, otherwise False
:rtype: bool
:raises: CommandExecutionError on user not found or any other unknown error
'''
cmd = 'pwpolicy -u {0} -setpolicy "{1}"'.format(name, policy)
try:
return salt.utils.mac_utils.execute_return_success(cmd)
except CommandExecutionError as exc:
if 'Error: user <{0}> not found'.format(name) in exc.strerror:
raise CommandExecutionError('User not found: {0}'.format(name))
raise CommandExecutionError('Unknown error: {0}'.format(exc.strerror))
|
Set a value in the user accountPolicy. For use by this module only
:param str name: The user name
:param str policy: The policy to apply
:return: True if success, otherwise False
:rtype: bool
:raises: CommandExecutionError on user not found or any other unknown error
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_shadow.py#L78-L97
|
[
"def execute_return_success(cmd):\n '''\n Executes the passed command. Returns True if successful\n\n :param str cmd: The command to run\n\n :return: True if successful, otherwise False\n :rtype: bool\n\n :raises: Error if command fails or is not supported\n '''\n\n ret = _run_all(cmd)\n\n if ret['retcode'] != 0 or 'not supported' in ret['stdout'].lower():\n msg = 'Command Failed: {0}\\n'.format(cmd)\n msg += 'Return Code: {0}\\n'.format(ret['retcode'])\n msg += 'Output: {0}\\n'.format(ret['stdout'])\n msg += 'Error: {0}\\n'.format(ret['stderr'])\n raise CommandExecutionError(msg)\n\n return True\n"
] |
# -*- coding: utf-8 -*-
'''
Manage macOS local directory passwords and policies
.. versionadded:: 2016.3.0
Note that it is usually better to apply password policies through the creation
of a configuration profile.
'''
# Authentication concepts reference:
# https://developer.apple.com/library/mac/documentation/Networking/Conceptual/Open_Directory/openDirectoryConcepts/openDirectoryConcepts.html#//apple_ref/doc/uid/TP40000917-CH3-CIFCAIBB
from __future__ import absolute_import, unicode_literals, print_function
from datetime import datetime
try:
import pwd
HAS_PWD = True
except ImportError:
HAS_PWD = False
# Import salt libs
import logging
import salt.utils.mac_utils
import salt.utils.platform
from salt.exceptions import CommandExecutionError
log = logging.getLogger(__name__) # Start logging
__virtualname__ = 'shadow'
def __virtual__():
# Is this macOS?
if not salt.utils.platform.is_darwin():
return False, 'Not macOS'
if HAS_PWD:
return __virtualname__
else:
return (False, 'The pwd module failed to load.')
def _get_account_policy(name):
'''
Get the entire accountPolicy and return it as a dictionary. For use by this
module only
:param str name: The user name
:return: a dictionary containing all values for the accountPolicy
:rtype: dict
:raises: CommandExecutionError on user not found or any other unknown error
'''
cmd = 'pwpolicy -u {0} -getpolicy'.format(name)
try:
ret = salt.utils.mac_utils.execute_return_result(cmd)
except CommandExecutionError as exc:
if 'Error: user <{0}> not found'.format(name) in exc.strerror:
raise CommandExecutionError('User not found: {0}'.format(name))
raise CommandExecutionError('Unknown error: {0}'.format(exc.strerror))
try:
policy_list = ret.split('\n')[1].split(' ')
policy_dict = {}
for policy in policy_list:
if '=' in policy:
key, value = policy.split('=')
policy_dict[key] = value
return policy_dict
except IndexError:
return {}
def _get_account_policy_data_value(name, key):
'''
Return the value for a key in the accountPolicy section of the user's plist
file. For use by this module only
:param str name: The username
:param str key: The accountPolicy key
:return: The value contained within the key
:rtype: str
:raises: CommandExecutionError on user not found or any other unknown error
'''
cmd = 'dscl . -readpl /Users/{0} accountPolicyData {1}'.format(name, key)
try:
ret = salt.utils.mac_utils.execute_return_result(cmd)
except CommandExecutionError as exc:
if 'eDSUnknownNodeName' in exc.strerror:
raise CommandExecutionError('User not found: {0}'.format(name))
raise CommandExecutionError('Unknown error: {0}'.format(exc.strerror))
return ret
def _convert_to_datetime(unix_timestamp):
'''
Converts a unix timestamp to a human readable date/time
:param float unix_timestamp: A unix timestamp
:return: A date/time in the format YYYY-mm-dd HH:MM:SS
:rtype: str
'''
try:
unix_timestamp = float(unix_timestamp)
return datetime.fromtimestamp(unix_timestamp).strftime('%Y-%m-%d %H:%M:%S')
except (ValueError, TypeError):
return 'Invalid Timestamp'
def info(name):
'''
Return information for the specified user
:param str name: The username
:return: A dictionary containing the user's shadow information
:rtype: dict
CLI Example:
.. code-block:: bash
salt '*' shadow.info admin
'''
try:
data = pwd.getpwnam(name)
return {'name': data.pw_name,
'passwd': data.pw_passwd,
'account_created': get_account_created(name),
'login_failed_count': get_login_failed_count(name),
'login_failed_last': get_login_failed_last(name),
'lstchg': get_last_change(name),
'max': get_maxdays(name),
'expire': get_expire(name),
'change': get_change(name),
'min': 'Unavailable',
'warn': 'Unavailable',
'inact': 'Unavailable'}
except KeyError:
log.debug('User not found: %s', name)
return {'name': '',
'passwd': '',
'account_created': '',
'login_failed_count': '',
'login_failed_last': '',
'lstchg': '',
'max': '',
'expire': '',
'change': '',
'min': '',
'warn': '',
'inact': ''}
def get_account_created(name):
'''
Get the date/time the account was created
:param str name: The username of the account
:return: The date/time the account was created (yyyy-mm-dd hh:mm:ss)
:rtype: str
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.get_account_created admin
'''
ret = _get_account_policy_data_value(name, 'creationTime')
unix_timestamp = salt.utils.mac_utils.parse_return(ret)
date_text = _convert_to_datetime(unix_timestamp)
return date_text
def get_last_change(name):
'''
Get the date/time the account was changed
:param str name: The username of the account
:return: The date/time the account was modified (yyyy-mm-dd hh:mm:ss)
:rtype: str
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.get_last_change admin
'''
ret = _get_account_policy_data_value(name, 'passwordLastSetTime')
unix_timestamp = salt.utils.mac_utils.parse_return(ret)
date_text = _convert_to_datetime(unix_timestamp)
return date_text
def get_login_failed_count(name):
'''
Get the the number of failed login attempts
:param str name: The username of the account
:return: The number of failed login attempts
:rtype: int
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.get_login_failed_count admin
'''
ret = _get_account_policy_data_value(name, 'failedLoginCount')
return salt.utils.mac_utils.parse_return(ret)
def get_login_failed_last(name):
'''
Get the date/time of the last failed login attempt
:param str name: The username of the account
:return: The date/time of the last failed login attempt on this account
(yyyy-mm-dd hh:mm:ss)
:rtype: str
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.get_login_failed_last admin
'''
ret = _get_account_policy_data_value(name, 'failedLoginTimestamp')
unix_timestamp = salt.utils.mac_utils.parse_return(ret)
date_text = _convert_to_datetime(unix_timestamp)
return date_text
def set_maxdays(name, days):
'''
Set the maximum age of the password in days
:param str name: The username of the account
:param int days: The maximum age of the account in days
:return: True if successful, False if not
:rtype: bool
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.set_maxdays admin 90
'''
minutes = days * 24 * 60
_set_account_policy(
name, 'maxMinutesUntilChangePassword={0}'.format(minutes))
return get_maxdays(name) == days
def get_maxdays(name):
'''
Get the maximum age of the password
:param str name: The username of the account
:return: The maximum age of the password in days
:rtype: int
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.get_maxdays admin 90
'''
policies = _get_account_policy(name)
if 'maxMinutesUntilChangePassword' in policies:
max_minutes = policies['maxMinutesUntilChangePassword']
return int(max_minutes) / 24 / 60
return 0
def set_mindays(name, days):
'''
Set the minimum password age in days. Not available in macOS.
:param str name: The user name
:param int days: The number of days
:return: Will always return False until macOS supports this feature.
:rtype: bool
CLI Example:
.. code-block:: bash
salt '*' shadow.set_mindays admin 90
'''
return False
def set_inactdays(name, days):
'''
Set the number if inactive days before the account is locked. Not available
in macOS
:param str name: The user name
:param int days: The number of days
:return: Will always return False until macOS supports this feature.
:rtype: bool
CLI Example:
.. code-block:: bash
salt '*' shadow.set_inactdays admin 90
'''
return False
def set_warndays(name, days):
'''
Set the number of days before the password expires that the user will start
to see a warning. Not available in macOS
:param str name: The user name
:param int days: The number of days
:return: Will always return False until macOS supports this feature.
:rtype: bool
CLI Example:
.. code-block:: bash
salt '*' shadow.set_warndays admin 90
'''
return False
def set_change(name, date):
'''
Sets the date on which the password expires. The user will be required to
change their password. Format is mm/dd/yyyy
:param str name: The name of the user account
:param date date: The date the password will expire. Must be in mm/dd/yyyy
format.
:return: True if successful, otherwise False
:rtype: bool
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.set_change username 09/21/2016
'''
_set_account_policy(
name, 'usingExpirationDate=1 expirationDateGMT={0}'.format(date))
return get_change(name) == date
def get_change(name):
'''
Gets the date on which the password expires
:param str name: The name of the user account
:return: The date the password will expire
:rtype: str
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.get_change username
'''
policies = _get_account_policy(name)
if 'expirationDateGMT' in policies:
return policies['expirationDateGMT']
return 'Value not set'
def set_expire(name, date):
'''
Sets the date on which the account expires. The user will not be able to
login after this date. Date format is mm/dd/yyyy
:param str name: The name of the user account
:param datetime date: The date the account will expire. Format must be
mm/dd/yyyy.
:return: True if successful, False if not
:rtype: bool
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.set_expire username 07/23/2015
'''
_set_account_policy(
name, 'usingHardExpirationDate=1 hardExpireDateGMT={0}'.format(date))
return get_expire(name) == date
def get_expire(name):
'''
Gets the date on which the account expires
:param str name: The name of the user account
:return: The date the account expires
:rtype: str
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.get_expire username
'''
policies = _get_account_policy(name)
if 'hardExpireDateGMT' in policies:
return policies['hardExpireDateGMT']
return 'Value not set'
def del_password(name):
'''
Deletes the account password
:param str name: The user name of the account
:return: True if successful, otherwise False
:rtype: bool
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.del_password username
'''
# This removes the password
cmd = "dscl . -passwd /Users/{0} ''".format(name)
try:
salt.utils.mac_utils.execute_return_success(cmd)
except CommandExecutionError as exc:
if 'eDSUnknownNodeName' in exc.strerror:
raise CommandExecutionError('User not found: {0}'.format(name))
raise CommandExecutionError('Unknown error: {0}'.format(exc.strerror))
# This is so it looks right in shadow.info
cmd = "dscl . -create /Users/{0} Password '*'".format(name)
salt.utils.mac_utils.execute_return_success(cmd)
return info(name)['passwd'] == '*'
def set_password(name, password):
'''
Set the password for a named user (insecure, the password will be in the
process list while the command is running)
:param str name: The name of the local user, which is assumed to be in the
local directory service
:param str password: The plaintext password to set
:return: True if successful, otherwise False
:rtype: bool
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' mac_shadow.set_password macuser macpassword
'''
cmd = "dscl . -passwd /Users/{0} '{1}'".format(name, password)
try:
salt.utils.mac_utils.execute_return_success(cmd)
except CommandExecutionError as exc:
if 'eDSUnknownNodeName' in exc.strerror:
raise CommandExecutionError('User not found: {0}'.format(name))
raise CommandExecutionError('Unknown error: {0}'.format(exc.strerror))
return True
|
saltstack/salt
|
salt/modules/mac_shadow.py
|
_get_account_policy_data_value
|
python
|
def _get_account_policy_data_value(name, key):
'''
Return the value for a key in the accountPolicy section of the user's plist
file. For use by this module only
:param str name: The username
:param str key: The accountPolicy key
:return: The value contained within the key
:rtype: str
:raises: CommandExecutionError on user not found or any other unknown error
'''
cmd = 'dscl . -readpl /Users/{0} accountPolicyData {1}'.format(name, key)
try:
ret = salt.utils.mac_utils.execute_return_result(cmd)
except CommandExecutionError as exc:
if 'eDSUnknownNodeName' in exc.strerror:
raise CommandExecutionError('User not found: {0}'.format(name))
raise CommandExecutionError('Unknown error: {0}'.format(exc.strerror))
return ret
|
Return the value for a key in the accountPolicy section of the user's plist
file. For use by this module only
:param str name: The username
:param str key: The accountPolicy key
:return: The value contained within the key
:rtype: str
:raises: CommandExecutionError on user not found or any other unknown error
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_shadow.py#L100-L121
|
[
"def execute_return_result(cmd):\n '''\n Executes the passed command. Returns the standard out if successful\n\n :param str cmd: The command to run\n\n :return: The standard out of the command if successful, otherwise returns\n an error\n :rtype: str\n\n :raises: Error if command fails or is not supported\n '''\n ret = _run_all(cmd)\n\n if ret['retcode'] != 0 or 'not supported' in ret['stdout'].lower():\n msg = 'Command Failed: {0}\\n'.format(cmd)\n msg += 'Return Code: {0}\\n'.format(ret['retcode'])\n msg += 'Output: {0}\\n'.format(ret['stdout'])\n msg += 'Error: {0}\\n'.format(ret['stderr'])\n raise CommandExecutionError(msg)\n\n return ret['stdout']\n"
] |
# -*- coding: utf-8 -*-
'''
Manage macOS local directory passwords and policies
.. versionadded:: 2016.3.0
Note that it is usually better to apply password policies through the creation
of a configuration profile.
'''
# Authentication concepts reference:
# https://developer.apple.com/library/mac/documentation/Networking/Conceptual/Open_Directory/openDirectoryConcepts/openDirectoryConcepts.html#//apple_ref/doc/uid/TP40000917-CH3-CIFCAIBB
from __future__ import absolute_import, unicode_literals, print_function
from datetime import datetime
try:
import pwd
HAS_PWD = True
except ImportError:
HAS_PWD = False
# Import salt libs
import logging
import salt.utils.mac_utils
import salt.utils.platform
from salt.exceptions import CommandExecutionError
log = logging.getLogger(__name__) # Start logging
__virtualname__ = 'shadow'
def __virtual__():
# Is this macOS?
if not salt.utils.platform.is_darwin():
return False, 'Not macOS'
if HAS_PWD:
return __virtualname__
else:
return (False, 'The pwd module failed to load.')
def _get_account_policy(name):
'''
Get the entire accountPolicy and return it as a dictionary. For use by this
module only
:param str name: The user name
:return: a dictionary containing all values for the accountPolicy
:rtype: dict
:raises: CommandExecutionError on user not found or any other unknown error
'''
cmd = 'pwpolicy -u {0} -getpolicy'.format(name)
try:
ret = salt.utils.mac_utils.execute_return_result(cmd)
except CommandExecutionError as exc:
if 'Error: user <{0}> not found'.format(name) in exc.strerror:
raise CommandExecutionError('User not found: {0}'.format(name))
raise CommandExecutionError('Unknown error: {0}'.format(exc.strerror))
try:
policy_list = ret.split('\n')[1].split(' ')
policy_dict = {}
for policy in policy_list:
if '=' in policy:
key, value = policy.split('=')
policy_dict[key] = value
return policy_dict
except IndexError:
return {}
def _set_account_policy(name, policy):
'''
Set a value in the user accountPolicy. For use by this module only
:param str name: The user name
:param str policy: The policy to apply
:return: True if success, otherwise False
:rtype: bool
:raises: CommandExecutionError on user not found or any other unknown error
'''
cmd = 'pwpolicy -u {0} -setpolicy "{1}"'.format(name, policy)
try:
return salt.utils.mac_utils.execute_return_success(cmd)
except CommandExecutionError as exc:
if 'Error: user <{0}> not found'.format(name) in exc.strerror:
raise CommandExecutionError('User not found: {0}'.format(name))
raise CommandExecutionError('Unknown error: {0}'.format(exc.strerror))
def _convert_to_datetime(unix_timestamp):
'''
Converts a unix timestamp to a human readable date/time
:param float unix_timestamp: A unix timestamp
:return: A date/time in the format YYYY-mm-dd HH:MM:SS
:rtype: str
'''
try:
unix_timestamp = float(unix_timestamp)
return datetime.fromtimestamp(unix_timestamp).strftime('%Y-%m-%d %H:%M:%S')
except (ValueError, TypeError):
return 'Invalid Timestamp'
def info(name):
'''
Return information for the specified user
:param str name: The username
:return: A dictionary containing the user's shadow information
:rtype: dict
CLI Example:
.. code-block:: bash
salt '*' shadow.info admin
'''
try:
data = pwd.getpwnam(name)
return {'name': data.pw_name,
'passwd': data.pw_passwd,
'account_created': get_account_created(name),
'login_failed_count': get_login_failed_count(name),
'login_failed_last': get_login_failed_last(name),
'lstchg': get_last_change(name),
'max': get_maxdays(name),
'expire': get_expire(name),
'change': get_change(name),
'min': 'Unavailable',
'warn': 'Unavailable',
'inact': 'Unavailable'}
except KeyError:
log.debug('User not found: %s', name)
return {'name': '',
'passwd': '',
'account_created': '',
'login_failed_count': '',
'login_failed_last': '',
'lstchg': '',
'max': '',
'expire': '',
'change': '',
'min': '',
'warn': '',
'inact': ''}
def get_account_created(name):
'''
Get the date/time the account was created
:param str name: The username of the account
:return: The date/time the account was created (yyyy-mm-dd hh:mm:ss)
:rtype: str
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.get_account_created admin
'''
ret = _get_account_policy_data_value(name, 'creationTime')
unix_timestamp = salt.utils.mac_utils.parse_return(ret)
date_text = _convert_to_datetime(unix_timestamp)
return date_text
def get_last_change(name):
'''
Get the date/time the account was changed
:param str name: The username of the account
:return: The date/time the account was modified (yyyy-mm-dd hh:mm:ss)
:rtype: str
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.get_last_change admin
'''
ret = _get_account_policy_data_value(name, 'passwordLastSetTime')
unix_timestamp = salt.utils.mac_utils.parse_return(ret)
date_text = _convert_to_datetime(unix_timestamp)
return date_text
def get_login_failed_count(name):
'''
Get the the number of failed login attempts
:param str name: The username of the account
:return: The number of failed login attempts
:rtype: int
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.get_login_failed_count admin
'''
ret = _get_account_policy_data_value(name, 'failedLoginCount')
return salt.utils.mac_utils.parse_return(ret)
def get_login_failed_last(name):
'''
Get the date/time of the last failed login attempt
:param str name: The username of the account
:return: The date/time of the last failed login attempt on this account
(yyyy-mm-dd hh:mm:ss)
:rtype: str
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.get_login_failed_last admin
'''
ret = _get_account_policy_data_value(name, 'failedLoginTimestamp')
unix_timestamp = salt.utils.mac_utils.parse_return(ret)
date_text = _convert_to_datetime(unix_timestamp)
return date_text
def set_maxdays(name, days):
'''
Set the maximum age of the password in days
:param str name: The username of the account
:param int days: The maximum age of the account in days
:return: True if successful, False if not
:rtype: bool
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.set_maxdays admin 90
'''
minutes = days * 24 * 60
_set_account_policy(
name, 'maxMinutesUntilChangePassword={0}'.format(minutes))
return get_maxdays(name) == days
def get_maxdays(name):
'''
Get the maximum age of the password
:param str name: The username of the account
:return: The maximum age of the password in days
:rtype: int
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.get_maxdays admin 90
'''
policies = _get_account_policy(name)
if 'maxMinutesUntilChangePassword' in policies:
max_minutes = policies['maxMinutesUntilChangePassword']
return int(max_minutes) / 24 / 60
return 0
def set_mindays(name, days):
'''
Set the minimum password age in days. Not available in macOS.
:param str name: The user name
:param int days: The number of days
:return: Will always return False until macOS supports this feature.
:rtype: bool
CLI Example:
.. code-block:: bash
salt '*' shadow.set_mindays admin 90
'''
return False
def set_inactdays(name, days):
'''
Set the number if inactive days before the account is locked. Not available
in macOS
:param str name: The user name
:param int days: The number of days
:return: Will always return False until macOS supports this feature.
:rtype: bool
CLI Example:
.. code-block:: bash
salt '*' shadow.set_inactdays admin 90
'''
return False
def set_warndays(name, days):
'''
Set the number of days before the password expires that the user will start
to see a warning. Not available in macOS
:param str name: The user name
:param int days: The number of days
:return: Will always return False until macOS supports this feature.
:rtype: bool
CLI Example:
.. code-block:: bash
salt '*' shadow.set_warndays admin 90
'''
return False
def set_change(name, date):
'''
Sets the date on which the password expires. The user will be required to
change their password. Format is mm/dd/yyyy
:param str name: The name of the user account
:param date date: The date the password will expire. Must be in mm/dd/yyyy
format.
:return: True if successful, otherwise False
:rtype: bool
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.set_change username 09/21/2016
'''
_set_account_policy(
name, 'usingExpirationDate=1 expirationDateGMT={0}'.format(date))
return get_change(name) == date
def get_change(name):
'''
Gets the date on which the password expires
:param str name: The name of the user account
:return: The date the password will expire
:rtype: str
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.get_change username
'''
policies = _get_account_policy(name)
if 'expirationDateGMT' in policies:
return policies['expirationDateGMT']
return 'Value not set'
def set_expire(name, date):
'''
Sets the date on which the account expires. The user will not be able to
login after this date. Date format is mm/dd/yyyy
:param str name: The name of the user account
:param datetime date: The date the account will expire. Format must be
mm/dd/yyyy.
:return: True if successful, False if not
:rtype: bool
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.set_expire username 07/23/2015
'''
_set_account_policy(
name, 'usingHardExpirationDate=1 hardExpireDateGMT={0}'.format(date))
return get_expire(name) == date
def get_expire(name):
'''
Gets the date on which the account expires
:param str name: The name of the user account
:return: The date the account expires
:rtype: str
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.get_expire username
'''
policies = _get_account_policy(name)
if 'hardExpireDateGMT' in policies:
return policies['hardExpireDateGMT']
return 'Value not set'
def del_password(name):
'''
Deletes the account password
:param str name: The user name of the account
:return: True if successful, otherwise False
:rtype: bool
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.del_password username
'''
# This removes the password
cmd = "dscl . -passwd /Users/{0} ''".format(name)
try:
salt.utils.mac_utils.execute_return_success(cmd)
except CommandExecutionError as exc:
if 'eDSUnknownNodeName' in exc.strerror:
raise CommandExecutionError('User not found: {0}'.format(name))
raise CommandExecutionError('Unknown error: {0}'.format(exc.strerror))
# This is so it looks right in shadow.info
cmd = "dscl . -create /Users/{0} Password '*'".format(name)
salt.utils.mac_utils.execute_return_success(cmd)
return info(name)['passwd'] == '*'
def set_password(name, password):
'''
Set the password for a named user (insecure, the password will be in the
process list while the command is running)
:param str name: The name of the local user, which is assumed to be in the
local directory service
:param str password: The plaintext password to set
:return: True if successful, otherwise False
:rtype: bool
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' mac_shadow.set_password macuser macpassword
'''
cmd = "dscl . -passwd /Users/{0} '{1}'".format(name, password)
try:
salt.utils.mac_utils.execute_return_success(cmd)
except CommandExecutionError as exc:
if 'eDSUnknownNodeName' in exc.strerror:
raise CommandExecutionError('User not found: {0}'.format(name))
raise CommandExecutionError('Unknown error: {0}'.format(exc.strerror))
return True
|
saltstack/salt
|
salt/modules/mac_shadow.py
|
_convert_to_datetime
|
python
|
def _convert_to_datetime(unix_timestamp):
'''
Converts a unix timestamp to a human readable date/time
:param float unix_timestamp: A unix timestamp
:return: A date/time in the format YYYY-mm-dd HH:MM:SS
:rtype: str
'''
try:
unix_timestamp = float(unix_timestamp)
return datetime.fromtimestamp(unix_timestamp).strftime('%Y-%m-%d %H:%M:%S')
except (ValueError, TypeError):
return 'Invalid Timestamp'
|
Converts a unix timestamp to a human readable date/time
:param float unix_timestamp: A unix timestamp
:return: A date/time in the format YYYY-mm-dd HH:MM:SS
:rtype: str
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_shadow.py#L124-L137
| null |
# -*- coding: utf-8 -*-
'''
Manage macOS local directory passwords and policies
.. versionadded:: 2016.3.0
Note that it is usually better to apply password policies through the creation
of a configuration profile.
'''
# Authentication concepts reference:
# https://developer.apple.com/library/mac/documentation/Networking/Conceptual/Open_Directory/openDirectoryConcepts/openDirectoryConcepts.html#//apple_ref/doc/uid/TP40000917-CH3-CIFCAIBB
from __future__ import absolute_import, unicode_literals, print_function
from datetime import datetime
try:
import pwd
HAS_PWD = True
except ImportError:
HAS_PWD = False
# Import salt libs
import logging
import salt.utils.mac_utils
import salt.utils.platform
from salt.exceptions import CommandExecutionError
log = logging.getLogger(__name__) # Start logging
__virtualname__ = 'shadow'
def __virtual__():
# Is this macOS?
if not salt.utils.platform.is_darwin():
return False, 'Not macOS'
if HAS_PWD:
return __virtualname__
else:
return (False, 'The pwd module failed to load.')
def _get_account_policy(name):
'''
Get the entire accountPolicy and return it as a dictionary. For use by this
module only
:param str name: The user name
:return: a dictionary containing all values for the accountPolicy
:rtype: dict
:raises: CommandExecutionError on user not found or any other unknown error
'''
cmd = 'pwpolicy -u {0} -getpolicy'.format(name)
try:
ret = salt.utils.mac_utils.execute_return_result(cmd)
except CommandExecutionError as exc:
if 'Error: user <{0}> not found'.format(name) in exc.strerror:
raise CommandExecutionError('User not found: {0}'.format(name))
raise CommandExecutionError('Unknown error: {0}'.format(exc.strerror))
try:
policy_list = ret.split('\n')[1].split(' ')
policy_dict = {}
for policy in policy_list:
if '=' in policy:
key, value = policy.split('=')
policy_dict[key] = value
return policy_dict
except IndexError:
return {}
def _set_account_policy(name, policy):
'''
Set a value in the user accountPolicy. For use by this module only
:param str name: The user name
:param str policy: The policy to apply
:return: True if success, otherwise False
:rtype: bool
:raises: CommandExecutionError on user not found or any other unknown error
'''
cmd = 'pwpolicy -u {0} -setpolicy "{1}"'.format(name, policy)
try:
return salt.utils.mac_utils.execute_return_success(cmd)
except CommandExecutionError as exc:
if 'Error: user <{0}> not found'.format(name) in exc.strerror:
raise CommandExecutionError('User not found: {0}'.format(name))
raise CommandExecutionError('Unknown error: {0}'.format(exc.strerror))
def _get_account_policy_data_value(name, key):
'''
Return the value for a key in the accountPolicy section of the user's plist
file. For use by this module only
:param str name: The username
:param str key: The accountPolicy key
:return: The value contained within the key
:rtype: str
:raises: CommandExecutionError on user not found or any other unknown error
'''
cmd = 'dscl . -readpl /Users/{0} accountPolicyData {1}'.format(name, key)
try:
ret = salt.utils.mac_utils.execute_return_result(cmd)
except CommandExecutionError as exc:
if 'eDSUnknownNodeName' in exc.strerror:
raise CommandExecutionError('User not found: {0}'.format(name))
raise CommandExecutionError('Unknown error: {0}'.format(exc.strerror))
return ret
def info(name):
'''
Return information for the specified user
:param str name: The username
:return: A dictionary containing the user's shadow information
:rtype: dict
CLI Example:
.. code-block:: bash
salt '*' shadow.info admin
'''
try:
data = pwd.getpwnam(name)
return {'name': data.pw_name,
'passwd': data.pw_passwd,
'account_created': get_account_created(name),
'login_failed_count': get_login_failed_count(name),
'login_failed_last': get_login_failed_last(name),
'lstchg': get_last_change(name),
'max': get_maxdays(name),
'expire': get_expire(name),
'change': get_change(name),
'min': 'Unavailable',
'warn': 'Unavailable',
'inact': 'Unavailable'}
except KeyError:
log.debug('User not found: %s', name)
return {'name': '',
'passwd': '',
'account_created': '',
'login_failed_count': '',
'login_failed_last': '',
'lstchg': '',
'max': '',
'expire': '',
'change': '',
'min': '',
'warn': '',
'inact': ''}
def get_account_created(name):
'''
Get the date/time the account was created
:param str name: The username of the account
:return: The date/time the account was created (yyyy-mm-dd hh:mm:ss)
:rtype: str
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.get_account_created admin
'''
ret = _get_account_policy_data_value(name, 'creationTime')
unix_timestamp = salt.utils.mac_utils.parse_return(ret)
date_text = _convert_to_datetime(unix_timestamp)
return date_text
def get_last_change(name):
'''
Get the date/time the account was changed
:param str name: The username of the account
:return: The date/time the account was modified (yyyy-mm-dd hh:mm:ss)
:rtype: str
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.get_last_change admin
'''
ret = _get_account_policy_data_value(name, 'passwordLastSetTime')
unix_timestamp = salt.utils.mac_utils.parse_return(ret)
date_text = _convert_to_datetime(unix_timestamp)
return date_text
def get_login_failed_count(name):
'''
Get the the number of failed login attempts
:param str name: The username of the account
:return: The number of failed login attempts
:rtype: int
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.get_login_failed_count admin
'''
ret = _get_account_policy_data_value(name, 'failedLoginCount')
return salt.utils.mac_utils.parse_return(ret)
def get_login_failed_last(name):
'''
Get the date/time of the last failed login attempt
:param str name: The username of the account
:return: The date/time of the last failed login attempt on this account
(yyyy-mm-dd hh:mm:ss)
:rtype: str
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.get_login_failed_last admin
'''
ret = _get_account_policy_data_value(name, 'failedLoginTimestamp')
unix_timestamp = salt.utils.mac_utils.parse_return(ret)
date_text = _convert_to_datetime(unix_timestamp)
return date_text
def set_maxdays(name, days):
'''
Set the maximum age of the password in days
:param str name: The username of the account
:param int days: The maximum age of the account in days
:return: True if successful, False if not
:rtype: bool
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.set_maxdays admin 90
'''
minutes = days * 24 * 60
_set_account_policy(
name, 'maxMinutesUntilChangePassword={0}'.format(minutes))
return get_maxdays(name) == days
def get_maxdays(name):
'''
Get the maximum age of the password
:param str name: The username of the account
:return: The maximum age of the password in days
:rtype: int
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.get_maxdays admin 90
'''
policies = _get_account_policy(name)
if 'maxMinutesUntilChangePassword' in policies:
max_minutes = policies['maxMinutesUntilChangePassword']
return int(max_minutes) / 24 / 60
return 0
def set_mindays(name, days):
'''
Set the minimum password age in days. Not available in macOS.
:param str name: The user name
:param int days: The number of days
:return: Will always return False until macOS supports this feature.
:rtype: bool
CLI Example:
.. code-block:: bash
salt '*' shadow.set_mindays admin 90
'''
return False
def set_inactdays(name, days):
'''
Set the number if inactive days before the account is locked. Not available
in macOS
:param str name: The user name
:param int days: The number of days
:return: Will always return False until macOS supports this feature.
:rtype: bool
CLI Example:
.. code-block:: bash
salt '*' shadow.set_inactdays admin 90
'''
return False
def set_warndays(name, days):
'''
Set the number of days before the password expires that the user will start
to see a warning. Not available in macOS
:param str name: The user name
:param int days: The number of days
:return: Will always return False until macOS supports this feature.
:rtype: bool
CLI Example:
.. code-block:: bash
salt '*' shadow.set_warndays admin 90
'''
return False
def set_change(name, date):
'''
Sets the date on which the password expires. The user will be required to
change their password. Format is mm/dd/yyyy
:param str name: The name of the user account
:param date date: The date the password will expire. Must be in mm/dd/yyyy
format.
:return: True if successful, otherwise False
:rtype: bool
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.set_change username 09/21/2016
'''
_set_account_policy(
name, 'usingExpirationDate=1 expirationDateGMT={0}'.format(date))
return get_change(name) == date
def get_change(name):
'''
Gets the date on which the password expires
:param str name: The name of the user account
:return: The date the password will expire
:rtype: str
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.get_change username
'''
policies = _get_account_policy(name)
if 'expirationDateGMT' in policies:
return policies['expirationDateGMT']
return 'Value not set'
def set_expire(name, date):
'''
Sets the date on which the account expires. The user will not be able to
login after this date. Date format is mm/dd/yyyy
:param str name: The name of the user account
:param datetime date: The date the account will expire. Format must be
mm/dd/yyyy.
:return: True if successful, False if not
:rtype: bool
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.set_expire username 07/23/2015
'''
_set_account_policy(
name, 'usingHardExpirationDate=1 hardExpireDateGMT={0}'.format(date))
return get_expire(name) == date
def get_expire(name):
'''
Gets the date on which the account expires
:param str name: The name of the user account
:return: The date the account expires
:rtype: str
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.get_expire username
'''
policies = _get_account_policy(name)
if 'hardExpireDateGMT' in policies:
return policies['hardExpireDateGMT']
return 'Value not set'
def del_password(name):
'''
Deletes the account password
:param str name: The user name of the account
:return: True if successful, otherwise False
:rtype: bool
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.del_password username
'''
# This removes the password
cmd = "dscl . -passwd /Users/{0} ''".format(name)
try:
salt.utils.mac_utils.execute_return_success(cmd)
except CommandExecutionError as exc:
if 'eDSUnknownNodeName' in exc.strerror:
raise CommandExecutionError('User not found: {0}'.format(name))
raise CommandExecutionError('Unknown error: {0}'.format(exc.strerror))
# This is so it looks right in shadow.info
cmd = "dscl . -create /Users/{0} Password '*'".format(name)
salt.utils.mac_utils.execute_return_success(cmd)
return info(name)['passwd'] == '*'
def set_password(name, password):
'''
Set the password for a named user (insecure, the password will be in the
process list while the command is running)
:param str name: The name of the local user, which is assumed to be in the
local directory service
:param str password: The plaintext password to set
:return: True if successful, otherwise False
:rtype: bool
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' mac_shadow.set_password macuser macpassword
'''
cmd = "dscl . -passwd /Users/{0} '{1}'".format(name, password)
try:
salt.utils.mac_utils.execute_return_success(cmd)
except CommandExecutionError as exc:
if 'eDSUnknownNodeName' in exc.strerror:
raise CommandExecutionError('User not found: {0}'.format(name))
raise CommandExecutionError('Unknown error: {0}'.format(exc.strerror))
return True
|
saltstack/salt
|
salt/modules/mac_shadow.py
|
info
|
python
|
def info(name):
'''
Return information for the specified user
:param str name: The username
:return: A dictionary containing the user's shadow information
:rtype: dict
CLI Example:
.. code-block:: bash
salt '*' shadow.info admin
'''
try:
data = pwd.getpwnam(name)
return {'name': data.pw_name,
'passwd': data.pw_passwd,
'account_created': get_account_created(name),
'login_failed_count': get_login_failed_count(name),
'login_failed_last': get_login_failed_last(name),
'lstchg': get_last_change(name),
'max': get_maxdays(name),
'expire': get_expire(name),
'change': get_change(name),
'min': 'Unavailable',
'warn': 'Unavailable',
'inact': 'Unavailable'}
except KeyError:
log.debug('User not found: %s', name)
return {'name': '',
'passwd': '',
'account_created': '',
'login_failed_count': '',
'login_failed_last': '',
'lstchg': '',
'max': '',
'expire': '',
'change': '',
'min': '',
'warn': '',
'inact': ''}
|
Return information for the specified user
:param str name: The username
:return: A dictionary containing the user's shadow information
:rtype: dict
CLI Example:
.. code-block:: bash
salt '*' shadow.info admin
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_shadow.py#L140-L183
|
[
"def get_change(name):\n '''\n Gets the date on which the password expires\n\n :param str name: The name of the user account\n\n :return: The date the password will expire\n :rtype: str\n\n :raises: CommandExecutionError on user not found or any other unknown error\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' shadow.get_change username\n '''\n policies = _get_account_policy(name)\n\n if 'expirationDateGMT' in policies:\n return policies['expirationDateGMT']\n\n return 'Value not set'\n",
"def get_account_created(name):\n '''\n Get the date/time the account was created\n\n :param str name: The username of the account\n\n :return: The date/time the account was created (yyyy-mm-dd hh:mm:ss)\n :rtype: str\n\n :raises: CommandExecutionError on user not found or any other unknown error\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' shadow.get_account_created admin\n '''\n ret = _get_account_policy_data_value(name, 'creationTime')\n\n unix_timestamp = salt.utils.mac_utils.parse_return(ret)\n\n date_text = _convert_to_datetime(unix_timestamp)\n\n return date_text\n",
"def get_login_failed_count(name):\n '''\n Get the the number of failed login attempts\n\n :param str name: The username of the account\n\n :return: The number of failed login attempts\n :rtype: int\n\n :raises: CommandExecutionError on user not found or any other unknown error\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' shadow.get_login_failed_count admin\n '''\n ret = _get_account_policy_data_value(name, 'failedLoginCount')\n\n return salt.utils.mac_utils.parse_return(ret)\n",
"def get_login_failed_last(name):\n '''\n Get the date/time of the last failed login attempt\n\n :param str name: The username of the account\n\n :return: The date/time of the last failed login attempt on this account\n (yyyy-mm-dd hh:mm:ss)\n :rtype: str\n\n :raises: CommandExecutionError on user not found or any other unknown error\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' shadow.get_login_failed_last admin\n '''\n ret = _get_account_policy_data_value(name, 'failedLoginTimestamp')\n\n unix_timestamp = salt.utils.mac_utils.parse_return(ret)\n\n date_text = _convert_to_datetime(unix_timestamp)\n\n return date_text\n",
"def get_last_change(name):\n '''\n Get the date/time the account was changed\n\n :param str name: The username of the account\n\n :return: The date/time the account was modified (yyyy-mm-dd hh:mm:ss)\n :rtype: str\n\n :raises: CommandExecutionError on user not found or any other unknown error\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' shadow.get_last_change admin\n '''\n ret = _get_account_policy_data_value(name, 'passwordLastSetTime')\n\n unix_timestamp = salt.utils.mac_utils.parse_return(ret)\n\n date_text = _convert_to_datetime(unix_timestamp)\n\n return date_text\n",
"def get_maxdays(name):\n '''\n Get the maximum age of the password\n\n :param str name: The username of the account\n\n :return: The maximum age of the password in days\n :rtype: int\n\n :raises: CommandExecutionError on user not found or any other unknown error\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' shadow.get_maxdays admin 90\n '''\n policies = _get_account_policy(name)\n\n if 'maxMinutesUntilChangePassword' in policies:\n max_minutes = policies['maxMinutesUntilChangePassword']\n return int(max_minutes) / 24 / 60\n\n return 0\n",
"def get_expire(name):\n '''\n Gets the date on which the account expires\n\n :param str name: The name of the user account\n\n :return: The date the account expires\n :rtype: str\n\n :raises: CommandExecutionError on user not found or any other unknown error\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' shadow.get_expire username\n '''\n policies = _get_account_policy(name)\n\n if 'hardExpireDateGMT' in policies:\n return policies['hardExpireDateGMT']\n\n return 'Value not set'\n"
] |
# -*- coding: utf-8 -*-
'''
Manage macOS local directory passwords and policies
.. versionadded:: 2016.3.0
Note that it is usually better to apply password policies through the creation
of a configuration profile.
'''
# Authentication concepts reference:
# https://developer.apple.com/library/mac/documentation/Networking/Conceptual/Open_Directory/openDirectoryConcepts/openDirectoryConcepts.html#//apple_ref/doc/uid/TP40000917-CH3-CIFCAIBB
from __future__ import absolute_import, unicode_literals, print_function
from datetime import datetime
try:
import pwd
HAS_PWD = True
except ImportError:
HAS_PWD = False
# Import salt libs
import logging
import salt.utils.mac_utils
import salt.utils.platform
from salt.exceptions import CommandExecutionError
log = logging.getLogger(__name__) # Start logging
__virtualname__ = 'shadow'
def __virtual__():
# Is this macOS?
if not salt.utils.platform.is_darwin():
return False, 'Not macOS'
if HAS_PWD:
return __virtualname__
else:
return (False, 'The pwd module failed to load.')
def _get_account_policy(name):
'''
Get the entire accountPolicy and return it as a dictionary. For use by this
module only
:param str name: The user name
:return: a dictionary containing all values for the accountPolicy
:rtype: dict
:raises: CommandExecutionError on user not found or any other unknown error
'''
cmd = 'pwpolicy -u {0} -getpolicy'.format(name)
try:
ret = salt.utils.mac_utils.execute_return_result(cmd)
except CommandExecutionError as exc:
if 'Error: user <{0}> not found'.format(name) in exc.strerror:
raise CommandExecutionError('User not found: {0}'.format(name))
raise CommandExecutionError('Unknown error: {0}'.format(exc.strerror))
try:
policy_list = ret.split('\n')[1].split(' ')
policy_dict = {}
for policy in policy_list:
if '=' in policy:
key, value = policy.split('=')
policy_dict[key] = value
return policy_dict
except IndexError:
return {}
def _set_account_policy(name, policy):
'''
Set a value in the user accountPolicy. For use by this module only
:param str name: The user name
:param str policy: The policy to apply
:return: True if success, otherwise False
:rtype: bool
:raises: CommandExecutionError on user not found or any other unknown error
'''
cmd = 'pwpolicy -u {0} -setpolicy "{1}"'.format(name, policy)
try:
return salt.utils.mac_utils.execute_return_success(cmd)
except CommandExecutionError as exc:
if 'Error: user <{0}> not found'.format(name) in exc.strerror:
raise CommandExecutionError('User not found: {0}'.format(name))
raise CommandExecutionError('Unknown error: {0}'.format(exc.strerror))
def _get_account_policy_data_value(name, key):
'''
Return the value for a key in the accountPolicy section of the user's plist
file. For use by this module only
:param str name: The username
:param str key: The accountPolicy key
:return: The value contained within the key
:rtype: str
:raises: CommandExecutionError on user not found or any other unknown error
'''
cmd = 'dscl . -readpl /Users/{0} accountPolicyData {1}'.format(name, key)
try:
ret = salt.utils.mac_utils.execute_return_result(cmd)
except CommandExecutionError as exc:
if 'eDSUnknownNodeName' in exc.strerror:
raise CommandExecutionError('User not found: {0}'.format(name))
raise CommandExecutionError('Unknown error: {0}'.format(exc.strerror))
return ret
def _convert_to_datetime(unix_timestamp):
'''
Converts a unix timestamp to a human readable date/time
:param float unix_timestamp: A unix timestamp
:return: A date/time in the format YYYY-mm-dd HH:MM:SS
:rtype: str
'''
try:
unix_timestamp = float(unix_timestamp)
return datetime.fromtimestamp(unix_timestamp).strftime('%Y-%m-%d %H:%M:%S')
except (ValueError, TypeError):
return 'Invalid Timestamp'
def get_account_created(name):
'''
Get the date/time the account was created
:param str name: The username of the account
:return: The date/time the account was created (yyyy-mm-dd hh:mm:ss)
:rtype: str
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.get_account_created admin
'''
ret = _get_account_policy_data_value(name, 'creationTime')
unix_timestamp = salt.utils.mac_utils.parse_return(ret)
date_text = _convert_to_datetime(unix_timestamp)
return date_text
def get_last_change(name):
'''
Get the date/time the account was changed
:param str name: The username of the account
:return: The date/time the account was modified (yyyy-mm-dd hh:mm:ss)
:rtype: str
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.get_last_change admin
'''
ret = _get_account_policy_data_value(name, 'passwordLastSetTime')
unix_timestamp = salt.utils.mac_utils.parse_return(ret)
date_text = _convert_to_datetime(unix_timestamp)
return date_text
def get_login_failed_count(name):
'''
Get the the number of failed login attempts
:param str name: The username of the account
:return: The number of failed login attempts
:rtype: int
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.get_login_failed_count admin
'''
ret = _get_account_policy_data_value(name, 'failedLoginCount')
return salt.utils.mac_utils.parse_return(ret)
def get_login_failed_last(name):
'''
Get the date/time of the last failed login attempt
:param str name: The username of the account
:return: The date/time of the last failed login attempt on this account
(yyyy-mm-dd hh:mm:ss)
:rtype: str
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.get_login_failed_last admin
'''
ret = _get_account_policy_data_value(name, 'failedLoginTimestamp')
unix_timestamp = salt.utils.mac_utils.parse_return(ret)
date_text = _convert_to_datetime(unix_timestamp)
return date_text
def set_maxdays(name, days):
'''
Set the maximum age of the password in days
:param str name: The username of the account
:param int days: The maximum age of the account in days
:return: True if successful, False if not
:rtype: bool
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.set_maxdays admin 90
'''
minutes = days * 24 * 60
_set_account_policy(
name, 'maxMinutesUntilChangePassword={0}'.format(minutes))
return get_maxdays(name) == days
def get_maxdays(name):
'''
Get the maximum age of the password
:param str name: The username of the account
:return: The maximum age of the password in days
:rtype: int
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.get_maxdays admin 90
'''
policies = _get_account_policy(name)
if 'maxMinutesUntilChangePassword' in policies:
max_minutes = policies['maxMinutesUntilChangePassword']
return int(max_minutes) / 24 / 60
return 0
def set_mindays(name, days):
'''
Set the minimum password age in days. Not available in macOS.
:param str name: The user name
:param int days: The number of days
:return: Will always return False until macOS supports this feature.
:rtype: bool
CLI Example:
.. code-block:: bash
salt '*' shadow.set_mindays admin 90
'''
return False
def set_inactdays(name, days):
'''
Set the number if inactive days before the account is locked. Not available
in macOS
:param str name: The user name
:param int days: The number of days
:return: Will always return False until macOS supports this feature.
:rtype: bool
CLI Example:
.. code-block:: bash
salt '*' shadow.set_inactdays admin 90
'''
return False
def set_warndays(name, days):
'''
Set the number of days before the password expires that the user will start
to see a warning. Not available in macOS
:param str name: The user name
:param int days: The number of days
:return: Will always return False until macOS supports this feature.
:rtype: bool
CLI Example:
.. code-block:: bash
salt '*' shadow.set_warndays admin 90
'''
return False
def set_change(name, date):
'''
Sets the date on which the password expires. The user will be required to
change their password. Format is mm/dd/yyyy
:param str name: The name of the user account
:param date date: The date the password will expire. Must be in mm/dd/yyyy
format.
:return: True if successful, otherwise False
:rtype: bool
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.set_change username 09/21/2016
'''
_set_account_policy(
name, 'usingExpirationDate=1 expirationDateGMT={0}'.format(date))
return get_change(name) == date
def get_change(name):
'''
Gets the date on which the password expires
:param str name: The name of the user account
:return: The date the password will expire
:rtype: str
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.get_change username
'''
policies = _get_account_policy(name)
if 'expirationDateGMT' in policies:
return policies['expirationDateGMT']
return 'Value not set'
def set_expire(name, date):
'''
Sets the date on which the account expires. The user will not be able to
login after this date. Date format is mm/dd/yyyy
:param str name: The name of the user account
:param datetime date: The date the account will expire. Format must be
mm/dd/yyyy.
:return: True if successful, False if not
:rtype: bool
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.set_expire username 07/23/2015
'''
_set_account_policy(
name, 'usingHardExpirationDate=1 hardExpireDateGMT={0}'.format(date))
return get_expire(name) == date
def get_expire(name):
'''
Gets the date on which the account expires
:param str name: The name of the user account
:return: The date the account expires
:rtype: str
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.get_expire username
'''
policies = _get_account_policy(name)
if 'hardExpireDateGMT' in policies:
return policies['hardExpireDateGMT']
return 'Value not set'
def del_password(name):
'''
Deletes the account password
:param str name: The user name of the account
:return: True if successful, otherwise False
:rtype: bool
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.del_password username
'''
# This removes the password
cmd = "dscl . -passwd /Users/{0} ''".format(name)
try:
salt.utils.mac_utils.execute_return_success(cmd)
except CommandExecutionError as exc:
if 'eDSUnknownNodeName' in exc.strerror:
raise CommandExecutionError('User not found: {0}'.format(name))
raise CommandExecutionError('Unknown error: {0}'.format(exc.strerror))
# This is so it looks right in shadow.info
cmd = "dscl . -create /Users/{0} Password '*'".format(name)
salt.utils.mac_utils.execute_return_success(cmd)
return info(name)['passwd'] == '*'
def set_password(name, password):
'''
Set the password for a named user (insecure, the password will be in the
process list while the command is running)
:param str name: The name of the local user, which is assumed to be in the
local directory service
:param str password: The plaintext password to set
:return: True if successful, otherwise False
:rtype: bool
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' mac_shadow.set_password macuser macpassword
'''
cmd = "dscl . -passwd /Users/{0} '{1}'".format(name, password)
try:
salt.utils.mac_utils.execute_return_success(cmd)
except CommandExecutionError as exc:
if 'eDSUnknownNodeName' in exc.strerror:
raise CommandExecutionError('User not found: {0}'.format(name))
raise CommandExecutionError('Unknown error: {0}'.format(exc.strerror))
return True
|
saltstack/salt
|
salt/modules/mac_shadow.py
|
get_account_created
|
python
|
def get_account_created(name):
'''
Get the date/time the account was created
:param str name: The username of the account
:return: The date/time the account was created (yyyy-mm-dd hh:mm:ss)
:rtype: str
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.get_account_created admin
'''
ret = _get_account_policy_data_value(name, 'creationTime')
unix_timestamp = salt.utils.mac_utils.parse_return(ret)
date_text = _convert_to_datetime(unix_timestamp)
return date_text
|
Get the date/time the account was created
:param str name: The username of the account
:return: The date/time the account was created (yyyy-mm-dd hh:mm:ss)
:rtype: str
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.get_account_created admin
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_shadow.py#L186-L209
|
[
"def parse_return(data):\n '''\n Returns the data portion of a string that is colon separated.\n\n :param str data: The string that contains the data to be parsed. Usually the\n standard out from a command\n\n For example:\n ``Time Zone: America/Denver``\n will return:\n ``America/Denver``\n '''\n\n if ': ' in data:\n return data.split(': ')[1]\n if ':\\n' in data:\n return data.split(':\\n')[1]\n else:\n return data\n",
"def _get_account_policy_data_value(name, key):\n '''\n Return the value for a key in the accountPolicy section of the user's plist\n file. For use by this module only\n\n :param str name: The username\n :param str key: The accountPolicy key\n\n :return: The value contained within the key\n :rtype: str\n\n :raises: CommandExecutionError on user not found or any other unknown error\n '''\n cmd = 'dscl . -readpl /Users/{0} accountPolicyData {1}'.format(name, key)\n try:\n ret = salt.utils.mac_utils.execute_return_result(cmd)\n except CommandExecutionError as exc:\n if 'eDSUnknownNodeName' in exc.strerror:\n raise CommandExecutionError('User not found: {0}'.format(name))\n raise CommandExecutionError('Unknown error: {0}'.format(exc.strerror))\n\n return ret\n",
"def _convert_to_datetime(unix_timestamp):\n '''\n Converts a unix timestamp to a human readable date/time\n\n :param float unix_timestamp: A unix timestamp\n\n :return: A date/time in the format YYYY-mm-dd HH:MM:SS\n :rtype: str\n '''\n try:\n unix_timestamp = float(unix_timestamp)\n return datetime.fromtimestamp(unix_timestamp).strftime('%Y-%m-%d %H:%M:%S')\n except (ValueError, TypeError):\n return 'Invalid Timestamp'\n"
] |
# -*- coding: utf-8 -*-
'''
Manage macOS local directory passwords and policies
.. versionadded:: 2016.3.0
Note that it is usually better to apply password policies through the creation
of a configuration profile.
'''
# Authentication concepts reference:
# https://developer.apple.com/library/mac/documentation/Networking/Conceptual/Open_Directory/openDirectoryConcepts/openDirectoryConcepts.html#//apple_ref/doc/uid/TP40000917-CH3-CIFCAIBB
from __future__ import absolute_import, unicode_literals, print_function
from datetime import datetime
try:
import pwd
HAS_PWD = True
except ImportError:
HAS_PWD = False
# Import salt libs
import logging
import salt.utils.mac_utils
import salt.utils.platform
from salt.exceptions import CommandExecutionError
log = logging.getLogger(__name__) # Start logging
__virtualname__ = 'shadow'
def __virtual__():
# Is this macOS?
if not salt.utils.platform.is_darwin():
return False, 'Not macOS'
if HAS_PWD:
return __virtualname__
else:
return (False, 'The pwd module failed to load.')
def _get_account_policy(name):
'''
Get the entire accountPolicy and return it as a dictionary. For use by this
module only
:param str name: The user name
:return: a dictionary containing all values for the accountPolicy
:rtype: dict
:raises: CommandExecutionError on user not found or any other unknown error
'''
cmd = 'pwpolicy -u {0} -getpolicy'.format(name)
try:
ret = salt.utils.mac_utils.execute_return_result(cmd)
except CommandExecutionError as exc:
if 'Error: user <{0}> not found'.format(name) in exc.strerror:
raise CommandExecutionError('User not found: {0}'.format(name))
raise CommandExecutionError('Unknown error: {0}'.format(exc.strerror))
try:
policy_list = ret.split('\n')[1].split(' ')
policy_dict = {}
for policy in policy_list:
if '=' in policy:
key, value = policy.split('=')
policy_dict[key] = value
return policy_dict
except IndexError:
return {}
def _set_account_policy(name, policy):
'''
Set a value in the user accountPolicy. For use by this module only
:param str name: The user name
:param str policy: The policy to apply
:return: True if success, otherwise False
:rtype: bool
:raises: CommandExecutionError on user not found or any other unknown error
'''
cmd = 'pwpolicy -u {0} -setpolicy "{1}"'.format(name, policy)
try:
return salt.utils.mac_utils.execute_return_success(cmd)
except CommandExecutionError as exc:
if 'Error: user <{0}> not found'.format(name) in exc.strerror:
raise CommandExecutionError('User not found: {0}'.format(name))
raise CommandExecutionError('Unknown error: {0}'.format(exc.strerror))
def _get_account_policy_data_value(name, key):
'''
Return the value for a key in the accountPolicy section of the user's plist
file. For use by this module only
:param str name: The username
:param str key: The accountPolicy key
:return: The value contained within the key
:rtype: str
:raises: CommandExecutionError on user not found or any other unknown error
'''
cmd = 'dscl . -readpl /Users/{0} accountPolicyData {1}'.format(name, key)
try:
ret = salt.utils.mac_utils.execute_return_result(cmd)
except CommandExecutionError as exc:
if 'eDSUnknownNodeName' in exc.strerror:
raise CommandExecutionError('User not found: {0}'.format(name))
raise CommandExecutionError('Unknown error: {0}'.format(exc.strerror))
return ret
def _convert_to_datetime(unix_timestamp):
'''
Converts a unix timestamp to a human readable date/time
:param float unix_timestamp: A unix timestamp
:return: A date/time in the format YYYY-mm-dd HH:MM:SS
:rtype: str
'''
try:
unix_timestamp = float(unix_timestamp)
return datetime.fromtimestamp(unix_timestamp).strftime('%Y-%m-%d %H:%M:%S')
except (ValueError, TypeError):
return 'Invalid Timestamp'
def info(name):
'''
Return information for the specified user
:param str name: The username
:return: A dictionary containing the user's shadow information
:rtype: dict
CLI Example:
.. code-block:: bash
salt '*' shadow.info admin
'''
try:
data = pwd.getpwnam(name)
return {'name': data.pw_name,
'passwd': data.pw_passwd,
'account_created': get_account_created(name),
'login_failed_count': get_login_failed_count(name),
'login_failed_last': get_login_failed_last(name),
'lstchg': get_last_change(name),
'max': get_maxdays(name),
'expire': get_expire(name),
'change': get_change(name),
'min': 'Unavailable',
'warn': 'Unavailable',
'inact': 'Unavailable'}
except KeyError:
log.debug('User not found: %s', name)
return {'name': '',
'passwd': '',
'account_created': '',
'login_failed_count': '',
'login_failed_last': '',
'lstchg': '',
'max': '',
'expire': '',
'change': '',
'min': '',
'warn': '',
'inact': ''}
def get_last_change(name):
'''
Get the date/time the account was changed
:param str name: The username of the account
:return: The date/time the account was modified (yyyy-mm-dd hh:mm:ss)
:rtype: str
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.get_last_change admin
'''
ret = _get_account_policy_data_value(name, 'passwordLastSetTime')
unix_timestamp = salt.utils.mac_utils.parse_return(ret)
date_text = _convert_to_datetime(unix_timestamp)
return date_text
def get_login_failed_count(name):
'''
Get the the number of failed login attempts
:param str name: The username of the account
:return: The number of failed login attempts
:rtype: int
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.get_login_failed_count admin
'''
ret = _get_account_policy_data_value(name, 'failedLoginCount')
return salt.utils.mac_utils.parse_return(ret)
def get_login_failed_last(name):
'''
Get the date/time of the last failed login attempt
:param str name: The username of the account
:return: The date/time of the last failed login attempt on this account
(yyyy-mm-dd hh:mm:ss)
:rtype: str
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.get_login_failed_last admin
'''
ret = _get_account_policy_data_value(name, 'failedLoginTimestamp')
unix_timestamp = salt.utils.mac_utils.parse_return(ret)
date_text = _convert_to_datetime(unix_timestamp)
return date_text
def set_maxdays(name, days):
'''
Set the maximum age of the password in days
:param str name: The username of the account
:param int days: The maximum age of the account in days
:return: True if successful, False if not
:rtype: bool
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.set_maxdays admin 90
'''
minutes = days * 24 * 60
_set_account_policy(
name, 'maxMinutesUntilChangePassword={0}'.format(minutes))
return get_maxdays(name) == days
def get_maxdays(name):
'''
Get the maximum age of the password
:param str name: The username of the account
:return: The maximum age of the password in days
:rtype: int
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.get_maxdays admin 90
'''
policies = _get_account_policy(name)
if 'maxMinutesUntilChangePassword' in policies:
max_minutes = policies['maxMinutesUntilChangePassword']
return int(max_minutes) / 24 / 60
return 0
def set_mindays(name, days):
'''
Set the minimum password age in days. Not available in macOS.
:param str name: The user name
:param int days: The number of days
:return: Will always return False until macOS supports this feature.
:rtype: bool
CLI Example:
.. code-block:: bash
salt '*' shadow.set_mindays admin 90
'''
return False
def set_inactdays(name, days):
'''
Set the number if inactive days before the account is locked. Not available
in macOS
:param str name: The user name
:param int days: The number of days
:return: Will always return False until macOS supports this feature.
:rtype: bool
CLI Example:
.. code-block:: bash
salt '*' shadow.set_inactdays admin 90
'''
return False
def set_warndays(name, days):
'''
Set the number of days before the password expires that the user will start
to see a warning. Not available in macOS
:param str name: The user name
:param int days: The number of days
:return: Will always return False until macOS supports this feature.
:rtype: bool
CLI Example:
.. code-block:: bash
salt '*' shadow.set_warndays admin 90
'''
return False
def set_change(name, date):
'''
Sets the date on which the password expires. The user will be required to
change their password. Format is mm/dd/yyyy
:param str name: The name of the user account
:param date date: The date the password will expire. Must be in mm/dd/yyyy
format.
:return: True if successful, otherwise False
:rtype: bool
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.set_change username 09/21/2016
'''
_set_account_policy(
name, 'usingExpirationDate=1 expirationDateGMT={0}'.format(date))
return get_change(name) == date
def get_change(name):
'''
Gets the date on which the password expires
:param str name: The name of the user account
:return: The date the password will expire
:rtype: str
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.get_change username
'''
policies = _get_account_policy(name)
if 'expirationDateGMT' in policies:
return policies['expirationDateGMT']
return 'Value not set'
def set_expire(name, date):
'''
Sets the date on which the account expires. The user will not be able to
login after this date. Date format is mm/dd/yyyy
:param str name: The name of the user account
:param datetime date: The date the account will expire. Format must be
mm/dd/yyyy.
:return: True if successful, False if not
:rtype: bool
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.set_expire username 07/23/2015
'''
_set_account_policy(
name, 'usingHardExpirationDate=1 hardExpireDateGMT={0}'.format(date))
return get_expire(name) == date
def get_expire(name):
'''
Gets the date on which the account expires
:param str name: The name of the user account
:return: The date the account expires
:rtype: str
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.get_expire username
'''
policies = _get_account_policy(name)
if 'hardExpireDateGMT' in policies:
return policies['hardExpireDateGMT']
return 'Value not set'
def del_password(name):
'''
Deletes the account password
:param str name: The user name of the account
:return: True if successful, otherwise False
:rtype: bool
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.del_password username
'''
# This removes the password
cmd = "dscl . -passwd /Users/{0} ''".format(name)
try:
salt.utils.mac_utils.execute_return_success(cmd)
except CommandExecutionError as exc:
if 'eDSUnknownNodeName' in exc.strerror:
raise CommandExecutionError('User not found: {0}'.format(name))
raise CommandExecutionError('Unknown error: {0}'.format(exc.strerror))
# This is so it looks right in shadow.info
cmd = "dscl . -create /Users/{0} Password '*'".format(name)
salt.utils.mac_utils.execute_return_success(cmd)
return info(name)['passwd'] == '*'
def set_password(name, password):
'''
Set the password for a named user (insecure, the password will be in the
process list while the command is running)
:param str name: The name of the local user, which is assumed to be in the
local directory service
:param str password: The plaintext password to set
:return: True if successful, otherwise False
:rtype: bool
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' mac_shadow.set_password macuser macpassword
'''
cmd = "dscl . -passwd /Users/{0} '{1}'".format(name, password)
try:
salt.utils.mac_utils.execute_return_success(cmd)
except CommandExecutionError as exc:
if 'eDSUnknownNodeName' in exc.strerror:
raise CommandExecutionError('User not found: {0}'.format(name))
raise CommandExecutionError('Unknown error: {0}'.format(exc.strerror))
return True
|
saltstack/salt
|
salt/modules/mac_shadow.py
|
get_login_failed_count
|
python
|
def get_login_failed_count(name):
'''
Get the the number of failed login attempts
:param str name: The username of the account
:return: The number of failed login attempts
:rtype: int
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.get_login_failed_count admin
'''
ret = _get_account_policy_data_value(name, 'failedLoginCount')
return salt.utils.mac_utils.parse_return(ret)
|
Get the the number of failed login attempts
:param str name: The username of the account
:return: The number of failed login attempts
:rtype: int
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.get_login_failed_count admin
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_shadow.py#L238-L257
|
[
"def parse_return(data):\n '''\n Returns the data portion of a string that is colon separated.\n\n :param str data: The string that contains the data to be parsed. Usually the\n standard out from a command\n\n For example:\n ``Time Zone: America/Denver``\n will return:\n ``America/Denver``\n '''\n\n if ': ' in data:\n return data.split(': ')[1]\n if ':\\n' in data:\n return data.split(':\\n')[1]\n else:\n return data\n",
"def _get_account_policy_data_value(name, key):\n '''\n Return the value for a key in the accountPolicy section of the user's plist\n file. For use by this module only\n\n :param str name: The username\n :param str key: The accountPolicy key\n\n :return: The value contained within the key\n :rtype: str\n\n :raises: CommandExecutionError on user not found or any other unknown error\n '''\n cmd = 'dscl . -readpl /Users/{0} accountPolicyData {1}'.format(name, key)\n try:\n ret = salt.utils.mac_utils.execute_return_result(cmd)\n except CommandExecutionError as exc:\n if 'eDSUnknownNodeName' in exc.strerror:\n raise CommandExecutionError('User not found: {0}'.format(name))\n raise CommandExecutionError('Unknown error: {0}'.format(exc.strerror))\n\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Manage macOS local directory passwords and policies
.. versionadded:: 2016.3.0
Note that it is usually better to apply password policies through the creation
of a configuration profile.
'''
# Authentication concepts reference:
# https://developer.apple.com/library/mac/documentation/Networking/Conceptual/Open_Directory/openDirectoryConcepts/openDirectoryConcepts.html#//apple_ref/doc/uid/TP40000917-CH3-CIFCAIBB
from __future__ import absolute_import, unicode_literals, print_function
from datetime import datetime
try:
import pwd
HAS_PWD = True
except ImportError:
HAS_PWD = False
# Import salt libs
import logging
import salt.utils.mac_utils
import salt.utils.platform
from salt.exceptions import CommandExecutionError
log = logging.getLogger(__name__) # Start logging
__virtualname__ = 'shadow'
def __virtual__():
# Is this macOS?
if not salt.utils.platform.is_darwin():
return False, 'Not macOS'
if HAS_PWD:
return __virtualname__
else:
return (False, 'The pwd module failed to load.')
def _get_account_policy(name):
'''
Get the entire accountPolicy and return it as a dictionary. For use by this
module only
:param str name: The user name
:return: a dictionary containing all values for the accountPolicy
:rtype: dict
:raises: CommandExecutionError on user not found or any other unknown error
'''
cmd = 'pwpolicy -u {0} -getpolicy'.format(name)
try:
ret = salt.utils.mac_utils.execute_return_result(cmd)
except CommandExecutionError as exc:
if 'Error: user <{0}> not found'.format(name) in exc.strerror:
raise CommandExecutionError('User not found: {0}'.format(name))
raise CommandExecutionError('Unknown error: {0}'.format(exc.strerror))
try:
policy_list = ret.split('\n')[1].split(' ')
policy_dict = {}
for policy in policy_list:
if '=' in policy:
key, value = policy.split('=')
policy_dict[key] = value
return policy_dict
except IndexError:
return {}
def _set_account_policy(name, policy):
'''
Set a value in the user accountPolicy. For use by this module only
:param str name: The user name
:param str policy: The policy to apply
:return: True if success, otherwise False
:rtype: bool
:raises: CommandExecutionError on user not found or any other unknown error
'''
cmd = 'pwpolicy -u {0} -setpolicy "{1}"'.format(name, policy)
try:
return salt.utils.mac_utils.execute_return_success(cmd)
except CommandExecutionError as exc:
if 'Error: user <{0}> not found'.format(name) in exc.strerror:
raise CommandExecutionError('User not found: {0}'.format(name))
raise CommandExecutionError('Unknown error: {0}'.format(exc.strerror))
def _get_account_policy_data_value(name, key):
'''
Return the value for a key in the accountPolicy section of the user's plist
file. For use by this module only
:param str name: The username
:param str key: The accountPolicy key
:return: The value contained within the key
:rtype: str
:raises: CommandExecutionError on user not found or any other unknown error
'''
cmd = 'dscl . -readpl /Users/{0} accountPolicyData {1}'.format(name, key)
try:
ret = salt.utils.mac_utils.execute_return_result(cmd)
except CommandExecutionError as exc:
if 'eDSUnknownNodeName' in exc.strerror:
raise CommandExecutionError('User not found: {0}'.format(name))
raise CommandExecutionError('Unknown error: {0}'.format(exc.strerror))
return ret
def _convert_to_datetime(unix_timestamp):
'''
Converts a unix timestamp to a human readable date/time
:param float unix_timestamp: A unix timestamp
:return: A date/time in the format YYYY-mm-dd HH:MM:SS
:rtype: str
'''
try:
unix_timestamp = float(unix_timestamp)
return datetime.fromtimestamp(unix_timestamp).strftime('%Y-%m-%d %H:%M:%S')
except (ValueError, TypeError):
return 'Invalid Timestamp'
def info(name):
'''
Return information for the specified user
:param str name: The username
:return: A dictionary containing the user's shadow information
:rtype: dict
CLI Example:
.. code-block:: bash
salt '*' shadow.info admin
'''
try:
data = pwd.getpwnam(name)
return {'name': data.pw_name,
'passwd': data.pw_passwd,
'account_created': get_account_created(name),
'login_failed_count': get_login_failed_count(name),
'login_failed_last': get_login_failed_last(name),
'lstchg': get_last_change(name),
'max': get_maxdays(name),
'expire': get_expire(name),
'change': get_change(name),
'min': 'Unavailable',
'warn': 'Unavailable',
'inact': 'Unavailable'}
except KeyError:
log.debug('User not found: %s', name)
return {'name': '',
'passwd': '',
'account_created': '',
'login_failed_count': '',
'login_failed_last': '',
'lstchg': '',
'max': '',
'expire': '',
'change': '',
'min': '',
'warn': '',
'inact': ''}
def get_account_created(name):
'''
Get the date/time the account was created
:param str name: The username of the account
:return: The date/time the account was created (yyyy-mm-dd hh:mm:ss)
:rtype: str
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.get_account_created admin
'''
ret = _get_account_policy_data_value(name, 'creationTime')
unix_timestamp = salt.utils.mac_utils.parse_return(ret)
date_text = _convert_to_datetime(unix_timestamp)
return date_text
def get_last_change(name):
'''
Get the date/time the account was changed
:param str name: The username of the account
:return: The date/time the account was modified (yyyy-mm-dd hh:mm:ss)
:rtype: str
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.get_last_change admin
'''
ret = _get_account_policy_data_value(name, 'passwordLastSetTime')
unix_timestamp = salt.utils.mac_utils.parse_return(ret)
date_text = _convert_to_datetime(unix_timestamp)
return date_text
def get_login_failed_last(name):
'''
Get the date/time of the last failed login attempt
:param str name: The username of the account
:return: The date/time of the last failed login attempt on this account
(yyyy-mm-dd hh:mm:ss)
:rtype: str
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.get_login_failed_last admin
'''
ret = _get_account_policy_data_value(name, 'failedLoginTimestamp')
unix_timestamp = salt.utils.mac_utils.parse_return(ret)
date_text = _convert_to_datetime(unix_timestamp)
return date_text
def set_maxdays(name, days):
'''
Set the maximum age of the password in days
:param str name: The username of the account
:param int days: The maximum age of the account in days
:return: True if successful, False if not
:rtype: bool
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.set_maxdays admin 90
'''
minutes = days * 24 * 60
_set_account_policy(
name, 'maxMinutesUntilChangePassword={0}'.format(minutes))
return get_maxdays(name) == days
def get_maxdays(name):
'''
Get the maximum age of the password
:param str name: The username of the account
:return: The maximum age of the password in days
:rtype: int
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.get_maxdays admin 90
'''
policies = _get_account_policy(name)
if 'maxMinutesUntilChangePassword' in policies:
max_minutes = policies['maxMinutesUntilChangePassword']
return int(max_minutes) / 24 / 60
return 0
def set_mindays(name, days):
'''
Set the minimum password age in days. Not available in macOS.
:param str name: The user name
:param int days: The number of days
:return: Will always return False until macOS supports this feature.
:rtype: bool
CLI Example:
.. code-block:: bash
salt '*' shadow.set_mindays admin 90
'''
return False
def set_inactdays(name, days):
'''
Set the number if inactive days before the account is locked. Not available
in macOS
:param str name: The user name
:param int days: The number of days
:return: Will always return False until macOS supports this feature.
:rtype: bool
CLI Example:
.. code-block:: bash
salt '*' shadow.set_inactdays admin 90
'''
return False
def set_warndays(name, days):
'''
Set the number of days before the password expires that the user will start
to see a warning. Not available in macOS
:param str name: The user name
:param int days: The number of days
:return: Will always return False until macOS supports this feature.
:rtype: bool
CLI Example:
.. code-block:: bash
salt '*' shadow.set_warndays admin 90
'''
return False
def set_change(name, date):
'''
Sets the date on which the password expires. The user will be required to
change their password. Format is mm/dd/yyyy
:param str name: The name of the user account
:param date date: The date the password will expire. Must be in mm/dd/yyyy
format.
:return: True if successful, otherwise False
:rtype: bool
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.set_change username 09/21/2016
'''
_set_account_policy(
name, 'usingExpirationDate=1 expirationDateGMT={0}'.format(date))
return get_change(name) == date
def get_change(name):
'''
Gets the date on which the password expires
:param str name: The name of the user account
:return: The date the password will expire
:rtype: str
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.get_change username
'''
policies = _get_account_policy(name)
if 'expirationDateGMT' in policies:
return policies['expirationDateGMT']
return 'Value not set'
def set_expire(name, date):
'''
Sets the date on which the account expires. The user will not be able to
login after this date. Date format is mm/dd/yyyy
:param str name: The name of the user account
:param datetime date: The date the account will expire. Format must be
mm/dd/yyyy.
:return: True if successful, False if not
:rtype: bool
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.set_expire username 07/23/2015
'''
_set_account_policy(
name, 'usingHardExpirationDate=1 hardExpireDateGMT={0}'.format(date))
return get_expire(name) == date
def get_expire(name):
'''
Gets the date on which the account expires
:param str name: The name of the user account
:return: The date the account expires
:rtype: str
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.get_expire username
'''
policies = _get_account_policy(name)
if 'hardExpireDateGMT' in policies:
return policies['hardExpireDateGMT']
return 'Value not set'
def del_password(name):
'''
Deletes the account password
:param str name: The user name of the account
:return: True if successful, otherwise False
:rtype: bool
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.del_password username
'''
# This removes the password
cmd = "dscl . -passwd /Users/{0} ''".format(name)
try:
salt.utils.mac_utils.execute_return_success(cmd)
except CommandExecutionError as exc:
if 'eDSUnknownNodeName' in exc.strerror:
raise CommandExecutionError('User not found: {0}'.format(name))
raise CommandExecutionError('Unknown error: {0}'.format(exc.strerror))
# This is so it looks right in shadow.info
cmd = "dscl . -create /Users/{0} Password '*'".format(name)
salt.utils.mac_utils.execute_return_success(cmd)
return info(name)['passwd'] == '*'
def set_password(name, password):
'''
Set the password for a named user (insecure, the password will be in the
process list while the command is running)
:param str name: The name of the local user, which is assumed to be in the
local directory service
:param str password: The plaintext password to set
:return: True if successful, otherwise False
:rtype: bool
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' mac_shadow.set_password macuser macpassword
'''
cmd = "dscl . -passwd /Users/{0} '{1}'".format(name, password)
try:
salt.utils.mac_utils.execute_return_success(cmd)
except CommandExecutionError as exc:
if 'eDSUnknownNodeName' in exc.strerror:
raise CommandExecutionError('User not found: {0}'.format(name))
raise CommandExecutionError('Unknown error: {0}'.format(exc.strerror))
return True
|
saltstack/salt
|
salt/modules/mac_shadow.py
|
set_maxdays
|
python
|
def set_maxdays(name, days):
'''
Set the maximum age of the password in days
:param str name: The username of the account
:param int days: The maximum age of the account in days
:return: True if successful, False if not
:rtype: bool
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.set_maxdays admin 90
'''
minutes = days * 24 * 60
_set_account_policy(
name, 'maxMinutesUntilChangePassword={0}'.format(minutes))
return get_maxdays(name) == days
|
Set the maximum age of the password in days
:param str name: The username of the account
:param int days: The maximum age of the account in days
:return: True if successful, False if not
:rtype: bool
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.set_maxdays admin 90
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_shadow.py#L287-L311
|
[
"def _set_account_policy(name, policy):\n '''\n Set a value in the user accountPolicy. For use by this module only\n\n :param str name: The user name\n :param str policy: The policy to apply\n\n :return: True if success, otherwise False\n :rtype: bool\n\n :raises: CommandExecutionError on user not found or any other unknown error\n '''\n cmd = 'pwpolicy -u {0} -setpolicy \"{1}\"'.format(name, policy)\n\n try:\n return salt.utils.mac_utils.execute_return_success(cmd)\n except CommandExecutionError as exc:\n if 'Error: user <{0}> not found'.format(name) in exc.strerror:\n raise CommandExecutionError('User not found: {0}'.format(name))\n raise CommandExecutionError('Unknown error: {0}'.format(exc.strerror))\n",
"def get_maxdays(name):\n '''\n Get the maximum age of the password\n\n :param str name: The username of the account\n\n :return: The maximum age of the password in days\n :rtype: int\n\n :raises: CommandExecutionError on user not found or any other unknown error\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' shadow.get_maxdays admin 90\n '''\n policies = _get_account_policy(name)\n\n if 'maxMinutesUntilChangePassword' in policies:\n max_minutes = policies['maxMinutesUntilChangePassword']\n return int(max_minutes) / 24 / 60\n\n return 0\n"
] |
# -*- coding: utf-8 -*-
'''
Manage macOS local directory passwords and policies
.. versionadded:: 2016.3.0
Note that it is usually better to apply password policies through the creation
of a configuration profile.
'''
# Authentication concepts reference:
# https://developer.apple.com/library/mac/documentation/Networking/Conceptual/Open_Directory/openDirectoryConcepts/openDirectoryConcepts.html#//apple_ref/doc/uid/TP40000917-CH3-CIFCAIBB
from __future__ import absolute_import, unicode_literals, print_function
from datetime import datetime
try:
import pwd
HAS_PWD = True
except ImportError:
HAS_PWD = False
# Import salt libs
import logging
import salt.utils.mac_utils
import salt.utils.platform
from salt.exceptions import CommandExecutionError
log = logging.getLogger(__name__) # Start logging
__virtualname__ = 'shadow'
def __virtual__():
# Is this macOS?
if not salt.utils.platform.is_darwin():
return False, 'Not macOS'
if HAS_PWD:
return __virtualname__
else:
return (False, 'The pwd module failed to load.')
def _get_account_policy(name):
'''
Get the entire accountPolicy and return it as a dictionary. For use by this
module only
:param str name: The user name
:return: a dictionary containing all values for the accountPolicy
:rtype: dict
:raises: CommandExecutionError on user not found or any other unknown error
'''
cmd = 'pwpolicy -u {0} -getpolicy'.format(name)
try:
ret = salt.utils.mac_utils.execute_return_result(cmd)
except CommandExecutionError as exc:
if 'Error: user <{0}> not found'.format(name) in exc.strerror:
raise CommandExecutionError('User not found: {0}'.format(name))
raise CommandExecutionError('Unknown error: {0}'.format(exc.strerror))
try:
policy_list = ret.split('\n')[1].split(' ')
policy_dict = {}
for policy in policy_list:
if '=' in policy:
key, value = policy.split('=')
policy_dict[key] = value
return policy_dict
except IndexError:
return {}
def _set_account_policy(name, policy):
'''
Set a value in the user accountPolicy. For use by this module only
:param str name: The user name
:param str policy: The policy to apply
:return: True if success, otherwise False
:rtype: bool
:raises: CommandExecutionError on user not found or any other unknown error
'''
cmd = 'pwpolicy -u {0} -setpolicy "{1}"'.format(name, policy)
try:
return salt.utils.mac_utils.execute_return_success(cmd)
except CommandExecutionError as exc:
if 'Error: user <{0}> not found'.format(name) in exc.strerror:
raise CommandExecutionError('User not found: {0}'.format(name))
raise CommandExecutionError('Unknown error: {0}'.format(exc.strerror))
def _get_account_policy_data_value(name, key):
'''
Return the value for a key in the accountPolicy section of the user's plist
file. For use by this module only
:param str name: The username
:param str key: The accountPolicy key
:return: The value contained within the key
:rtype: str
:raises: CommandExecutionError on user not found or any other unknown error
'''
cmd = 'dscl . -readpl /Users/{0} accountPolicyData {1}'.format(name, key)
try:
ret = salt.utils.mac_utils.execute_return_result(cmd)
except CommandExecutionError as exc:
if 'eDSUnknownNodeName' in exc.strerror:
raise CommandExecutionError('User not found: {0}'.format(name))
raise CommandExecutionError('Unknown error: {0}'.format(exc.strerror))
return ret
def _convert_to_datetime(unix_timestamp):
'''
Converts a unix timestamp to a human readable date/time
:param float unix_timestamp: A unix timestamp
:return: A date/time in the format YYYY-mm-dd HH:MM:SS
:rtype: str
'''
try:
unix_timestamp = float(unix_timestamp)
return datetime.fromtimestamp(unix_timestamp).strftime('%Y-%m-%d %H:%M:%S')
except (ValueError, TypeError):
return 'Invalid Timestamp'
def info(name):
'''
Return information for the specified user
:param str name: The username
:return: A dictionary containing the user's shadow information
:rtype: dict
CLI Example:
.. code-block:: bash
salt '*' shadow.info admin
'''
try:
data = pwd.getpwnam(name)
return {'name': data.pw_name,
'passwd': data.pw_passwd,
'account_created': get_account_created(name),
'login_failed_count': get_login_failed_count(name),
'login_failed_last': get_login_failed_last(name),
'lstchg': get_last_change(name),
'max': get_maxdays(name),
'expire': get_expire(name),
'change': get_change(name),
'min': 'Unavailable',
'warn': 'Unavailable',
'inact': 'Unavailable'}
except KeyError:
log.debug('User not found: %s', name)
return {'name': '',
'passwd': '',
'account_created': '',
'login_failed_count': '',
'login_failed_last': '',
'lstchg': '',
'max': '',
'expire': '',
'change': '',
'min': '',
'warn': '',
'inact': ''}
def get_account_created(name):
'''
Get the date/time the account was created
:param str name: The username of the account
:return: The date/time the account was created (yyyy-mm-dd hh:mm:ss)
:rtype: str
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.get_account_created admin
'''
ret = _get_account_policy_data_value(name, 'creationTime')
unix_timestamp = salt.utils.mac_utils.parse_return(ret)
date_text = _convert_to_datetime(unix_timestamp)
return date_text
def get_last_change(name):
'''
Get the date/time the account was changed
:param str name: The username of the account
:return: The date/time the account was modified (yyyy-mm-dd hh:mm:ss)
:rtype: str
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.get_last_change admin
'''
ret = _get_account_policy_data_value(name, 'passwordLastSetTime')
unix_timestamp = salt.utils.mac_utils.parse_return(ret)
date_text = _convert_to_datetime(unix_timestamp)
return date_text
def get_login_failed_count(name):
'''
Get the the number of failed login attempts
:param str name: The username of the account
:return: The number of failed login attempts
:rtype: int
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.get_login_failed_count admin
'''
ret = _get_account_policy_data_value(name, 'failedLoginCount')
return salt.utils.mac_utils.parse_return(ret)
def get_login_failed_last(name):
'''
Get the date/time of the last failed login attempt
:param str name: The username of the account
:return: The date/time of the last failed login attempt on this account
(yyyy-mm-dd hh:mm:ss)
:rtype: str
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.get_login_failed_last admin
'''
ret = _get_account_policy_data_value(name, 'failedLoginTimestamp')
unix_timestamp = salt.utils.mac_utils.parse_return(ret)
date_text = _convert_to_datetime(unix_timestamp)
return date_text
def get_maxdays(name):
'''
Get the maximum age of the password
:param str name: The username of the account
:return: The maximum age of the password in days
:rtype: int
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.get_maxdays admin 90
'''
policies = _get_account_policy(name)
if 'maxMinutesUntilChangePassword' in policies:
max_minutes = policies['maxMinutesUntilChangePassword']
return int(max_minutes) / 24 / 60
return 0
def set_mindays(name, days):
'''
Set the minimum password age in days. Not available in macOS.
:param str name: The user name
:param int days: The number of days
:return: Will always return False until macOS supports this feature.
:rtype: bool
CLI Example:
.. code-block:: bash
salt '*' shadow.set_mindays admin 90
'''
return False
def set_inactdays(name, days):
'''
Set the number if inactive days before the account is locked. Not available
in macOS
:param str name: The user name
:param int days: The number of days
:return: Will always return False until macOS supports this feature.
:rtype: bool
CLI Example:
.. code-block:: bash
salt '*' shadow.set_inactdays admin 90
'''
return False
def set_warndays(name, days):
'''
Set the number of days before the password expires that the user will start
to see a warning. Not available in macOS
:param str name: The user name
:param int days: The number of days
:return: Will always return False until macOS supports this feature.
:rtype: bool
CLI Example:
.. code-block:: bash
salt '*' shadow.set_warndays admin 90
'''
return False
def set_change(name, date):
'''
Sets the date on which the password expires. The user will be required to
change their password. Format is mm/dd/yyyy
:param str name: The name of the user account
:param date date: The date the password will expire. Must be in mm/dd/yyyy
format.
:return: True if successful, otherwise False
:rtype: bool
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.set_change username 09/21/2016
'''
_set_account_policy(
name, 'usingExpirationDate=1 expirationDateGMT={0}'.format(date))
return get_change(name) == date
def get_change(name):
'''
Gets the date on which the password expires
:param str name: The name of the user account
:return: The date the password will expire
:rtype: str
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.get_change username
'''
policies = _get_account_policy(name)
if 'expirationDateGMT' in policies:
return policies['expirationDateGMT']
return 'Value not set'
def set_expire(name, date):
'''
Sets the date on which the account expires. The user will not be able to
login after this date. Date format is mm/dd/yyyy
:param str name: The name of the user account
:param datetime date: The date the account will expire. Format must be
mm/dd/yyyy.
:return: True if successful, False if not
:rtype: bool
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.set_expire username 07/23/2015
'''
_set_account_policy(
name, 'usingHardExpirationDate=1 hardExpireDateGMT={0}'.format(date))
return get_expire(name) == date
def get_expire(name):
'''
Gets the date on which the account expires
:param str name: The name of the user account
:return: The date the account expires
:rtype: str
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.get_expire username
'''
policies = _get_account_policy(name)
if 'hardExpireDateGMT' in policies:
return policies['hardExpireDateGMT']
return 'Value not set'
def del_password(name):
'''
Deletes the account password
:param str name: The user name of the account
:return: True if successful, otherwise False
:rtype: bool
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.del_password username
'''
# This removes the password
cmd = "dscl . -passwd /Users/{0} ''".format(name)
try:
salt.utils.mac_utils.execute_return_success(cmd)
except CommandExecutionError as exc:
if 'eDSUnknownNodeName' in exc.strerror:
raise CommandExecutionError('User not found: {0}'.format(name))
raise CommandExecutionError('Unknown error: {0}'.format(exc.strerror))
# This is so it looks right in shadow.info
cmd = "dscl . -create /Users/{0} Password '*'".format(name)
salt.utils.mac_utils.execute_return_success(cmd)
return info(name)['passwd'] == '*'
def set_password(name, password):
'''
Set the password for a named user (insecure, the password will be in the
process list while the command is running)
:param str name: The name of the local user, which is assumed to be in the
local directory service
:param str password: The plaintext password to set
:return: True if successful, otherwise False
:rtype: bool
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' mac_shadow.set_password macuser macpassword
'''
cmd = "dscl . -passwd /Users/{0} '{1}'".format(name, password)
try:
salt.utils.mac_utils.execute_return_success(cmd)
except CommandExecutionError as exc:
if 'eDSUnknownNodeName' in exc.strerror:
raise CommandExecutionError('User not found: {0}'.format(name))
raise CommandExecutionError('Unknown error: {0}'.format(exc.strerror))
return True
|
saltstack/salt
|
salt/modules/mac_shadow.py
|
get_maxdays
|
python
|
def get_maxdays(name):
'''
Get the maximum age of the password
:param str name: The username of the account
:return: The maximum age of the password in days
:rtype: int
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.get_maxdays admin 90
'''
policies = _get_account_policy(name)
if 'maxMinutesUntilChangePassword' in policies:
max_minutes = policies['maxMinutesUntilChangePassword']
return int(max_minutes) / 24 / 60
return 0
|
Get the maximum age of the password
:param str name: The username of the account
:return: The maximum age of the password in days
:rtype: int
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.get_maxdays admin 90
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_shadow.py#L314-L337
|
[
"def _get_account_policy(name):\n '''\n Get the entire accountPolicy and return it as a dictionary. For use by this\n module only\n\n :param str name: The user name\n\n :return: a dictionary containing all values for the accountPolicy\n :rtype: dict\n\n :raises: CommandExecutionError on user not found or any other unknown error\n '''\n\n cmd = 'pwpolicy -u {0} -getpolicy'.format(name)\n try:\n ret = salt.utils.mac_utils.execute_return_result(cmd)\n except CommandExecutionError as exc:\n if 'Error: user <{0}> not found'.format(name) in exc.strerror:\n raise CommandExecutionError('User not found: {0}'.format(name))\n raise CommandExecutionError('Unknown error: {0}'.format(exc.strerror))\n\n try:\n policy_list = ret.split('\\n')[1].split(' ')\n policy_dict = {}\n for policy in policy_list:\n if '=' in policy:\n key, value = policy.split('=')\n policy_dict[key] = value\n return policy_dict\n except IndexError:\n return {}\n"
] |
# -*- coding: utf-8 -*-
'''
Manage macOS local directory passwords and policies
.. versionadded:: 2016.3.0
Note that it is usually better to apply password policies through the creation
of a configuration profile.
'''
# Authentication concepts reference:
# https://developer.apple.com/library/mac/documentation/Networking/Conceptual/Open_Directory/openDirectoryConcepts/openDirectoryConcepts.html#//apple_ref/doc/uid/TP40000917-CH3-CIFCAIBB
from __future__ import absolute_import, unicode_literals, print_function
from datetime import datetime
try:
import pwd
HAS_PWD = True
except ImportError:
HAS_PWD = False
# Import salt libs
import logging
import salt.utils.mac_utils
import salt.utils.platform
from salt.exceptions import CommandExecutionError
log = logging.getLogger(__name__) # Start logging
__virtualname__ = 'shadow'
def __virtual__():
# Is this macOS?
if not salt.utils.platform.is_darwin():
return False, 'Not macOS'
if HAS_PWD:
return __virtualname__
else:
return (False, 'The pwd module failed to load.')
def _get_account_policy(name):
'''
Get the entire accountPolicy and return it as a dictionary. For use by this
module only
:param str name: The user name
:return: a dictionary containing all values for the accountPolicy
:rtype: dict
:raises: CommandExecutionError on user not found or any other unknown error
'''
cmd = 'pwpolicy -u {0} -getpolicy'.format(name)
try:
ret = salt.utils.mac_utils.execute_return_result(cmd)
except CommandExecutionError as exc:
if 'Error: user <{0}> not found'.format(name) in exc.strerror:
raise CommandExecutionError('User not found: {0}'.format(name))
raise CommandExecutionError('Unknown error: {0}'.format(exc.strerror))
try:
policy_list = ret.split('\n')[1].split(' ')
policy_dict = {}
for policy in policy_list:
if '=' in policy:
key, value = policy.split('=')
policy_dict[key] = value
return policy_dict
except IndexError:
return {}
def _set_account_policy(name, policy):
'''
Set a value in the user accountPolicy. For use by this module only
:param str name: The user name
:param str policy: The policy to apply
:return: True if success, otherwise False
:rtype: bool
:raises: CommandExecutionError on user not found or any other unknown error
'''
cmd = 'pwpolicy -u {0} -setpolicy "{1}"'.format(name, policy)
try:
return salt.utils.mac_utils.execute_return_success(cmd)
except CommandExecutionError as exc:
if 'Error: user <{0}> not found'.format(name) in exc.strerror:
raise CommandExecutionError('User not found: {0}'.format(name))
raise CommandExecutionError('Unknown error: {0}'.format(exc.strerror))
def _get_account_policy_data_value(name, key):
'''
Return the value for a key in the accountPolicy section of the user's plist
file. For use by this module only
:param str name: The username
:param str key: The accountPolicy key
:return: The value contained within the key
:rtype: str
:raises: CommandExecutionError on user not found or any other unknown error
'''
cmd = 'dscl . -readpl /Users/{0} accountPolicyData {1}'.format(name, key)
try:
ret = salt.utils.mac_utils.execute_return_result(cmd)
except CommandExecutionError as exc:
if 'eDSUnknownNodeName' in exc.strerror:
raise CommandExecutionError('User not found: {0}'.format(name))
raise CommandExecutionError('Unknown error: {0}'.format(exc.strerror))
return ret
def _convert_to_datetime(unix_timestamp):
'''
Converts a unix timestamp to a human readable date/time
:param float unix_timestamp: A unix timestamp
:return: A date/time in the format YYYY-mm-dd HH:MM:SS
:rtype: str
'''
try:
unix_timestamp = float(unix_timestamp)
return datetime.fromtimestamp(unix_timestamp).strftime('%Y-%m-%d %H:%M:%S')
except (ValueError, TypeError):
return 'Invalid Timestamp'
def info(name):
'''
Return information for the specified user
:param str name: The username
:return: A dictionary containing the user's shadow information
:rtype: dict
CLI Example:
.. code-block:: bash
salt '*' shadow.info admin
'''
try:
data = pwd.getpwnam(name)
return {'name': data.pw_name,
'passwd': data.pw_passwd,
'account_created': get_account_created(name),
'login_failed_count': get_login_failed_count(name),
'login_failed_last': get_login_failed_last(name),
'lstchg': get_last_change(name),
'max': get_maxdays(name),
'expire': get_expire(name),
'change': get_change(name),
'min': 'Unavailable',
'warn': 'Unavailable',
'inact': 'Unavailable'}
except KeyError:
log.debug('User not found: %s', name)
return {'name': '',
'passwd': '',
'account_created': '',
'login_failed_count': '',
'login_failed_last': '',
'lstchg': '',
'max': '',
'expire': '',
'change': '',
'min': '',
'warn': '',
'inact': ''}
def get_account_created(name):
'''
Get the date/time the account was created
:param str name: The username of the account
:return: The date/time the account was created (yyyy-mm-dd hh:mm:ss)
:rtype: str
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.get_account_created admin
'''
ret = _get_account_policy_data_value(name, 'creationTime')
unix_timestamp = salt.utils.mac_utils.parse_return(ret)
date_text = _convert_to_datetime(unix_timestamp)
return date_text
def get_last_change(name):
'''
Get the date/time the account was changed
:param str name: The username of the account
:return: The date/time the account was modified (yyyy-mm-dd hh:mm:ss)
:rtype: str
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.get_last_change admin
'''
ret = _get_account_policy_data_value(name, 'passwordLastSetTime')
unix_timestamp = salt.utils.mac_utils.parse_return(ret)
date_text = _convert_to_datetime(unix_timestamp)
return date_text
def get_login_failed_count(name):
'''
Get the the number of failed login attempts
:param str name: The username of the account
:return: The number of failed login attempts
:rtype: int
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.get_login_failed_count admin
'''
ret = _get_account_policy_data_value(name, 'failedLoginCount')
return salt.utils.mac_utils.parse_return(ret)
def get_login_failed_last(name):
'''
Get the date/time of the last failed login attempt
:param str name: The username of the account
:return: The date/time of the last failed login attempt on this account
(yyyy-mm-dd hh:mm:ss)
:rtype: str
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.get_login_failed_last admin
'''
ret = _get_account_policy_data_value(name, 'failedLoginTimestamp')
unix_timestamp = salt.utils.mac_utils.parse_return(ret)
date_text = _convert_to_datetime(unix_timestamp)
return date_text
def set_maxdays(name, days):
'''
Set the maximum age of the password in days
:param str name: The username of the account
:param int days: The maximum age of the account in days
:return: True if successful, False if not
:rtype: bool
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.set_maxdays admin 90
'''
minutes = days * 24 * 60
_set_account_policy(
name, 'maxMinutesUntilChangePassword={0}'.format(minutes))
return get_maxdays(name) == days
def set_mindays(name, days):
'''
Set the minimum password age in days. Not available in macOS.
:param str name: The user name
:param int days: The number of days
:return: Will always return False until macOS supports this feature.
:rtype: bool
CLI Example:
.. code-block:: bash
salt '*' shadow.set_mindays admin 90
'''
return False
def set_inactdays(name, days):
'''
Set the number if inactive days before the account is locked. Not available
in macOS
:param str name: The user name
:param int days: The number of days
:return: Will always return False until macOS supports this feature.
:rtype: bool
CLI Example:
.. code-block:: bash
salt '*' shadow.set_inactdays admin 90
'''
return False
def set_warndays(name, days):
'''
Set the number of days before the password expires that the user will start
to see a warning. Not available in macOS
:param str name: The user name
:param int days: The number of days
:return: Will always return False until macOS supports this feature.
:rtype: bool
CLI Example:
.. code-block:: bash
salt '*' shadow.set_warndays admin 90
'''
return False
def set_change(name, date):
'''
Sets the date on which the password expires. The user will be required to
change their password. Format is mm/dd/yyyy
:param str name: The name of the user account
:param date date: The date the password will expire. Must be in mm/dd/yyyy
format.
:return: True if successful, otherwise False
:rtype: bool
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.set_change username 09/21/2016
'''
_set_account_policy(
name, 'usingExpirationDate=1 expirationDateGMT={0}'.format(date))
return get_change(name) == date
def get_change(name):
'''
Gets the date on which the password expires
:param str name: The name of the user account
:return: The date the password will expire
:rtype: str
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.get_change username
'''
policies = _get_account_policy(name)
if 'expirationDateGMT' in policies:
return policies['expirationDateGMT']
return 'Value not set'
def set_expire(name, date):
'''
Sets the date on which the account expires. The user will not be able to
login after this date. Date format is mm/dd/yyyy
:param str name: The name of the user account
:param datetime date: The date the account will expire. Format must be
mm/dd/yyyy.
:return: True if successful, False if not
:rtype: bool
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.set_expire username 07/23/2015
'''
_set_account_policy(
name, 'usingHardExpirationDate=1 hardExpireDateGMT={0}'.format(date))
return get_expire(name) == date
def get_expire(name):
'''
Gets the date on which the account expires
:param str name: The name of the user account
:return: The date the account expires
:rtype: str
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.get_expire username
'''
policies = _get_account_policy(name)
if 'hardExpireDateGMT' in policies:
return policies['hardExpireDateGMT']
return 'Value not set'
def del_password(name):
'''
Deletes the account password
:param str name: The user name of the account
:return: True if successful, otherwise False
:rtype: bool
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.del_password username
'''
# This removes the password
cmd = "dscl . -passwd /Users/{0} ''".format(name)
try:
salt.utils.mac_utils.execute_return_success(cmd)
except CommandExecutionError as exc:
if 'eDSUnknownNodeName' in exc.strerror:
raise CommandExecutionError('User not found: {0}'.format(name))
raise CommandExecutionError('Unknown error: {0}'.format(exc.strerror))
# This is so it looks right in shadow.info
cmd = "dscl . -create /Users/{0} Password '*'".format(name)
salt.utils.mac_utils.execute_return_success(cmd)
return info(name)['passwd'] == '*'
def set_password(name, password):
'''
Set the password for a named user (insecure, the password will be in the
process list while the command is running)
:param str name: The name of the local user, which is assumed to be in the
local directory service
:param str password: The plaintext password to set
:return: True if successful, otherwise False
:rtype: bool
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' mac_shadow.set_password macuser macpassword
'''
cmd = "dscl . -passwd /Users/{0} '{1}'".format(name, password)
try:
salt.utils.mac_utils.execute_return_success(cmd)
except CommandExecutionError as exc:
if 'eDSUnknownNodeName' in exc.strerror:
raise CommandExecutionError('User not found: {0}'.format(name))
raise CommandExecutionError('Unknown error: {0}'.format(exc.strerror))
return True
|
saltstack/salt
|
salt/modules/mac_shadow.py
|
set_change
|
python
|
def set_change(name, date):
'''
Sets the date on which the password expires. The user will be required to
change their password. Format is mm/dd/yyyy
:param str name: The name of the user account
:param date date: The date the password will expire. Must be in mm/dd/yyyy
format.
:return: True if successful, otherwise False
:rtype: bool
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.set_change username 09/21/2016
'''
_set_account_policy(
name, 'usingExpirationDate=1 expirationDateGMT={0}'.format(date))
return get_change(name) == date
|
Sets the date on which the password expires. The user will be required to
change their password. Format is mm/dd/yyyy
:param str name: The name of the user account
:param date date: The date the password will expire. Must be in mm/dd/yyyy
format.
:return: True if successful, otherwise False
:rtype: bool
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.set_change username 09/21/2016
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_shadow.py#L402-L426
|
[
"def get_change(name):\n '''\n Gets the date on which the password expires\n\n :param str name: The name of the user account\n\n :return: The date the password will expire\n :rtype: str\n\n :raises: CommandExecutionError on user not found or any other unknown error\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' shadow.get_change username\n '''\n policies = _get_account_policy(name)\n\n if 'expirationDateGMT' in policies:\n return policies['expirationDateGMT']\n\n return 'Value not set'\n",
"def _set_account_policy(name, policy):\n '''\n Set a value in the user accountPolicy. For use by this module only\n\n :param str name: The user name\n :param str policy: The policy to apply\n\n :return: True if success, otherwise False\n :rtype: bool\n\n :raises: CommandExecutionError on user not found or any other unknown error\n '''\n cmd = 'pwpolicy -u {0} -setpolicy \"{1}\"'.format(name, policy)\n\n try:\n return salt.utils.mac_utils.execute_return_success(cmd)\n except CommandExecutionError as exc:\n if 'Error: user <{0}> not found'.format(name) in exc.strerror:\n raise CommandExecutionError('User not found: {0}'.format(name))\n raise CommandExecutionError('Unknown error: {0}'.format(exc.strerror))\n"
] |
# -*- coding: utf-8 -*-
'''
Manage macOS local directory passwords and policies
.. versionadded:: 2016.3.0
Note that it is usually better to apply password policies through the creation
of a configuration profile.
'''
# Authentication concepts reference:
# https://developer.apple.com/library/mac/documentation/Networking/Conceptual/Open_Directory/openDirectoryConcepts/openDirectoryConcepts.html#//apple_ref/doc/uid/TP40000917-CH3-CIFCAIBB
from __future__ import absolute_import, unicode_literals, print_function
from datetime import datetime
try:
import pwd
HAS_PWD = True
except ImportError:
HAS_PWD = False
# Import salt libs
import logging
import salt.utils.mac_utils
import salt.utils.platform
from salt.exceptions import CommandExecutionError
log = logging.getLogger(__name__) # Start logging
__virtualname__ = 'shadow'
def __virtual__():
# Is this macOS?
if not salt.utils.platform.is_darwin():
return False, 'Not macOS'
if HAS_PWD:
return __virtualname__
else:
return (False, 'The pwd module failed to load.')
def _get_account_policy(name):
'''
Get the entire accountPolicy and return it as a dictionary. For use by this
module only
:param str name: The user name
:return: a dictionary containing all values for the accountPolicy
:rtype: dict
:raises: CommandExecutionError on user not found or any other unknown error
'''
cmd = 'pwpolicy -u {0} -getpolicy'.format(name)
try:
ret = salt.utils.mac_utils.execute_return_result(cmd)
except CommandExecutionError as exc:
if 'Error: user <{0}> not found'.format(name) in exc.strerror:
raise CommandExecutionError('User not found: {0}'.format(name))
raise CommandExecutionError('Unknown error: {0}'.format(exc.strerror))
try:
policy_list = ret.split('\n')[1].split(' ')
policy_dict = {}
for policy in policy_list:
if '=' in policy:
key, value = policy.split('=')
policy_dict[key] = value
return policy_dict
except IndexError:
return {}
def _set_account_policy(name, policy):
'''
Set a value in the user accountPolicy. For use by this module only
:param str name: The user name
:param str policy: The policy to apply
:return: True if success, otherwise False
:rtype: bool
:raises: CommandExecutionError on user not found or any other unknown error
'''
cmd = 'pwpolicy -u {0} -setpolicy "{1}"'.format(name, policy)
try:
return salt.utils.mac_utils.execute_return_success(cmd)
except CommandExecutionError as exc:
if 'Error: user <{0}> not found'.format(name) in exc.strerror:
raise CommandExecutionError('User not found: {0}'.format(name))
raise CommandExecutionError('Unknown error: {0}'.format(exc.strerror))
def _get_account_policy_data_value(name, key):
'''
Return the value for a key in the accountPolicy section of the user's plist
file. For use by this module only
:param str name: The username
:param str key: The accountPolicy key
:return: The value contained within the key
:rtype: str
:raises: CommandExecutionError on user not found or any other unknown error
'''
cmd = 'dscl . -readpl /Users/{0} accountPolicyData {1}'.format(name, key)
try:
ret = salt.utils.mac_utils.execute_return_result(cmd)
except CommandExecutionError as exc:
if 'eDSUnknownNodeName' in exc.strerror:
raise CommandExecutionError('User not found: {0}'.format(name))
raise CommandExecutionError('Unknown error: {0}'.format(exc.strerror))
return ret
def _convert_to_datetime(unix_timestamp):
'''
Converts a unix timestamp to a human readable date/time
:param float unix_timestamp: A unix timestamp
:return: A date/time in the format YYYY-mm-dd HH:MM:SS
:rtype: str
'''
try:
unix_timestamp = float(unix_timestamp)
return datetime.fromtimestamp(unix_timestamp).strftime('%Y-%m-%d %H:%M:%S')
except (ValueError, TypeError):
return 'Invalid Timestamp'
def info(name):
'''
Return information for the specified user
:param str name: The username
:return: A dictionary containing the user's shadow information
:rtype: dict
CLI Example:
.. code-block:: bash
salt '*' shadow.info admin
'''
try:
data = pwd.getpwnam(name)
return {'name': data.pw_name,
'passwd': data.pw_passwd,
'account_created': get_account_created(name),
'login_failed_count': get_login_failed_count(name),
'login_failed_last': get_login_failed_last(name),
'lstchg': get_last_change(name),
'max': get_maxdays(name),
'expire': get_expire(name),
'change': get_change(name),
'min': 'Unavailable',
'warn': 'Unavailable',
'inact': 'Unavailable'}
except KeyError:
log.debug('User not found: %s', name)
return {'name': '',
'passwd': '',
'account_created': '',
'login_failed_count': '',
'login_failed_last': '',
'lstchg': '',
'max': '',
'expire': '',
'change': '',
'min': '',
'warn': '',
'inact': ''}
def get_account_created(name):
'''
Get the date/time the account was created
:param str name: The username of the account
:return: The date/time the account was created (yyyy-mm-dd hh:mm:ss)
:rtype: str
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.get_account_created admin
'''
ret = _get_account_policy_data_value(name, 'creationTime')
unix_timestamp = salt.utils.mac_utils.parse_return(ret)
date_text = _convert_to_datetime(unix_timestamp)
return date_text
def get_last_change(name):
'''
Get the date/time the account was changed
:param str name: The username of the account
:return: The date/time the account was modified (yyyy-mm-dd hh:mm:ss)
:rtype: str
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.get_last_change admin
'''
ret = _get_account_policy_data_value(name, 'passwordLastSetTime')
unix_timestamp = salt.utils.mac_utils.parse_return(ret)
date_text = _convert_to_datetime(unix_timestamp)
return date_text
def get_login_failed_count(name):
'''
Get the the number of failed login attempts
:param str name: The username of the account
:return: The number of failed login attempts
:rtype: int
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.get_login_failed_count admin
'''
ret = _get_account_policy_data_value(name, 'failedLoginCount')
return salt.utils.mac_utils.parse_return(ret)
def get_login_failed_last(name):
'''
Get the date/time of the last failed login attempt
:param str name: The username of the account
:return: The date/time of the last failed login attempt on this account
(yyyy-mm-dd hh:mm:ss)
:rtype: str
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.get_login_failed_last admin
'''
ret = _get_account_policy_data_value(name, 'failedLoginTimestamp')
unix_timestamp = salt.utils.mac_utils.parse_return(ret)
date_text = _convert_to_datetime(unix_timestamp)
return date_text
def set_maxdays(name, days):
'''
Set the maximum age of the password in days
:param str name: The username of the account
:param int days: The maximum age of the account in days
:return: True if successful, False if not
:rtype: bool
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.set_maxdays admin 90
'''
minutes = days * 24 * 60
_set_account_policy(
name, 'maxMinutesUntilChangePassword={0}'.format(minutes))
return get_maxdays(name) == days
def get_maxdays(name):
'''
Get the maximum age of the password
:param str name: The username of the account
:return: The maximum age of the password in days
:rtype: int
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.get_maxdays admin 90
'''
policies = _get_account_policy(name)
if 'maxMinutesUntilChangePassword' in policies:
max_minutes = policies['maxMinutesUntilChangePassword']
return int(max_minutes) / 24 / 60
return 0
def set_mindays(name, days):
'''
Set the minimum password age in days. Not available in macOS.
:param str name: The user name
:param int days: The number of days
:return: Will always return False until macOS supports this feature.
:rtype: bool
CLI Example:
.. code-block:: bash
salt '*' shadow.set_mindays admin 90
'''
return False
def set_inactdays(name, days):
'''
Set the number if inactive days before the account is locked. Not available
in macOS
:param str name: The user name
:param int days: The number of days
:return: Will always return False until macOS supports this feature.
:rtype: bool
CLI Example:
.. code-block:: bash
salt '*' shadow.set_inactdays admin 90
'''
return False
def set_warndays(name, days):
'''
Set the number of days before the password expires that the user will start
to see a warning. Not available in macOS
:param str name: The user name
:param int days: The number of days
:return: Will always return False until macOS supports this feature.
:rtype: bool
CLI Example:
.. code-block:: bash
salt '*' shadow.set_warndays admin 90
'''
return False
def get_change(name):
'''
Gets the date on which the password expires
:param str name: The name of the user account
:return: The date the password will expire
:rtype: str
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.get_change username
'''
policies = _get_account_policy(name)
if 'expirationDateGMT' in policies:
return policies['expirationDateGMT']
return 'Value not set'
def set_expire(name, date):
'''
Sets the date on which the account expires. The user will not be able to
login after this date. Date format is mm/dd/yyyy
:param str name: The name of the user account
:param datetime date: The date the account will expire. Format must be
mm/dd/yyyy.
:return: True if successful, False if not
:rtype: bool
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.set_expire username 07/23/2015
'''
_set_account_policy(
name, 'usingHardExpirationDate=1 hardExpireDateGMT={0}'.format(date))
return get_expire(name) == date
def get_expire(name):
'''
Gets the date on which the account expires
:param str name: The name of the user account
:return: The date the account expires
:rtype: str
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.get_expire username
'''
policies = _get_account_policy(name)
if 'hardExpireDateGMT' in policies:
return policies['hardExpireDateGMT']
return 'Value not set'
def del_password(name):
'''
Deletes the account password
:param str name: The user name of the account
:return: True if successful, otherwise False
:rtype: bool
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.del_password username
'''
# This removes the password
cmd = "dscl . -passwd /Users/{0} ''".format(name)
try:
salt.utils.mac_utils.execute_return_success(cmd)
except CommandExecutionError as exc:
if 'eDSUnknownNodeName' in exc.strerror:
raise CommandExecutionError('User not found: {0}'.format(name))
raise CommandExecutionError('Unknown error: {0}'.format(exc.strerror))
# This is so it looks right in shadow.info
cmd = "dscl . -create /Users/{0} Password '*'".format(name)
salt.utils.mac_utils.execute_return_success(cmd)
return info(name)['passwd'] == '*'
def set_password(name, password):
'''
Set the password for a named user (insecure, the password will be in the
process list while the command is running)
:param str name: The name of the local user, which is assumed to be in the
local directory service
:param str password: The plaintext password to set
:return: True if successful, otherwise False
:rtype: bool
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' mac_shadow.set_password macuser macpassword
'''
cmd = "dscl . -passwd /Users/{0} '{1}'".format(name, password)
try:
salt.utils.mac_utils.execute_return_success(cmd)
except CommandExecutionError as exc:
if 'eDSUnknownNodeName' in exc.strerror:
raise CommandExecutionError('User not found: {0}'.format(name))
raise CommandExecutionError('Unknown error: {0}'.format(exc.strerror))
return True
|
saltstack/salt
|
salt/modules/mac_shadow.py
|
set_expire
|
python
|
def set_expire(name, date):
'''
Sets the date on which the account expires. The user will not be able to
login after this date. Date format is mm/dd/yyyy
:param str name: The name of the user account
:param datetime date: The date the account will expire. Format must be
mm/dd/yyyy.
:return: True if successful, False if not
:rtype: bool
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.set_expire username 07/23/2015
'''
_set_account_policy(
name, 'usingHardExpirationDate=1 hardExpireDateGMT={0}'.format(date))
return get_expire(name) == date
|
Sets the date on which the account expires. The user will not be able to
login after this date. Date format is mm/dd/yyyy
:param str name: The name of the user account
:param datetime date: The date the account will expire. Format must be
mm/dd/yyyy.
:return: True if successful, False if not
:rtype: bool
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.set_expire username 07/23/2015
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_shadow.py#L454-L478
|
[
"def _set_account_policy(name, policy):\n '''\n Set a value in the user accountPolicy. For use by this module only\n\n :param str name: The user name\n :param str policy: The policy to apply\n\n :return: True if success, otherwise False\n :rtype: bool\n\n :raises: CommandExecutionError on user not found or any other unknown error\n '''\n cmd = 'pwpolicy -u {0} -setpolicy \"{1}\"'.format(name, policy)\n\n try:\n return salt.utils.mac_utils.execute_return_success(cmd)\n except CommandExecutionError as exc:\n if 'Error: user <{0}> not found'.format(name) in exc.strerror:\n raise CommandExecutionError('User not found: {0}'.format(name))\n raise CommandExecutionError('Unknown error: {0}'.format(exc.strerror))\n",
"def get_expire(name):\n '''\n Gets the date on which the account expires\n\n :param str name: The name of the user account\n\n :return: The date the account expires\n :rtype: str\n\n :raises: CommandExecutionError on user not found or any other unknown error\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' shadow.get_expire username\n '''\n policies = _get_account_policy(name)\n\n if 'hardExpireDateGMT' in policies:\n return policies['hardExpireDateGMT']\n\n return 'Value not set'\n"
] |
# -*- coding: utf-8 -*-
'''
Manage macOS local directory passwords and policies
.. versionadded:: 2016.3.0
Note that it is usually better to apply password policies through the creation
of a configuration profile.
'''
# Authentication concepts reference:
# https://developer.apple.com/library/mac/documentation/Networking/Conceptual/Open_Directory/openDirectoryConcepts/openDirectoryConcepts.html#//apple_ref/doc/uid/TP40000917-CH3-CIFCAIBB
from __future__ import absolute_import, unicode_literals, print_function
from datetime import datetime
try:
import pwd
HAS_PWD = True
except ImportError:
HAS_PWD = False
# Import salt libs
import logging
import salt.utils.mac_utils
import salt.utils.platform
from salt.exceptions import CommandExecutionError
log = logging.getLogger(__name__) # Start logging
__virtualname__ = 'shadow'
def __virtual__():
# Is this macOS?
if not salt.utils.platform.is_darwin():
return False, 'Not macOS'
if HAS_PWD:
return __virtualname__
else:
return (False, 'The pwd module failed to load.')
def _get_account_policy(name):
'''
Get the entire accountPolicy and return it as a dictionary. For use by this
module only
:param str name: The user name
:return: a dictionary containing all values for the accountPolicy
:rtype: dict
:raises: CommandExecutionError on user not found or any other unknown error
'''
cmd = 'pwpolicy -u {0} -getpolicy'.format(name)
try:
ret = salt.utils.mac_utils.execute_return_result(cmd)
except CommandExecutionError as exc:
if 'Error: user <{0}> not found'.format(name) in exc.strerror:
raise CommandExecutionError('User not found: {0}'.format(name))
raise CommandExecutionError('Unknown error: {0}'.format(exc.strerror))
try:
policy_list = ret.split('\n')[1].split(' ')
policy_dict = {}
for policy in policy_list:
if '=' in policy:
key, value = policy.split('=')
policy_dict[key] = value
return policy_dict
except IndexError:
return {}
def _set_account_policy(name, policy):
'''
Set a value in the user accountPolicy. For use by this module only
:param str name: The user name
:param str policy: The policy to apply
:return: True if success, otherwise False
:rtype: bool
:raises: CommandExecutionError on user not found or any other unknown error
'''
cmd = 'pwpolicy -u {0} -setpolicy "{1}"'.format(name, policy)
try:
return salt.utils.mac_utils.execute_return_success(cmd)
except CommandExecutionError as exc:
if 'Error: user <{0}> not found'.format(name) in exc.strerror:
raise CommandExecutionError('User not found: {0}'.format(name))
raise CommandExecutionError('Unknown error: {0}'.format(exc.strerror))
def _get_account_policy_data_value(name, key):
'''
Return the value for a key in the accountPolicy section of the user's plist
file. For use by this module only
:param str name: The username
:param str key: The accountPolicy key
:return: The value contained within the key
:rtype: str
:raises: CommandExecutionError on user not found or any other unknown error
'''
cmd = 'dscl . -readpl /Users/{0} accountPolicyData {1}'.format(name, key)
try:
ret = salt.utils.mac_utils.execute_return_result(cmd)
except CommandExecutionError as exc:
if 'eDSUnknownNodeName' in exc.strerror:
raise CommandExecutionError('User not found: {0}'.format(name))
raise CommandExecutionError('Unknown error: {0}'.format(exc.strerror))
return ret
def _convert_to_datetime(unix_timestamp):
'''
Converts a unix timestamp to a human readable date/time
:param float unix_timestamp: A unix timestamp
:return: A date/time in the format YYYY-mm-dd HH:MM:SS
:rtype: str
'''
try:
unix_timestamp = float(unix_timestamp)
return datetime.fromtimestamp(unix_timestamp).strftime('%Y-%m-%d %H:%M:%S')
except (ValueError, TypeError):
return 'Invalid Timestamp'
def info(name):
'''
Return information for the specified user
:param str name: The username
:return: A dictionary containing the user's shadow information
:rtype: dict
CLI Example:
.. code-block:: bash
salt '*' shadow.info admin
'''
try:
data = pwd.getpwnam(name)
return {'name': data.pw_name,
'passwd': data.pw_passwd,
'account_created': get_account_created(name),
'login_failed_count': get_login_failed_count(name),
'login_failed_last': get_login_failed_last(name),
'lstchg': get_last_change(name),
'max': get_maxdays(name),
'expire': get_expire(name),
'change': get_change(name),
'min': 'Unavailable',
'warn': 'Unavailable',
'inact': 'Unavailable'}
except KeyError:
log.debug('User not found: %s', name)
return {'name': '',
'passwd': '',
'account_created': '',
'login_failed_count': '',
'login_failed_last': '',
'lstchg': '',
'max': '',
'expire': '',
'change': '',
'min': '',
'warn': '',
'inact': ''}
def get_account_created(name):
'''
Get the date/time the account was created
:param str name: The username of the account
:return: The date/time the account was created (yyyy-mm-dd hh:mm:ss)
:rtype: str
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.get_account_created admin
'''
ret = _get_account_policy_data_value(name, 'creationTime')
unix_timestamp = salt.utils.mac_utils.parse_return(ret)
date_text = _convert_to_datetime(unix_timestamp)
return date_text
def get_last_change(name):
'''
Get the date/time the account was changed
:param str name: The username of the account
:return: The date/time the account was modified (yyyy-mm-dd hh:mm:ss)
:rtype: str
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.get_last_change admin
'''
ret = _get_account_policy_data_value(name, 'passwordLastSetTime')
unix_timestamp = salt.utils.mac_utils.parse_return(ret)
date_text = _convert_to_datetime(unix_timestamp)
return date_text
def get_login_failed_count(name):
'''
Get the the number of failed login attempts
:param str name: The username of the account
:return: The number of failed login attempts
:rtype: int
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.get_login_failed_count admin
'''
ret = _get_account_policy_data_value(name, 'failedLoginCount')
return salt.utils.mac_utils.parse_return(ret)
def get_login_failed_last(name):
'''
Get the date/time of the last failed login attempt
:param str name: The username of the account
:return: The date/time of the last failed login attempt on this account
(yyyy-mm-dd hh:mm:ss)
:rtype: str
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.get_login_failed_last admin
'''
ret = _get_account_policy_data_value(name, 'failedLoginTimestamp')
unix_timestamp = salt.utils.mac_utils.parse_return(ret)
date_text = _convert_to_datetime(unix_timestamp)
return date_text
def set_maxdays(name, days):
'''
Set the maximum age of the password in days
:param str name: The username of the account
:param int days: The maximum age of the account in days
:return: True if successful, False if not
:rtype: bool
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.set_maxdays admin 90
'''
minutes = days * 24 * 60
_set_account_policy(
name, 'maxMinutesUntilChangePassword={0}'.format(minutes))
return get_maxdays(name) == days
def get_maxdays(name):
'''
Get the maximum age of the password
:param str name: The username of the account
:return: The maximum age of the password in days
:rtype: int
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.get_maxdays admin 90
'''
policies = _get_account_policy(name)
if 'maxMinutesUntilChangePassword' in policies:
max_minutes = policies['maxMinutesUntilChangePassword']
return int(max_minutes) / 24 / 60
return 0
def set_mindays(name, days):
'''
Set the minimum password age in days. Not available in macOS.
:param str name: The user name
:param int days: The number of days
:return: Will always return False until macOS supports this feature.
:rtype: bool
CLI Example:
.. code-block:: bash
salt '*' shadow.set_mindays admin 90
'''
return False
def set_inactdays(name, days):
'''
Set the number if inactive days before the account is locked. Not available
in macOS
:param str name: The user name
:param int days: The number of days
:return: Will always return False until macOS supports this feature.
:rtype: bool
CLI Example:
.. code-block:: bash
salt '*' shadow.set_inactdays admin 90
'''
return False
def set_warndays(name, days):
'''
Set the number of days before the password expires that the user will start
to see a warning. Not available in macOS
:param str name: The user name
:param int days: The number of days
:return: Will always return False until macOS supports this feature.
:rtype: bool
CLI Example:
.. code-block:: bash
salt '*' shadow.set_warndays admin 90
'''
return False
def set_change(name, date):
'''
Sets the date on which the password expires. The user will be required to
change their password. Format is mm/dd/yyyy
:param str name: The name of the user account
:param date date: The date the password will expire. Must be in mm/dd/yyyy
format.
:return: True if successful, otherwise False
:rtype: bool
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.set_change username 09/21/2016
'''
_set_account_policy(
name, 'usingExpirationDate=1 expirationDateGMT={0}'.format(date))
return get_change(name) == date
def get_change(name):
'''
Gets the date on which the password expires
:param str name: The name of the user account
:return: The date the password will expire
:rtype: str
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.get_change username
'''
policies = _get_account_policy(name)
if 'expirationDateGMT' in policies:
return policies['expirationDateGMT']
return 'Value not set'
def get_expire(name):
'''
Gets the date on which the account expires
:param str name: The name of the user account
:return: The date the account expires
:rtype: str
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.get_expire username
'''
policies = _get_account_policy(name)
if 'hardExpireDateGMT' in policies:
return policies['hardExpireDateGMT']
return 'Value not set'
def del_password(name):
'''
Deletes the account password
:param str name: The user name of the account
:return: True if successful, otherwise False
:rtype: bool
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.del_password username
'''
# This removes the password
cmd = "dscl . -passwd /Users/{0} ''".format(name)
try:
salt.utils.mac_utils.execute_return_success(cmd)
except CommandExecutionError as exc:
if 'eDSUnknownNodeName' in exc.strerror:
raise CommandExecutionError('User not found: {0}'.format(name))
raise CommandExecutionError('Unknown error: {0}'.format(exc.strerror))
# This is so it looks right in shadow.info
cmd = "dscl . -create /Users/{0} Password '*'".format(name)
salt.utils.mac_utils.execute_return_success(cmd)
return info(name)['passwd'] == '*'
def set_password(name, password):
'''
Set the password for a named user (insecure, the password will be in the
process list while the command is running)
:param str name: The name of the local user, which is assumed to be in the
local directory service
:param str password: The plaintext password to set
:return: True if successful, otherwise False
:rtype: bool
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' mac_shadow.set_password macuser macpassword
'''
cmd = "dscl . -passwd /Users/{0} '{1}'".format(name, password)
try:
salt.utils.mac_utils.execute_return_success(cmd)
except CommandExecutionError as exc:
if 'eDSUnknownNodeName' in exc.strerror:
raise CommandExecutionError('User not found: {0}'.format(name))
raise CommandExecutionError('Unknown error: {0}'.format(exc.strerror))
return True
|
saltstack/salt
|
salt/modules/mac_shadow.py
|
del_password
|
python
|
def del_password(name):
'''
Deletes the account password
:param str name: The user name of the account
:return: True if successful, otherwise False
:rtype: bool
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.del_password username
'''
# This removes the password
cmd = "dscl . -passwd /Users/{0} ''".format(name)
try:
salt.utils.mac_utils.execute_return_success(cmd)
except CommandExecutionError as exc:
if 'eDSUnknownNodeName' in exc.strerror:
raise CommandExecutionError('User not found: {0}'.format(name))
raise CommandExecutionError('Unknown error: {0}'.format(exc.strerror))
# This is so it looks right in shadow.info
cmd = "dscl . -create /Users/{0} Password '*'".format(name)
salt.utils.mac_utils.execute_return_success(cmd)
return info(name)['passwd'] == '*'
|
Deletes the account password
:param str name: The user name of the account
:return: True if successful, otherwise False
:rtype: bool
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.del_password username
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_shadow.py#L506-L536
|
[
"def info(name):\n '''\n Return information for the specified user\n\n :param str name: The username\n\n :return: A dictionary containing the user's shadow information\n :rtype: dict\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' shadow.info admin\n '''\n try:\n data = pwd.getpwnam(name)\n return {'name': data.pw_name,\n 'passwd': data.pw_passwd,\n 'account_created': get_account_created(name),\n 'login_failed_count': get_login_failed_count(name),\n 'login_failed_last': get_login_failed_last(name),\n 'lstchg': get_last_change(name),\n 'max': get_maxdays(name),\n 'expire': get_expire(name),\n 'change': get_change(name),\n 'min': 'Unavailable',\n 'warn': 'Unavailable',\n 'inact': 'Unavailable'}\n\n except KeyError:\n log.debug('User not found: %s', name)\n return {'name': '',\n 'passwd': '',\n 'account_created': '',\n 'login_failed_count': '',\n 'login_failed_last': '',\n 'lstchg': '',\n 'max': '',\n 'expire': '',\n 'change': '',\n 'min': '',\n 'warn': '',\n 'inact': ''}\n",
"def execute_return_success(cmd):\n '''\n Executes the passed command. Returns True if successful\n\n :param str cmd: The command to run\n\n :return: True if successful, otherwise False\n :rtype: bool\n\n :raises: Error if command fails or is not supported\n '''\n\n ret = _run_all(cmd)\n\n if ret['retcode'] != 0 or 'not supported' in ret['stdout'].lower():\n msg = 'Command Failed: {0}\\n'.format(cmd)\n msg += 'Return Code: {0}\\n'.format(ret['retcode'])\n msg += 'Output: {0}\\n'.format(ret['stdout'])\n msg += 'Error: {0}\\n'.format(ret['stderr'])\n raise CommandExecutionError(msg)\n\n return True\n"
] |
# -*- coding: utf-8 -*-
'''
Manage macOS local directory passwords and policies
.. versionadded:: 2016.3.0
Note that it is usually better to apply password policies through the creation
of a configuration profile.
'''
# Authentication concepts reference:
# https://developer.apple.com/library/mac/documentation/Networking/Conceptual/Open_Directory/openDirectoryConcepts/openDirectoryConcepts.html#//apple_ref/doc/uid/TP40000917-CH3-CIFCAIBB
from __future__ import absolute_import, unicode_literals, print_function
from datetime import datetime
try:
import pwd
HAS_PWD = True
except ImportError:
HAS_PWD = False
# Import salt libs
import logging
import salt.utils.mac_utils
import salt.utils.platform
from salt.exceptions import CommandExecutionError
log = logging.getLogger(__name__) # Start logging
__virtualname__ = 'shadow'
def __virtual__():
# Is this macOS?
if not salt.utils.platform.is_darwin():
return False, 'Not macOS'
if HAS_PWD:
return __virtualname__
else:
return (False, 'The pwd module failed to load.')
def _get_account_policy(name):
'''
Get the entire accountPolicy and return it as a dictionary. For use by this
module only
:param str name: The user name
:return: a dictionary containing all values for the accountPolicy
:rtype: dict
:raises: CommandExecutionError on user not found or any other unknown error
'''
cmd = 'pwpolicy -u {0} -getpolicy'.format(name)
try:
ret = salt.utils.mac_utils.execute_return_result(cmd)
except CommandExecutionError as exc:
if 'Error: user <{0}> not found'.format(name) in exc.strerror:
raise CommandExecutionError('User not found: {0}'.format(name))
raise CommandExecutionError('Unknown error: {0}'.format(exc.strerror))
try:
policy_list = ret.split('\n')[1].split(' ')
policy_dict = {}
for policy in policy_list:
if '=' in policy:
key, value = policy.split('=')
policy_dict[key] = value
return policy_dict
except IndexError:
return {}
def _set_account_policy(name, policy):
'''
Set a value in the user accountPolicy. For use by this module only
:param str name: The user name
:param str policy: The policy to apply
:return: True if success, otherwise False
:rtype: bool
:raises: CommandExecutionError on user not found or any other unknown error
'''
cmd = 'pwpolicy -u {0} -setpolicy "{1}"'.format(name, policy)
try:
return salt.utils.mac_utils.execute_return_success(cmd)
except CommandExecutionError as exc:
if 'Error: user <{0}> not found'.format(name) in exc.strerror:
raise CommandExecutionError('User not found: {0}'.format(name))
raise CommandExecutionError('Unknown error: {0}'.format(exc.strerror))
def _get_account_policy_data_value(name, key):
'''
Return the value for a key in the accountPolicy section of the user's plist
file. For use by this module only
:param str name: The username
:param str key: The accountPolicy key
:return: The value contained within the key
:rtype: str
:raises: CommandExecutionError on user not found or any other unknown error
'''
cmd = 'dscl . -readpl /Users/{0} accountPolicyData {1}'.format(name, key)
try:
ret = salt.utils.mac_utils.execute_return_result(cmd)
except CommandExecutionError as exc:
if 'eDSUnknownNodeName' in exc.strerror:
raise CommandExecutionError('User not found: {0}'.format(name))
raise CommandExecutionError('Unknown error: {0}'.format(exc.strerror))
return ret
def _convert_to_datetime(unix_timestamp):
'''
Converts a unix timestamp to a human readable date/time
:param float unix_timestamp: A unix timestamp
:return: A date/time in the format YYYY-mm-dd HH:MM:SS
:rtype: str
'''
try:
unix_timestamp = float(unix_timestamp)
return datetime.fromtimestamp(unix_timestamp).strftime('%Y-%m-%d %H:%M:%S')
except (ValueError, TypeError):
return 'Invalid Timestamp'
def info(name):
'''
Return information for the specified user
:param str name: The username
:return: A dictionary containing the user's shadow information
:rtype: dict
CLI Example:
.. code-block:: bash
salt '*' shadow.info admin
'''
try:
data = pwd.getpwnam(name)
return {'name': data.pw_name,
'passwd': data.pw_passwd,
'account_created': get_account_created(name),
'login_failed_count': get_login_failed_count(name),
'login_failed_last': get_login_failed_last(name),
'lstchg': get_last_change(name),
'max': get_maxdays(name),
'expire': get_expire(name),
'change': get_change(name),
'min': 'Unavailable',
'warn': 'Unavailable',
'inact': 'Unavailable'}
except KeyError:
log.debug('User not found: %s', name)
return {'name': '',
'passwd': '',
'account_created': '',
'login_failed_count': '',
'login_failed_last': '',
'lstchg': '',
'max': '',
'expire': '',
'change': '',
'min': '',
'warn': '',
'inact': ''}
def get_account_created(name):
'''
Get the date/time the account was created
:param str name: The username of the account
:return: The date/time the account was created (yyyy-mm-dd hh:mm:ss)
:rtype: str
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.get_account_created admin
'''
ret = _get_account_policy_data_value(name, 'creationTime')
unix_timestamp = salt.utils.mac_utils.parse_return(ret)
date_text = _convert_to_datetime(unix_timestamp)
return date_text
def get_last_change(name):
'''
Get the date/time the account was changed
:param str name: The username of the account
:return: The date/time the account was modified (yyyy-mm-dd hh:mm:ss)
:rtype: str
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.get_last_change admin
'''
ret = _get_account_policy_data_value(name, 'passwordLastSetTime')
unix_timestamp = salt.utils.mac_utils.parse_return(ret)
date_text = _convert_to_datetime(unix_timestamp)
return date_text
def get_login_failed_count(name):
'''
Get the the number of failed login attempts
:param str name: The username of the account
:return: The number of failed login attempts
:rtype: int
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.get_login_failed_count admin
'''
ret = _get_account_policy_data_value(name, 'failedLoginCount')
return salt.utils.mac_utils.parse_return(ret)
def get_login_failed_last(name):
'''
Get the date/time of the last failed login attempt
:param str name: The username of the account
:return: The date/time of the last failed login attempt on this account
(yyyy-mm-dd hh:mm:ss)
:rtype: str
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.get_login_failed_last admin
'''
ret = _get_account_policy_data_value(name, 'failedLoginTimestamp')
unix_timestamp = salt.utils.mac_utils.parse_return(ret)
date_text = _convert_to_datetime(unix_timestamp)
return date_text
def set_maxdays(name, days):
'''
Set the maximum age of the password in days
:param str name: The username of the account
:param int days: The maximum age of the account in days
:return: True if successful, False if not
:rtype: bool
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.set_maxdays admin 90
'''
minutes = days * 24 * 60
_set_account_policy(
name, 'maxMinutesUntilChangePassword={0}'.format(minutes))
return get_maxdays(name) == days
def get_maxdays(name):
'''
Get the maximum age of the password
:param str name: The username of the account
:return: The maximum age of the password in days
:rtype: int
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.get_maxdays admin 90
'''
policies = _get_account_policy(name)
if 'maxMinutesUntilChangePassword' in policies:
max_minutes = policies['maxMinutesUntilChangePassword']
return int(max_minutes) / 24 / 60
return 0
def set_mindays(name, days):
'''
Set the minimum password age in days. Not available in macOS.
:param str name: The user name
:param int days: The number of days
:return: Will always return False until macOS supports this feature.
:rtype: bool
CLI Example:
.. code-block:: bash
salt '*' shadow.set_mindays admin 90
'''
return False
def set_inactdays(name, days):
'''
Set the number if inactive days before the account is locked. Not available
in macOS
:param str name: The user name
:param int days: The number of days
:return: Will always return False until macOS supports this feature.
:rtype: bool
CLI Example:
.. code-block:: bash
salt '*' shadow.set_inactdays admin 90
'''
return False
def set_warndays(name, days):
'''
Set the number of days before the password expires that the user will start
to see a warning. Not available in macOS
:param str name: The user name
:param int days: The number of days
:return: Will always return False until macOS supports this feature.
:rtype: bool
CLI Example:
.. code-block:: bash
salt '*' shadow.set_warndays admin 90
'''
return False
def set_change(name, date):
'''
Sets the date on which the password expires. The user will be required to
change their password. Format is mm/dd/yyyy
:param str name: The name of the user account
:param date date: The date the password will expire. Must be in mm/dd/yyyy
format.
:return: True if successful, otherwise False
:rtype: bool
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.set_change username 09/21/2016
'''
_set_account_policy(
name, 'usingExpirationDate=1 expirationDateGMT={0}'.format(date))
return get_change(name) == date
def get_change(name):
'''
Gets the date on which the password expires
:param str name: The name of the user account
:return: The date the password will expire
:rtype: str
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.get_change username
'''
policies = _get_account_policy(name)
if 'expirationDateGMT' in policies:
return policies['expirationDateGMT']
return 'Value not set'
def set_expire(name, date):
'''
Sets the date on which the account expires. The user will not be able to
login after this date. Date format is mm/dd/yyyy
:param str name: The name of the user account
:param datetime date: The date the account will expire. Format must be
mm/dd/yyyy.
:return: True if successful, False if not
:rtype: bool
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.set_expire username 07/23/2015
'''
_set_account_policy(
name, 'usingHardExpirationDate=1 hardExpireDateGMT={0}'.format(date))
return get_expire(name) == date
def get_expire(name):
'''
Gets the date on which the account expires
:param str name: The name of the user account
:return: The date the account expires
:rtype: str
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.get_expire username
'''
policies = _get_account_policy(name)
if 'hardExpireDateGMT' in policies:
return policies['hardExpireDateGMT']
return 'Value not set'
def set_password(name, password):
'''
Set the password for a named user (insecure, the password will be in the
process list while the command is running)
:param str name: The name of the local user, which is assumed to be in the
local directory service
:param str password: The plaintext password to set
:return: True if successful, otherwise False
:rtype: bool
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' mac_shadow.set_password macuser macpassword
'''
cmd = "dscl . -passwd /Users/{0} '{1}'".format(name, password)
try:
salt.utils.mac_utils.execute_return_success(cmd)
except CommandExecutionError as exc:
if 'eDSUnknownNodeName' in exc.strerror:
raise CommandExecutionError('User not found: {0}'.format(name))
raise CommandExecutionError('Unknown error: {0}'.format(exc.strerror))
return True
|
saltstack/salt
|
salt/modules/mac_shadow.py
|
set_password
|
python
|
def set_password(name, password):
'''
Set the password for a named user (insecure, the password will be in the
process list while the command is running)
:param str name: The name of the local user, which is assumed to be in the
local directory service
:param str password: The plaintext password to set
:return: True if successful, otherwise False
:rtype: bool
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' mac_shadow.set_password macuser macpassword
'''
cmd = "dscl . -passwd /Users/{0} '{1}'".format(name, password)
try:
salt.utils.mac_utils.execute_return_success(cmd)
except CommandExecutionError as exc:
if 'eDSUnknownNodeName' in exc.strerror:
raise CommandExecutionError('User not found: {0}'.format(name))
raise CommandExecutionError('Unknown error: {0}'.format(exc.strerror))
return True
|
Set the password for a named user (insecure, the password will be in the
process list while the command is running)
:param str name: The name of the local user, which is assumed to be in the
local directory service
:param str password: The plaintext password to set
:return: True if successful, otherwise False
:rtype: bool
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' mac_shadow.set_password macuser macpassword
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_shadow.py#L539-L568
|
[
"def execute_return_success(cmd):\n '''\n Executes the passed command. Returns True if successful\n\n :param str cmd: The command to run\n\n :return: True if successful, otherwise False\n :rtype: bool\n\n :raises: Error if command fails or is not supported\n '''\n\n ret = _run_all(cmd)\n\n if ret['retcode'] != 0 or 'not supported' in ret['stdout'].lower():\n msg = 'Command Failed: {0}\\n'.format(cmd)\n msg += 'Return Code: {0}\\n'.format(ret['retcode'])\n msg += 'Output: {0}\\n'.format(ret['stdout'])\n msg += 'Error: {0}\\n'.format(ret['stderr'])\n raise CommandExecutionError(msg)\n\n return True\n"
] |
# -*- coding: utf-8 -*-
'''
Manage macOS local directory passwords and policies
.. versionadded:: 2016.3.0
Note that it is usually better to apply password policies through the creation
of a configuration profile.
'''
# Authentication concepts reference:
# https://developer.apple.com/library/mac/documentation/Networking/Conceptual/Open_Directory/openDirectoryConcepts/openDirectoryConcepts.html#//apple_ref/doc/uid/TP40000917-CH3-CIFCAIBB
from __future__ import absolute_import, unicode_literals, print_function
from datetime import datetime
try:
import pwd
HAS_PWD = True
except ImportError:
HAS_PWD = False
# Import salt libs
import logging
import salt.utils.mac_utils
import salt.utils.platform
from salt.exceptions import CommandExecutionError
log = logging.getLogger(__name__) # Start logging
__virtualname__ = 'shadow'
def __virtual__():
# Is this macOS?
if not salt.utils.platform.is_darwin():
return False, 'Not macOS'
if HAS_PWD:
return __virtualname__
else:
return (False, 'The pwd module failed to load.')
def _get_account_policy(name):
'''
Get the entire accountPolicy and return it as a dictionary. For use by this
module only
:param str name: The user name
:return: a dictionary containing all values for the accountPolicy
:rtype: dict
:raises: CommandExecutionError on user not found or any other unknown error
'''
cmd = 'pwpolicy -u {0} -getpolicy'.format(name)
try:
ret = salt.utils.mac_utils.execute_return_result(cmd)
except CommandExecutionError as exc:
if 'Error: user <{0}> not found'.format(name) in exc.strerror:
raise CommandExecutionError('User not found: {0}'.format(name))
raise CommandExecutionError('Unknown error: {0}'.format(exc.strerror))
try:
policy_list = ret.split('\n')[1].split(' ')
policy_dict = {}
for policy in policy_list:
if '=' in policy:
key, value = policy.split('=')
policy_dict[key] = value
return policy_dict
except IndexError:
return {}
def _set_account_policy(name, policy):
'''
Set a value in the user accountPolicy. For use by this module only
:param str name: The user name
:param str policy: The policy to apply
:return: True if success, otherwise False
:rtype: bool
:raises: CommandExecutionError on user not found or any other unknown error
'''
cmd = 'pwpolicy -u {0} -setpolicy "{1}"'.format(name, policy)
try:
return salt.utils.mac_utils.execute_return_success(cmd)
except CommandExecutionError as exc:
if 'Error: user <{0}> not found'.format(name) in exc.strerror:
raise CommandExecutionError('User not found: {0}'.format(name))
raise CommandExecutionError('Unknown error: {0}'.format(exc.strerror))
def _get_account_policy_data_value(name, key):
'''
Return the value for a key in the accountPolicy section of the user's plist
file. For use by this module only
:param str name: The username
:param str key: The accountPolicy key
:return: The value contained within the key
:rtype: str
:raises: CommandExecutionError on user not found or any other unknown error
'''
cmd = 'dscl . -readpl /Users/{0} accountPolicyData {1}'.format(name, key)
try:
ret = salt.utils.mac_utils.execute_return_result(cmd)
except CommandExecutionError as exc:
if 'eDSUnknownNodeName' in exc.strerror:
raise CommandExecutionError('User not found: {0}'.format(name))
raise CommandExecutionError('Unknown error: {0}'.format(exc.strerror))
return ret
def _convert_to_datetime(unix_timestamp):
'''
Converts a unix timestamp to a human readable date/time
:param float unix_timestamp: A unix timestamp
:return: A date/time in the format YYYY-mm-dd HH:MM:SS
:rtype: str
'''
try:
unix_timestamp = float(unix_timestamp)
return datetime.fromtimestamp(unix_timestamp).strftime('%Y-%m-%d %H:%M:%S')
except (ValueError, TypeError):
return 'Invalid Timestamp'
def info(name):
'''
Return information for the specified user
:param str name: The username
:return: A dictionary containing the user's shadow information
:rtype: dict
CLI Example:
.. code-block:: bash
salt '*' shadow.info admin
'''
try:
data = pwd.getpwnam(name)
return {'name': data.pw_name,
'passwd': data.pw_passwd,
'account_created': get_account_created(name),
'login_failed_count': get_login_failed_count(name),
'login_failed_last': get_login_failed_last(name),
'lstchg': get_last_change(name),
'max': get_maxdays(name),
'expire': get_expire(name),
'change': get_change(name),
'min': 'Unavailable',
'warn': 'Unavailable',
'inact': 'Unavailable'}
except KeyError:
log.debug('User not found: %s', name)
return {'name': '',
'passwd': '',
'account_created': '',
'login_failed_count': '',
'login_failed_last': '',
'lstchg': '',
'max': '',
'expire': '',
'change': '',
'min': '',
'warn': '',
'inact': ''}
def get_account_created(name):
'''
Get the date/time the account was created
:param str name: The username of the account
:return: The date/time the account was created (yyyy-mm-dd hh:mm:ss)
:rtype: str
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.get_account_created admin
'''
ret = _get_account_policy_data_value(name, 'creationTime')
unix_timestamp = salt.utils.mac_utils.parse_return(ret)
date_text = _convert_to_datetime(unix_timestamp)
return date_text
def get_last_change(name):
'''
Get the date/time the account was changed
:param str name: The username of the account
:return: The date/time the account was modified (yyyy-mm-dd hh:mm:ss)
:rtype: str
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.get_last_change admin
'''
ret = _get_account_policy_data_value(name, 'passwordLastSetTime')
unix_timestamp = salt.utils.mac_utils.parse_return(ret)
date_text = _convert_to_datetime(unix_timestamp)
return date_text
def get_login_failed_count(name):
'''
Get the the number of failed login attempts
:param str name: The username of the account
:return: The number of failed login attempts
:rtype: int
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.get_login_failed_count admin
'''
ret = _get_account_policy_data_value(name, 'failedLoginCount')
return salt.utils.mac_utils.parse_return(ret)
def get_login_failed_last(name):
'''
Get the date/time of the last failed login attempt
:param str name: The username of the account
:return: The date/time of the last failed login attempt on this account
(yyyy-mm-dd hh:mm:ss)
:rtype: str
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.get_login_failed_last admin
'''
ret = _get_account_policy_data_value(name, 'failedLoginTimestamp')
unix_timestamp = salt.utils.mac_utils.parse_return(ret)
date_text = _convert_to_datetime(unix_timestamp)
return date_text
def set_maxdays(name, days):
'''
Set the maximum age of the password in days
:param str name: The username of the account
:param int days: The maximum age of the account in days
:return: True if successful, False if not
:rtype: bool
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.set_maxdays admin 90
'''
minutes = days * 24 * 60
_set_account_policy(
name, 'maxMinutesUntilChangePassword={0}'.format(minutes))
return get_maxdays(name) == days
def get_maxdays(name):
'''
Get the maximum age of the password
:param str name: The username of the account
:return: The maximum age of the password in days
:rtype: int
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.get_maxdays admin 90
'''
policies = _get_account_policy(name)
if 'maxMinutesUntilChangePassword' in policies:
max_minutes = policies['maxMinutesUntilChangePassword']
return int(max_minutes) / 24 / 60
return 0
def set_mindays(name, days):
'''
Set the minimum password age in days. Not available in macOS.
:param str name: The user name
:param int days: The number of days
:return: Will always return False until macOS supports this feature.
:rtype: bool
CLI Example:
.. code-block:: bash
salt '*' shadow.set_mindays admin 90
'''
return False
def set_inactdays(name, days):
'''
Set the number if inactive days before the account is locked. Not available
in macOS
:param str name: The user name
:param int days: The number of days
:return: Will always return False until macOS supports this feature.
:rtype: bool
CLI Example:
.. code-block:: bash
salt '*' shadow.set_inactdays admin 90
'''
return False
def set_warndays(name, days):
'''
Set the number of days before the password expires that the user will start
to see a warning. Not available in macOS
:param str name: The user name
:param int days: The number of days
:return: Will always return False until macOS supports this feature.
:rtype: bool
CLI Example:
.. code-block:: bash
salt '*' shadow.set_warndays admin 90
'''
return False
def set_change(name, date):
'''
Sets the date on which the password expires. The user will be required to
change their password. Format is mm/dd/yyyy
:param str name: The name of the user account
:param date date: The date the password will expire. Must be in mm/dd/yyyy
format.
:return: True if successful, otherwise False
:rtype: bool
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.set_change username 09/21/2016
'''
_set_account_policy(
name, 'usingExpirationDate=1 expirationDateGMT={0}'.format(date))
return get_change(name) == date
def get_change(name):
'''
Gets the date on which the password expires
:param str name: The name of the user account
:return: The date the password will expire
:rtype: str
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.get_change username
'''
policies = _get_account_policy(name)
if 'expirationDateGMT' in policies:
return policies['expirationDateGMT']
return 'Value not set'
def set_expire(name, date):
'''
Sets the date on which the account expires. The user will not be able to
login after this date. Date format is mm/dd/yyyy
:param str name: The name of the user account
:param datetime date: The date the account will expire. Format must be
mm/dd/yyyy.
:return: True if successful, False if not
:rtype: bool
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.set_expire username 07/23/2015
'''
_set_account_policy(
name, 'usingHardExpirationDate=1 hardExpireDateGMT={0}'.format(date))
return get_expire(name) == date
def get_expire(name):
'''
Gets the date on which the account expires
:param str name: The name of the user account
:return: The date the account expires
:rtype: str
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.get_expire username
'''
policies = _get_account_policy(name)
if 'hardExpireDateGMT' in policies:
return policies['hardExpireDateGMT']
return 'Value not set'
def del_password(name):
'''
Deletes the account password
:param str name: The user name of the account
:return: True if successful, otherwise False
:rtype: bool
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.del_password username
'''
# This removes the password
cmd = "dscl . -passwd /Users/{0} ''".format(name)
try:
salt.utils.mac_utils.execute_return_success(cmd)
except CommandExecutionError as exc:
if 'eDSUnknownNodeName' in exc.strerror:
raise CommandExecutionError('User not found: {0}'.format(name))
raise CommandExecutionError('Unknown error: {0}'.format(exc.strerror))
# This is so it looks right in shadow.info
cmd = "dscl . -create /Users/{0} Password '*'".format(name)
salt.utils.mac_utils.execute_return_success(cmd)
return info(name)['passwd'] == '*'
|
saltstack/salt
|
salt/states/rabbitmq_policy.py
|
present
|
python
|
def present(name,
pattern,
definition,
priority=0,
vhost='/',
runas=None,
apply_to=None):
'''
Ensure the RabbitMQ policy exists.
Reference: http://www.rabbitmq.com/ha.html
name
Policy name
pattern
A regex of queues to apply the policy to
definition
A json dict describing the policy
priority
Priority (defaults to 0)
vhost
Virtual host to apply to (defaults to '/')
runas
Name of the user to run the command as
apply_to
Apply policy to 'queues', 'exchanges' or 'all' (default to 'all')
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
result = {}
policies = __salt__['rabbitmq.list_policies'](vhost=vhost, runas=runas)
policy = policies.get(vhost, {}).get(name)
updates = []
if policy:
if policy.get('pattern') != pattern:
updates.append('Pattern')
current_definition = policy.get('definition')
current_definition = json.loads(current_definition) if current_definition else ''
new_definition = json.loads(definition) if definition else ''
if current_definition != new_definition:
updates.append('Definition')
if apply_to and (policy.get('apply-to') != apply_to):
updates.append('Applyto')
if int(policy.get('priority')) != priority:
updates.append('Priority')
if policy and not updates:
ret['comment'] = 'Policy {0} {1} is already present'.format(vhost, name)
return ret
if not policy:
ret['changes'].update({'old': {}, 'new': name})
if __opts__['test']:
ret['comment'] = 'Policy {0} {1} is set to be created'.format(vhost, name)
else:
log.debug('Policy doesn\'t exist - Creating')
result = __salt__['rabbitmq.set_policy'](vhost,
name,
pattern,
definition,
priority=priority,
runas=runas,
apply_to=apply_to)
elif updates:
ret['changes'].update({'old': policy, 'new': updates})
if __opts__['test']:
ret['comment'] = 'Policy {0} {1} is set to be updated'.format(vhost, name)
else:
log.debug('Policy exists but needs updating')
result = __salt__['rabbitmq.set_policy'](vhost,
name,
pattern,
definition,
priority=priority,
runas=runas,
apply_to=apply_to)
if 'Error' in result:
ret['result'] = False
ret['comment'] = result['Error']
elif ret['changes'] == {}:
ret['comment'] = '\'{0}\' is already in the desired state.'.format(name)
elif __opts__['test']:
ret['result'] = None
elif 'Set' in result:
ret['comment'] = result['Set']
return ret
|
Ensure the RabbitMQ policy exists.
Reference: http://www.rabbitmq.com/ha.html
name
Policy name
pattern
A regex of queues to apply the policy to
definition
A json dict describing the policy
priority
Priority (defaults to 0)
vhost
Virtual host to apply to (defaults to '/')
runas
Name of the user to run the command as
apply_to
Apply policy to 'queues', 'exchanges' or 'all' (default to 'all')
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/rabbitmq_policy.py#L37-L124
| null |
# -*- coding: utf-8 -*-
'''
Manage RabbitMQ Policies
========================
:maintainer: Benn Eichhorn <benn@getlocalmeasure.com>
:maturity: new
:platform: all
Example:
.. code-block:: yaml
rabbit_policy:
rabbitmq_policy.present:
- name: HA
- pattern: '.*'
- definition: '{"ha-mode": "all"}'
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import python libs
import logging
import salt.utils.path
import json
log = logging.getLogger(__name__)
def __virtual__():
'''
Only load if RabbitMQ is installed.
'''
return salt.utils.path.which('rabbitmqctl') is not None
def absent(name,
vhost='/',
runas=None):
'''
Ensure the named policy is absent
Reference: http://www.rabbitmq.com/ha.html
name
The name of the policy to remove
runas
Name of the user to run the command as
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
policy_exists = __salt__['rabbitmq.policy_exists'](
vhost, name, runas=runas)
if not policy_exists:
ret['comment'] = 'Policy \'{0} {1}\' is not present.'.format(vhost, name)
return ret
if not __opts__['test']:
result = __salt__['rabbitmq.delete_policy'](vhost, name, runas=runas)
if 'Error' in result:
ret['result'] = False
ret['comment'] = result['Error']
return ret
elif 'Deleted' in result:
ret['comment'] = 'Deleted'
# If we've reached this far before returning, we have changes.
ret['changes'] = {'new': '', 'old': name}
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Policy \'{0} {1}\' will be removed.'.format(vhost, name)
return ret
|
saltstack/salt
|
salt/states/rabbitmq_policy.py
|
absent
|
python
|
def absent(name,
vhost='/',
runas=None):
'''
Ensure the named policy is absent
Reference: http://www.rabbitmq.com/ha.html
name
The name of the policy to remove
runas
Name of the user to run the command as
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
policy_exists = __salt__['rabbitmq.policy_exists'](
vhost, name, runas=runas)
if not policy_exists:
ret['comment'] = 'Policy \'{0} {1}\' is not present.'.format(vhost, name)
return ret
if not __opts__['test']:
result = __salt__['rabbitmq.delete_policy'](vhost, name, runas=runas)
if 'Error' in result:
ret['result'] = False
ret['comment'] = result['Error']
return ret
elif 'Deleted' in result:
ret['comment'] = 'Deleted'
# If we've reached this far before returning, we have changes.
ret['changes'] = {'new': '', 'old': name}
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Policy \'{0} {1}\' will be removed.'.format(vhost, name)
return ret
|
Ensure the named policy is absent
Reference: http://www.rabbitmq.com/ha.html
name
The name of the policy to remove
runas
Name of the user to run the command as
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/rabbitmq_policy.py#L127-L165
| null |
# -*- coding: utf-8 -*-
'''
Manage RabbitMQ Policies
========================
:maintainer: Benn Eichhorn <benn@getlocalmeasure.com>
:maturity: new
:platform: all
Example:
.. code-block:: yaml
rabbit_policy:
rabbitmq_policy.present:
- name: HA
- pattern: '.*'
- definition: '{"ha-mode": "all"}'
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import python libs
import logging
import salt.utils.path
import json
log = logging.getLogger(__name__)
def __virtual__():
'''
Only load if RabbitMQ is installed.
'''
return salt.utils.path.which('rabbitmqctl') is not None
def present(name,
pattern,
definition,
priority=0,
vhost='/',
runas=None,
apply_to=None):
'''
Ensure the RabbitMQ policy exists.
Reference: http://www.rabbitmq.com/ha.html
name
Policy name
pattern
A regex of queues to apply the policy to
definition
A json dict describing the policy
priority
Priority (defaults to 0)
vhost
Virtual host to apply to (defaults to '/')
runas
Name of the user to run the command as
apply_to
Apply policy to 'queues', 'exchanges' or 'all' (default to 'all')
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
result = {}
policies = __salt__['rabbitmq.list_policies'](vhost=vhost, runas=runas)
policy = policies.get(vhost, {}).get(name)
updates = []
if policy:
if policy.get('pattern') != pattern:
updates.append('Pattern')
current_definition = policy.get('definition')
current_definition = json.loads(current_definition) if current_definition else ''
new_definition = json.loads(definition) if definition else ''
if current_definition != new_definition:
updates.append('Definition')
if apply_to and (policy.get('apply-to') != apply_to):
updates.append('Applyto')
if int(policy.get('priority')) != priority:
updates.append('Priority')
if policy and not updates:
ret['comment'] = 'Policy {0} {1} is already present'.format(vhost, name)
return ret
if not policy:
ret['changes'].update({'old': {}, 'new': name})
if __opts__['test']:
ret['comment'] = 'Policy {0} {1} is set to be created'.format(vhost, name)
else:
log.debug('Policy doesn\'t exist - Creating')
result = __salt__['rabbitmq.set_policy'](vhost,
name,
pattern,
definition,
priority=priority,
runas=runas,
apply_to=apply_to)
elif updates:
ret['changes'].update({'old': policy, 'new': updates})
if __opts__['test']:
ret['comment'] = 'Policy {0} {1} is set to be updated'.format(vhost, name)
else:
log.debug('Policy exists but needs updating')
result = __salt__['rabbitmq.set_policy'](vhost,
name,
pattern,
definition,
priority=priority,
runas=runas,
apply_to=apply_to)
if 'Error' in result:
ret['result'] = False
ret['comment'] = result['Error']
elif ret['changes'] == {}:
ret['comment'] = '\'{0}\' is already in the desired state.'.format(name)
elif __opts__['test']:
ret['result'] = None
elif 'Set' in result:
ret['comment'] = result['Set']
return ret
|
saltstack/salt
|
salt/cloud/clouds/openstack.py
|
get_configured_provider
|
python
|
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__, __active_provider_name__ or __virtualname__,
('auth', 'region_name'), log_message=False,
) or config.is_provider_configured(
__opts__, __active_provider_name__ or __virtualname__,
('cloud', 'region_name')
)
|
Return the first configured instance.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/openstack.py#L259-L269
|
[
"def is_provider_configured(opts, provider, required_keys=(), log_message=True, aliases=()):\n '''\n Check and return the first matching and fully configured cloud provider\n configuration.\n '''\n if ':' in provider:\n alias, driver = provider.split(':')\n if alias not in opts['providers']:\n return False\n if driver not in opts['providers'][alias]:\n return False\n for key in required_keys:\n if opts['providers'][alias][driver].get(key, None) is None:\n if log_message is True:\n # There's at least one require configuration key which is not\n # set.\n log.warning(\n \"The required '%s' configuration setting is missing \"\n \"from the '%s' driver, which is configured under the \"\n \"'%s' alias.\", key, provider, alias\n )\n return False\n # If we reached this far, there's a properly configured provider.\n # Return it!\n return opts['providers'][alias][driver]\n\n for alias, drivers in six.iteritems(opts['providers']):\n for driver, provider_details in six.iteritems(drivers):\n if driver != provider and driver not in aliases:\n continue\n\n # If we reached this far, we have a matching provider, let's see if\n # all required configuration keys are present and not None.\n skip_provider = False\n for key in required_keys:\n if provider_details.get(key, None) is None:\n if log_message is True:\n # This provider does not include all necessary keys,\n # continue to next one.\n log.warning(\n \"The required '%s' configuration setting is \"\n \"missing from the '%s' driver, which is configured \"\n \"under the '%s' alias.\", key, provider, alias\n )\n skip_provider = True\n break\n\n if skip_provider:\n continue\n\n # If we reached this far, the provider included all required keys\n return provider_details\n\n # If we reached this point, the provider is not configured.\n return False\n"
] |
# -*- coding: utf-8 -*-
'''
Openstack Cloud Driver
======================
:depends: `shade>=1.19.0 <https://pypi.python.org/pypi/shade>`_
OpenStack is an open source project that is in use by a number a cloud
providers, each of which have their own ways of using it.
This OpenStack driver uses a the shade python module which is managed by the
OpenStack Infra team. This module is written to handle all the different
versions of different OpenStack tools for salt, so most commands are just passed
over to the module to handle everything.
Provider
--------
There are two ways to configure providers for this driver. The first one is to
just let shade handle everything, and configure using os-client-config_ and
setting up `/etc/openstack/clouds.yml`.
.. code-block:: yaml
clouds:
democloud:
region_name: RegionOne
auth:
username: 'demo'
password: secret
project_name: 'demo'
auth_url: 'http://openstack/identity'
And then this can be referenced in the salt provider based on the `democloud`
name.
.. code-block:: yaml
myopenstack:
driver: openstack
cloud: democloud
region_name: RegionOne
This allows for just using one configuration for salt-cloud and for any other
openstack tools which are all using `/etc/openstack/clouds.yml`
The other method allows for specifying everything in the provider config,
instead of using the extra configuration file. This will allow for passing
salt-cloud configs only through pillars for minions without having to write a
clouds.yml file on each minion.abs
.. code-block:: yaml
myopenstack:
driver: openstack
region_name: RegionOne
auth:
username: 'demo'
password: secret
project_name: 'demo'
auth_url: 'http://openstack/identity'
Or if you need to use a profile to setup some extra stuff, it can be passed as a
`profile` to use any of the vendor_ config options.
.. code-block:: yaml
myrackspace:
driver: openstack
profile: rackspace
auth:
username: rackusername
api_key: myapikey
region_name: ORD
auth_type: rackspace_apikey
And this will pull in the profile for rackspace and setup all the correct
options for the auth_url and different api versions for services.
Profile
-------
Most of the options for building servers are just passed on to the
create_server_ function from shade.
The salt specific ones are:
- ssh_key_file: The path to the ssh key that should be used to login to the machine to bootstrap it
- ssh_key_file: The name of the keypair in openstack
- userdata_template: The renderer to use if the userdata is a file that is templated. Default: False
- ssh_interface: The interface to use to login for bootstrapping: public_ips, private_ips, floating_ips, fixed_ips
.. code-block:: yaml
centos:
provider: myopenstack
image: CentOS 7
size: ds1G
ssh_key_name: mykey
ssh_key_file: /root/.ssh/id_rsa
This is the minimum setup required.
If metadata is set to make sure that the host has finished setting up the
`wait_for_metadata` can be set.
.. code-block:: yaml
centos:
provider: myopenstack
image: CentOS 7
size: ds1G
ssh_key_name: mykey
ssh_key_file: /root/.ssh/id_rsa
meta:
build_config: rack_user_only
wait_for_metadata:
rax_service_level_automation: Complete
rackconnect_automation_status: DEPLOYED
Anything else from the create_server_ docs can be passed through here.
- **image**: Image dict, name or ID to boot with. image is required
unless boot_volume is given.
- **flavor**: Flavor dict, name or ID to boot onto.
- **auto_ip**: Whether to take actions to find a routable IP for
the server. (defaults to True)
- **ips**: List of IPs to attach to the server (defaults to None)
- **ip_pool**: Name of the network or floating IP pool to get an
address from. (defaults to None)
- **root_volume**: Name or ID of a volume to boot from
(defaults to None - deprecated, use boot_volume)
- **boot_volume**: Name or ID of a volume to boot from
(defaults to None)
- **terminate_volume**: If booting from a volume, whether it should
be deleted when the server is destroyed.
(defaults to False)
- **volumes**: (optional) A list of volumes to attach to the server
- **meta**: (optional) A dict of arbitrary key/value metadata to
store for this server. Both keys and values must be
<=255 characters.
- **files**: (optional, deprecated) A dict of files to overwrite
on the server upon boot. Keys are file names (i.e.
``/etc/passwd``) and values
are the file contents (either as a string or as a
file-like object). A maximum of five entries is allowed,
and each file must be 10k or less.
- **reservation_id**: a UUID for the set of servers being requested.
- **min_count**: (optional extension) The minimum number of
servers to launch.
- **max_count**: (optional extension) The maximum number of
servers to launch.
- **security_groups**: A list of security group names
- **userdata**: user data to pass to be exposed by the metadata
server this can be a file type object as well or a
string.
- **key_name**: (optional extension) name of previously created
keypair to inject into the instance.
- **availability_zone**: Name of the availability zone for instance
placement.
- **block_device_mapping**: (optional) A dict of block
device mappings for this server.
- **block_device_mapping_v2**: (optional) A dict of block
device mappings for this server.
- **nics**: (optional extension) an ordered list of nics to be
added to this server, with information about
connected networks, fixed IPs, port etc.
- **scheduler_hints**: (optional extension) arbitrary key-value pairs
specified by the client to help boot an instance
- **config_drive**: (optional extension) value for config drive
either boolean, or volume-id
- **disk_config**: (optional extension) control how the disk is
partitioned when the server is created. possible
values are 'AUTO' or 'MANUAL'.
- **admin_pass**: (optional extension) add a user supplied admin
password.
- **timeout**: (optional) Seconds to wait, defaults to 60.
See the ``wait`` parameter.
- **reuse_ips**: (optional) Whether to attempt to reuse pre-existing
floating ips should a floating IP be
needed (defaults to True)
- **network**: (optional) Network dict or name or ID to attach the
server to. Mutually exclusive with the nics parameter.
Can also be be a list of network names or IDs or
network dicts.
- **boot_from_volume**: Whether to boot from volume. 'boot_volume'
implies True, but boot_from_volume=True with
no boot_volume is valid and will create a
volume from the image and use that.
- **volume_size**: When booting an image from volume, how big should
the created volume be? Defaults to 50.
- **nat_destination**: Which network should a created floating IP
be attached to, if it's not possible to
infer from the cloud's configuration.
(Optional, defaults to None)
- **group**: ServerGroup dict, name or id to boot the server in.
If a group is provided in both scheduler_hints and in
the group param, the group param will win.
(Optional, defaults to None)
.. note::
If there is anything added, that is not in this list, it can be added to an `extras`
dictionary for the profile, and that will be to the create_server function.
.. _create_server: https://docs.openstack.org/shade/latest/user/usage.html#shade.OpenStackCloud.create_server
.. _vendor: https://docs.openstack.org/os-client-config/latest/user/vendor-support.html
.. _os-client-config: https://docs.openstack.org/os-client-config/latest/user/configuration.html#config-files
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import Python Libs
import copy
import logging
import os
import pprint
import socket
# Import Salt Libs
import salt.utils.versions
import salt.config as config
from salt.ext import six
from salt.exceptions import (
SaltCloudSystemExit,
SaltCloudExecutionTimeout,
SaltCloudExecutionFailure,
SaltCloudConfigError,
)
# Import 3rd-Party Libs
try:
import shade
import shade.openstackcloud
import shade.exc
import os_client_config
HAS_SHADE = (
salt.utils.versions._LooseVersion(shade.__version__) >= salt.utils.versions._LooseVersion('1.19.0'),
'Please install newer version of shade: >= 1.19.0'
)
except ImportError:
HAS_SHADE = (False, 'Install pypi module shade >= 1.19.0')
log = logging.getLogger(__name__)
__virtualname__ = 'openstack'
def __virtual__():
'''
Check for OpenStack dependencies
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return HAS_SHADE
return __virtualname__
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
deps = {
'shade': shade[0],
'os_client_config': shade[0],
}
return config.check_driver_dependencies(
__virtualname__,
deps
)
def preferred_ip(vm_, ips):
'''
Return the preferred Internet protocol. Either 'ipv4' (default) or 'ipv6'.
'''
proto = config.get_cloud_config_value(
'protocol', vm_, __opts__, default='ipv4', search_global=False
)
family = socket.AF_INET
if proto == 'ipv6':
family = socket.AF_INET6
for ip in ips:
try:
socket.inet_pton(family, ip)
return ip
except Exception:
continue
return False
def ssh_interface(vm_):
'''
Return the ssh_interface type to connect to. Either 'public_ips' (default)
or 'private_ips'.
'''
return config.get_cloud_config_value('ssh_interface', vm_, __opts__, default='public_ips', search_global=False)
def get_conn():
'''
Return a conn object for the passed VM data
'''
if __active_provider_name__ in __context__:
return __context__[__active_provider_name__]
vm_ = get_configured_provider()
profile = vm_.pop('profile', None)
if profile is not None:
vm_ = __utils__['dictupdate.update'](os_client_config.vendors.get_profile(profile), vm_)
conn = shade.openstackcloud.OpenStackCloud(cloud_config=None, **vm_)
if __active_provider_name__ is not None:
__context__[__active_provider_name__] = conn
return conn
def list_nodes(conn=None, call=None):
'''
Return a list of VMs
CLI Example
.. code-block:: bash
salt-cloud -f list_nodes myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
ret = {}
for node, info in list_nodes_full(conn=conn).items():
for key in ('id', 'name', 'size', 'state', 'private_ips', 'public_ips', 'floating_ips', 'fixed_ips', 'image'):
ret.setdefault(node, {}).setdefault(key, info.get(key))
return ret
def list_nodes_min(conn=None, call=None):
'''
Return a list of VMs with minimal information
CLI Example
.. code-block:: bash
salt-cloud -f list_nodes_min myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_min function must be called with -f or --function.'
)
if conn is None:
conn = get_conn()
ret = {}
for node in conn.list_servers(bare=True):
ret[node.name] = {'id': node.id, 'state': node.status}
return ret
def _get_ips(node, addr_type='public'):
ret = []
for _, interface in node.addresses.items():
for addr in interface:
if addr_type in ('floating', 'fixed') and addr_type == addr.get('OS-EXT-IPS:type'):
ret.append(addr['addr'])
elif addr_type == 'public' and __utils__['cloud.is_public_ip'](addr['addr']):
ret.append(addr['addr'])
elif addr_type == 'private' and not __utils__['cloud.is_public_ip'](addr['addr']):
ret.append(addr['addr'])
return ret
def list_nodes_full(conn=None, call=None):
'''
Return a list of VMs with all the information about them
CLI Example
.. code-block:: bash
salt-cloud -f list_nodes_full myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or --function.'
)
if conn is None:
conn = get_conn()
ret = {}
for node in conn.list_servers(detailed=True):
ret[node.name] = dict(node)
ret[node.name]['id'] = node.id
ret[node.name]['name'] = node.name
ret[node.name]['size'] = node.flavor.name
ret[node.name]['state'] = node.status
ret[node.name]['private_ips'] = _get_ips(node, 'private')
ret[node.name]['public_ips'] = _get_ips(node, 'public')
ret[node.name]['floating_ips'] = _get_ips(node, 'floating')
ret[node.name]['fixed_ips'] = _get_ips(node, 'fixed')
ret[node.name]['image'] = node.image.name
return ret
def list_nodes_select(conn=None, call=None):
'''
Return a list of VMs with the fields from `query.selection`
CLI Example
.. code-block:: bash
salt-cloud -f list_nodes_full myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_select function must be called with -f or --function.'
)
return __utils__['cloud.list_nodes_select'](
list_nodes(conn, 'function'), __opts__['query.selection'], call,
)
def show_instance(name, conn=None, call=None):
'''
Get VM on this OpenStack account
name
name of the instance
CLI Example
.. code-block:: bash
salt-cloud -a show_instance myserver
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
if conn is None:
conn = get_conn()
node = conn.get_server(name, bare=True)
ret = dict(node)
ret['id'] = node.id
ret['name'] = node.name
ret['size'] = conn.get_flavor(node.flavor.id).name
ret['state'] = node.status
ret['private_ips'] = _get_ips(node, 'private')
ret['public_ips'] = _get_ips(node, 'public')
ret['floating_ips'] = _get_ips(node, 'floating')
ret['fixed_ips'] = _get_ips(node, 'fixed')
if isinstance(node.image, six.string_types):
ret['image'] = node.image
else:
ret['image'] = conn.get_image(node.image.id).name
return ret
def avail_images(conn=None, call=None):
'''
List available images for OpenStack
CLI Example
.. code-block:: bash
salt-cloud -f avail_images myopenstack
salt-cloud --list-images myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
if conn is None:
conn = get_conn()
return conn.list_images()
def avail_sizes(conn=None, call=None):
'''
List available sizes for OpenStack
CLI Example
.. code-block:: bash
salt-cloud -f avail_sizes myopenstack
salt-cloud --list-sizes myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
if conn is None:
conn = get_conn()
return conn.list_flavors()
def list_networks(conn=None, call=None):
'''
List networks for OpenStack
CLI Example
.. code-block:: bash
salt-cloud -f list_networks myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_networks function must be called with '
'-f or --function'
)
if conn is None:
conn = get_conn()
return conn.list_networks()
def list_subnets(conn=None, call=None, kwargs=None):
'''
List subnets in a virtual network
network
network to list subnets of
.. code-block:: bash
salt-cloud -f list_subnets myopenstack network=salt-net
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_subnets function must be called with '
'-f or --function.'
)
if conn is None:
conn = get_conn()
if kwargs is None or (isinstance(kwargs, dict) and 'network' not in kwargs):
raise SaltCloudSystemExit(
'A `network` must be specified'
)
return conn.list_subnets(filters={'network': kwargs['network']})
def _clean_create_kwargs(**kwargs):
'''
Sanatize kwargs to be sent to create_server
'''
VALID_OPTS = {
'name': six.string_types,
'image': six.string_types,
'flavor': six.string_types,
'auto_ip': bool,
'ips': list,
'ip_pool': six.string_types,
'root_volume': six.string_types,
'boot_volume': six.string_types,
'terminate_volume': bool,
'volumes': list,
'meta': dict,
'files': dict,
'reservation_id': six.string_types,
'security_groups': list,
'key_name': six.string_types,
'availability_zone': six.string_types,
'block_device_mapping': dict,
'block_device_mapping_v2': dict,
'nics': list,
'scheduler_hints': dict,
'config_drive': bool,
'disk_config': six.string_types, # AUTO or MANUAL
'admin_pass': six.string_types,
'wait': bool,
'timeout': int,
'reuse_ips': bool,
'network': dict,
'boot_from_volume': bool,
'volume_size': int,
'nat_destination': six.string_types,
'group': six.string_types,
'userdata': six.string_types,
}
extra = kwargs.pop('extra', {})
for key, value in six.iteritems(kwargs.copy()):
if key in VALID_OPTS:
if isinstance(value, VALID_OPTS[key]):
continue
log.error('Error %s: %s is not of type %s', key, value, VALID_OPTS[key])
kwargs.pop(key)
return __utils__['dictupdate.update'](kwargs, extra)
def request_instance(vm_, conn=None, call=None):
'''
Request an instance to be built
'''
if call == 'function':
# Technically this function may be called other ways too, but it
# definitely cannot be called with --function.
raise SaltCloudSystemExit(
'The request_instance action must be called with -a or --action.'
)
kwargs = copy.deepcopy(vm_)
log.info('Creating Cloud VM %s', vm_['name'])
__utils__['cloud.check_name'](vm_['name'], 'a-zA-Z0-9._-')
conn = get_conn()
userdata = config.get_cloud_config_value(
'userdata', vm_, __opts__, search_global=False, default=None
)
if userdata is not None and os.path.isfile(userdata):
try:
with __utils__['files.fopen'](userdata, 'r') as fp_:
kwargs['userdata'] = __utils__['cloud.userdata_template'](
__opts__, vm_, fp_.read()
)
except Exception as exc:
log.exception(
'Failed to read userdata from %s: %s', userdata, exc)
if 'size' in kwargs:
kwargs['flavor'] = kwargs.pop('size')
kwargs['key_name'] = config.get_cloud_config_value(
'ssh_key_name', vm_, __opts__, search_global=False, default=None
)
kwargs['wait'] = True
try:
conn.create_server(**_clean_create_kwargs(**kwargs))
except shade.exc.OpenStackCloudException as exc:
log.error('Error creating server %s: %s', vm_['name'], exc)
destroy(vm_['name'], conn=conn, call='action')
raise SaltCloudSystemExit(six.text_type(exc))
return show_instance(vm_['name'], conn=conn, call='action')
def create(vm_):
'''
Create a single VM from a data dict
'''
deploy = config.get_cloud_config_value('deploy', vm_, __opts__)
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 ssh_key_file \'{0}\' does not exist'.format(
key_filename
)
)
vm_['key_filename'] = key_filename
__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']
)
conn = get_conn()
if 'instance_id' in vm_:
# This was probably created via another process, and doesn't have
# things like salt keys created yet, so let's create them now.
if 'pub_key' not in vm_ and 'priv_key' not in vm_:
log.debug('Generating minion keys for \'%s\'', vm_['name'])
vm_['priv_key'], vm_['pub_key'] = __utils__['cloud.gen_keys'](
config.get_cloud_config_value(
'keysize',
vm_,
__opts__
)
)
else:
# Put together all of the information required to request the instance,
# and then fire off the request for it
request_instance(conn=conn, call='action', vm_=vm_)
data = show_instance(vm_.get('instance_id', vm_['name']), conn=conn, call='action')
log.debug('VM is now running')
def __query_node(vm_):
data = show_instance(vm_['name'], conn=conn, call='action')
if 'wait_for_metadata' in vm_:
for key, value in six.iteritems(vm_.get('wait_for_metadata', {})):
log.debug('Waiting for metadata: %s=%s', key, value)
if data['metadata'].get(key, None) != value:
log.debug('Metadata is not ready: %s=%s', key, data['metadata'].get(key))
return False
return preferred_ip(vm_, data[ssh_interface(vm_)])
try:
ip_address = __utils__['cloud.wait_for_fun'](
__query_node,
vm_=vm_
)
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))
log.debug('Using IP address %s', ip_address)
salt_interface = __utils__['cloud.get_salt_interface'](vm_, __opts__)
salt_ip_address = preferred_ip(vm_, data[salt_interface])
log.debug('Salt interface set to: %s', salt_ip_address)
if not ip_address:
raise SaltCloudSystemExit('A valid IP address was not found')
vm_['ssh_host'] = ip_address
vm_['salt_host'] = salt_ip_address
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)
)
event_data = {
'name': vm_['name'],
'profile': vm_['profile'],
'provider': vm_['driver'],
'instance_id': data['id'],
'floating_ips': data['floating_ips'],
'fixed_ips': data['fixed_ips'],
'private_ips': data['private_ips'],
'public_ips': data['public_ips'],
}
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args=__utils__['cloud.filter_event']('created', event_data, list(event_data)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
__utils__['cloud.cachedir_index_add'](vm_['name'], vm_['profile'], 'nova', vm_['driver'])
return ret
def destroy(name, conn=None, call=None):
'''
Delete a single VM
'''
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']
)
if not conn:
conn = get_conn()
node = show_instance(name, conn=conn, call='action')
log.info('Destroying VM: %s', name)
ret = conn.delete_server(name)
if ret:
log.info('Destroyed VM: %s', name)
# Fire destroy action
__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('delete_sshkeys', False) is True:
__utils__['cloud.remove_sshkey'](getattr(node, __opts__.get('ssh_interface', 'public_ips'))[0])
if __opts__.get('update_cachedir', False) is True:
__utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__)
__utils__['cloud.cachedir_index_del'](name)
return True
log.error('Failed to Destroy VM: %s', name)
return False
def call(conn=None, call=None, kwargs=None):
'''
Call function from shade.
func
function to call from shade.openstackcloud library
CLI Example
.. code-block:: bash
salt-cloud -f call myopenstack func=list_images
t sujksalt-cloud -f call myopenstack func=create_network name=mysubnet
'''
if call == 'action':
raise SaltCloudSystemExit(
'The call function must be called with '
'-f or --function.'
)
if 'func' not in kwargs:
raise SaltCloudSystemExit(
'No `func` argument passed'
)
if conn is None:
conn = get_conn()
func = kwargs.pop('func')
for key, value in kwargs.items():
try:
kwargs[key] = __utils__['json.loads'](value)
except ValueError:
continue
try:
return getattr(conn, func)(**kwargs)
except shade.exc.OpenStackCloudException as exc:
log.error('Error running %s: %s', func, exc)
raise SaltCloudSystemExit(six.text_type(exc))
|
saltstack/salt
|
salt/cloud/clouds/openstack.py
|
preferred_ip
|
python
|
def preferred_ip(vm_, ips):
'''
Return the preferred Internet protocol. Either 'ipv4' (default) or 'ipv6'.
'''
proto = config.get_cloud_config_value(
'protocol', vm_, __opts__, default='ipv4', search_global=False
)
family = socket.AF_INET
if proto == 'ipv6':
family = socket.AF_INET6
for ip in ips:
try:
socket.inet_pton(family, ip)
return ip
except Exception:
continue
return False
|
Return the preferred Internet protocol. Either 'ipv4' (default) or 'ipv6'.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/openstack.py#L286-L303
|
[
"def get_cloud_config_value(name, vm_, opts, default=None, search_global=True):\n '''\n Search and return a setting in a known order:\n\n 1. In the virtual machine's configuration\n 2. In the virtual machine's profile configuration\n 3. In the virtual machine's provider configuration\n 4. In the salt cloud configuration if global searching is enabled\n 5. Return the provided default\n '''\n\n # As a last resort, return the default\n value = default\n\n if search_global is True and opts.get(name, None) is not None:\n # The setting name exists in the cloud(global) configuration\n value = deepcopy(opts[name])\n\n if vm_ and name:\n # Let's get the value from the profile, if present\n if 'profile' in vm_ and vm_['profile'] is not None:\n if name in opts['profiles'][vm_['profile']]:\n if isinstance(value, dict):\n value.update(opts['profiles'][vm_['profile']][name].copy())\n else:\n value = deepcopy(opts['profiles'][vm_['profile']][name])\n\n # Let's get the value from the provider, if present.\n if ':' in vm_['driver']:\n # The provider is defined as <provider-alias>:<driver-name>\n alias, driver = vm_['driver'].split(':')\n if alias in opts['providers'] and \\\n driver in opts['providers'][alias]:\n details = opts['providers'][alias][driver]\n if name in details:\n if isinstance(value, dict):\n value.update(details[name].copy())\n else:\n value = deepcopy(details[name])\n elif len(opts['providers'].get(vm_['driver'], ())) > 1:\n # The provider is NOT defined as <provider-alias>:<driver-name>\n # and there's more than one entry under the alias.\n # WARN the user!!!!\n log.error(\n \"The '%s' cloud provider definition has more than one \"\n 'entry. Your VM configuration should be specifying the '\n \"provider as 'driver: %s:<driver-engine>'. Since \"\n \"it's not, we're returning the first definition which \"\n 'might not be what you intended.',\n vm_['driver'], vm_['driver']\n )\n\n if vm_['driver'] in opts['providers']:\n # There's only one driver defined for this provider. This is safe.\n alias_defs = opts['providers'].get(vm_['driver'])\n provider_driver_defs = alias_defs[next(iter(list(alias_defs.keys())))]\n if name in provider_driver_defs:\n # The setting name exists in the VM's provider configuration.\n # Return it!\n if isinstance(value, dict):\n value.update(provider_driver_defs[name].copy())\n else:\n value = deepcopy(provider_driver_defs[name])\n\n if name and vm_ and name in vm_:\n # The setting name exists in VM configuration.\n if isinstance(vm_[name], types.GeneratorType):\n value = next(vm_[name], '')\n else:\n if isinstance(value, dict) and isinstance(vm_[name], dict):\n value.update(vm_[name].copy())\n else:\n value = deepcopy(vm_[name])\n\n return value\n"
] |
# -*- coding: utf-8 -*-
'''
Openstack Cloud Driver
======================
:depends: `shade>=1.19.0 <https://pypi.python.org/pypi/shade>`_
OpenStack is an open source project that is in use by a number a cloud
providers, each of which have their own ways of using it.
This OpenStack driver uses a the shade python module which is managed by the
OpenStack Infra team. This module is written to handle all the different
versions of different OpenStack tools for salt, so most commands are just passed
over to the module to handle everything.
Provider
--------
There are two ways to configure providers for this driver. The first one is to
just let shade handle everything, and configure using os-client-config_ and
setting up `/etc/openstack/clouds.yml`.
.. code-block:: yaml
clouds:
democloud:
region_name: RegionOne
auth:
username: 'demo'
password: secret
project_name: 'demo'
auth_url: 'http://openstack/identity'
And then this can be referenced in the salt provider based on the `democloud`
name.
.. code-block:: yaml
myopenstack:
driver: openstack
cloud: democloud
region_name: RegionOne
This allows for just using one configuration for salt-cloud and for any other
openstack tools which are all using `/etc/openstack/clouds.yml`
The other method allows for specifying everything in the provider config,
instead of using the extra configuration file. This will allow for passing
salt-cloud configs only through pillars for minions without having to write a
clouds.yml file on each minion.abs
.. code-block:: yaml
myopenstack:
driver: openstack
region_name: RegionOne
auth:
username: 'demo'
password: secret
project_name: 'demo'
auth_url: 'http://openstack/identity'
Or if you need to use a profile to setup some extra stuff, it can be passed as a
`profile` to use any of the vendor_ config options.
.. code-block:: yaml
myrackspace:
driver: openstack
profile: rackspace
auth:
username: rackusername
api_key: myapikey
region_name: ORD
auth_type: rackspace_apikey
And this will pull in the profile for rackspace and setup all the correct
options for the auth_url and different api versions for services.
Profile
-------
Most of the options for building servers are just passed on to the
create_server_ function from shade.
The salt specific ones are:
- ssh_key_file: The path to the ssh key that should be used to login to the machine to bootstrap it
- ssh_key_file: The name of the keypair in openstack
- userdata_template: The renderer to use if the userdata is a file that is templated. Default: False
- ssh_interface: The interface to use to login for bootstrapping: public_ips, private_ips, floating_ips, fixed_ips
.. code-block:: yaml
centos:
provider: myopenstack
image: CentOS 7
size: ds1G
ssh_key_name: mykey
ssh_key_file: /root/.ssh/id_rsa
This is the minimum setup required.
If metadata is set to make sure that the host has finished setting up the
`wait_for_metadata` can be set.
.. code-block:: yaml
centos:
provider: myopenstack
image: CentOS 7
size: ds1G
ssh_key_name: mykey
ssh_key_file: /root/.ssh/id_rsa
meta:
build_config: rack_user_only
wait_for_metadata:
rax_service_level_automation: Complete
rackconnect_automation_status: DEPLOYED
Anything else from the create_server_ docs can be passed through here.
- **image**: Image dict, name or ID to boot with. image is required
unless boot_volume is given.
- **flavor**: Flavor dict, name or ID to boot onto.
- **auto_ip**: Whether to take actions to find a routable IP for
the server. (defaults to True)
- **ips**: List of IPs to attach to the server (defaults to None)
- **ip_pool**: Name of the network or floating IP pool to get an
address from. (defaults to None)
- **root_volume**: Name or ID of a volume to boot from
(defaults to None - deprecated, use boot_volume)
- **boot_volume**: Name or ID of a volume to boot from
(defaults to None)
- **terminate_volume**: If booting from a volume, whether it should
be deleted when the server is destroyed.
(defaults to False)
- **volumes**: (optional) A list of volumes to attach to the server
- **meta**: (optional) A dict of arbitrary key/value metadata to
store for this server. Both keys and values must be
<=255 characters.
- **files**: (optional, deprecated) A dict of files to overwrite
on the server upon boot. Keys are file names (i.e.
``/etc/passwd``) and values
are the file contents (either as a string or as a
file-like object). A maximum of five entries is allowed,
and each file must be 10k or less.
- **reservation_id**: a UUID for the set of servers being requested.
- **min_count**: (optional extension) The minimum number of
servers to launch.
- **max_count**: (optional extension) The maximum number of
servers to launch.
- **security_groups**: A list of security group names
- **userdata**: user data to pass to be exposed by the metadata
server this can be a file type object as well or a
string.
- **key_name**: (optional extension) name of previously created
keypair to inject into the instance.
- **availability_zone**: Name of the availability zone for instance
placement.
- **block_device_mapping**: (optional) A dict of block
device mappings for this server.
- **block_device_mapping_v2**: (optional) A dict of block
device mappings for this server.
- **nics**: (optional extension) an ordered list of nics to be
added to this server, with information about
connected networks, fixed IPs, port etc.
- **scheduler_hints**: (optional extension) arbitrary key-value pairs
specified by the client to help boot an instance
- **config_drive**: (optional extension) value for config drive
either boolean, or volume-id
- **disk_config**: (optional extension) control how the disk is
partitioned when the server is created. possible
values are 'AUTO' or 'MANUAL'.
- **admin_pass**: (optional extension) add a user supplied admin
password.
- **timeout**: (optional) Seconds to wait, defaults to 60.
See the ``wait`` parameter.
- **reuse_ips**: (optional) Whether to attempt to reuse pre-existing
floating ips should a floating IP be
needed (defaults to True)
- **network**: (optional) Network dict or name or ID to attach the
server to. Mutually exclusive with the nics parameter.
Can also be be a list of network names or IDs or
network dicts.
- **boot_from_volume**: Whether to boot from volume. 'boot_volume'
implies True, but boot_from_volume=True with
no boot_volume is valid and will create a
volume from the image and use that.
- **volume_size**: When booting an image from volume, how big should
the created volume be? Defaults to 50.
- **nat_destination**: Which network should a created floating IP
be attached to, if it's not possible to
infer from the cloud's configuration.
(Optional, defaults to None)
- **group**: ServerGroup dict, name or id to boot the server in.
If a group is provided in both scheduler_hints and in
the group param, the group param will win.
(Optional, defaults to None)
.. note::
If there is anything added, that is not in this list, it can be added to an `extras`
dictionary for the profile, and that will be to the create_server function.
.. _create_server: https://docs.openstack.org/shade/latest/user/usage.html#shade.OpenStackCloud.create_server
.. _vendor: https://docs.openstack.org/os-client-config/latest/user/vendor-support.html
.. _os-client-config: https://docs.openstack.org/os-client-config/latest/user/configuration.html#config-files
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import Python Libs
import copy
import logging
import os
import pprint
import socket
# Import Salt Libs
import salt.utils.versions
import salt.config as config
from salt.ext import six
from salt.exceptions import (
SaltCloudSystemExit,
SaltCloudExecutionTimeout,
SaltCloudExecutionFailure,
SaltCloudConfigError,
)
# Import 3rd-Party Libs
try:
import shade
import shade.openstackcloud
import shade.exc
import os_client_config
HAS_SHADE = (
salt.utils.versions._LooseVersion(shade.__version__) >= salt.utils.versions._LooseVersion('1.19.0'),
'Please install newer version of shade: >= 1.19.0'
)
except ImportError:
HAS_SHADE = (False, 'Install pypi module shade >= 1.19.0')
log = logging.getLogger(__name__)
__virtualname__ = 'openstack'
def __virtual__():
'''
Check for OpenStack dependencies
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return HAS_SHADE
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__, __active_provider_name__ or __virtualname__,
('auth', 'region_name'), log_message=False,
) or config.is_provider_configured(
__opts__, __active_provider_name__ or __virtualname__,
('cloud', 'region_name')
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
deps = {
'shade': shade[0],
'os_client_config': shade[0],
}
return config.check_driver_dependencies(
__virtualname__,
deps
)
def ssh_interface(vm_):
'''
Return the ssh_interface type to connect to. Either 'public_ips' (default)
or 'private_ips'.
'''
return config.get_cloud_config_value('ssh_interface', vm_, __opts__, default='public_ips', search_global=False)
def get_conn():
'''
Return a conn object for the passed VM data
'''
if __active_provider_name__ in __context__:
return __context__[__active_provider_name__]
vm_ = get_configured_provider()
profile = vm_.pop('profile', None)
if profile is not None:
vm_ = __utils__['dictupdate.update'](os_client_config.vendors.get_profile(profile), vm_)
conn = shade.openstackcloud.OpenStackCloud(cloud_config=None, **vm_)
if __active_provider_name__ is not None:
__context__[__active_provider_name__] = conn
return conn
def list_nodes(conn=None, call=None):
'''
Return a list of VMs
CLI Example
.. code-block:: bash
salt-cloud -f list_nodes myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
ret = {}
for node, info in list_nodes_full(conn=conn).items():
for key in ('id', 'name', 'size', 'state', 'private_ips', 'public_ips', 'floating_ips', 'fixed_ips', 'image'):
ret.setdefault(node, {}).setdefault(key, info.get(key))
return ret
def list_nodes_min(conn=None, call=None):
'''
Return a list of VMs with minimal information
CLI Example
.. code-block:: bash
salt-cloud -f list_nodes_min myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_min function must be called with -f or --function.'
)
if conn is None:
conn = get_conn()
ret = {}
for node in conn.list_servers(bare=True):
ret[node.name] = {'id': node.id, 'state': node.status}
return ret
def _get_ips(node, addr_type='public'):
ret = []
for _, interface in node.addresses.items():
for addr in interface:
if addr_type in ('floating', 'fixed') and addr_type == addr.get('OS-EXT-IPS:type'):
ret.append(addr['addr'])
elif addr_type == 'public' and __utils__['cloud.is_public_ip'](addr['addr']):
ret.append(addr['addr'])
elif addr_type == 'private' and not __utils__['cloud.is_public_ip'](addr['addr']):
ret.append(addr['addr'])
return ret
def list_nodes_full(conn=None, call=None):
'''
Return a list of VMs with all the information about them
CLI Example
.. code-block:: bash
salt-cloud -f list_nodes_full myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or --function.'
)
if conn is None:
conn = get_conn()
ret = {}
for node in conn.list_servers(detailed=True):
ret[node.name] = dict(node)
ret[node.name]['id'] = node.id
ret[node.name]['name'] = node.name
ret[node.name]['size'] = node.flavor.name
ret[node.name]['state'] = node.status
ret[node.name]['private_ips'] = _get_ips(node, 'private')
ret[node.name]['public_ips'] = _get_ips(node, 'public')
ret[node.name]['floating_ips'] = _get_ips(node, 'floating')
ret[node.name]['fixed_ips'] = _get_ips(node, 'fixed')
ret[node.name]['image'] = node.image.name
return ret
def list_nodes_select(conn=None, call=None):
'''
Return a list of VMs with the fields from `query.selection`
CLI Example
.. code-block:: bash
salt-cloud -f list_nodes_full myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_select function must be called with -f or --function.'
)
return __utils__['cloud.list_nodes_select'](
list_nodes(conn, 'function'), __opts__['query.selection'], call,
)
def show_instance(name, conn=None, call=None):
'''
Get VM on this OpenStack account
name
name of the instance
CLI Example
.. code-block:: bash
salt-cloud -a show_instance myserver
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
if conn is None:
conn = get_conn()
node = conn.get_server(name, bare=True)
ret = dict(node)
ret['id'] = node.id
ret['name'] = node.name
ret['size'] = conn.get_flavor(node.flavor.id).name
ret['state'] = node.status
ret['private_ips'] = _get_ips(node, 'private')
ret['public_ips'] = _get_ips(node, 'public')
ret['floating_ips'] = _get_ips(node, 'floating')
ret['fixed_ips'] = _get_ips(node, 'fixed')
if isinstance(node.image, six.string_types):
ret['image'] = node.image
else:
ret['image'] = conn.get_image(node.image.id).name
return ret
def avail_images(conn=None, call=None):
'''
List available images for OpenStack
CLI Example
.. code-block:: bash
salt-cloud -f avail_images myopenstack
salt-cloud --list-images myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
if conn is None:
conn = get_conn()
return conn.list_images()
def avail_sizes(conn=None, call=None):
'''
List available sizes for OpenStack
CLI Example
.. code-block:: bash
salt-cloud -f avail_sizes myopenstack
salt-cloud --list-sizes myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
if conn is None:
conn = get_conn()
return conn.list_flavors()
def list_networks(conn=None, call=None):
'''
List networks for OpenStack
CLI Example
.. code-block:: bash
salt-cloud -f list_networks myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_networks function must be called with '
'-f or --function'
)
if conn is None:
conn = get_conn()
return conn.list_networks()
def list_subnets(conn=None, call=None, kwargs=None):
'''
List subnets in a virtual network
network
network to list subnets of
.. code-block:: bash
salt-cloud -f list_subnets myopenstack network=salt-net
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_subnets function must be called with '
'-f or --function.'
)
if conn is None:
conn = get_conn()
if kwargs is None or (isinstance(kwargs, dict) and 'network' not in kwargs):
raise SaltCloudSystemExit(
'A `network` must be specified'
)
return conn.list_subnets(filters={'network': kwargs['network']})
def _clean_create_kwargs(**kwargs):
'''
Sanatize kwargs to be sent to create_server
'''
VALID_OPTS = {
'name': six.string_types,
'image': six.string_types,
'flavor': six.string_types,
'auto_ip': bool,
'ips': list,
'ip_pool': six.string_types,
'root_volume': six.string_types,
'boot_volume': six.string_types,
'terminate_volume': bool,
'volumes': list,
'meta': dict,
'files': dict,
'reservation_id': six.string_types,
'security_groups': list,
'key_name': six.string_types,
'availability_zone': six.string_types,
'block_device_mapping': dict,
'block_device_mapping_v2': dict,
'nics': list,
'scheduler_hints': dict,
'config_drive': bool,
'disk_config': six.string_types, # AUTO or MANUAL
'admin_pass': six.string_types,
'wait': bool,
'timeout': int,
'reuse_ips': bool,
'network': dict,
'boot_from_volume': bool,
'volume_size': int,
'nat_destination': six.string_types,
'group': six.string_types,
'userdata': six.string_types,
}
extra = kwargs.pop('extra', {})
for key, value in six.iteritems(kwargs.copy()):
if key in VALID_OPTS:
if isinstance(value, VALID_OPTS[key]):
continue
log.error('Error %s: %s is not of type %s', key, value, VALID_OPTS[key])
kwargs.pop(key)
return __utils__['dictupdate.update'](kwargs, extra)
def request_instance(vm_, conn=None, call=None):
'''
Request an instance to be built
'''
if call == 'function':
# Technically this function may be called other ways too, but it
# definitely cannot be called with --function.
raise SaltCloudSystemExit(
'The request_instance action must be called with -a or --action.'
)
kwargs = copy.deepcopy(vm_)
log.info('Creating Cloud VM %s', vm_['name'])
__utils__['cloud.check_name'](vm_['name'], 'a-zA-Z0-9._-')
conn = get_conn()
userdata = config.get_cloud_config_value(
'userdata', vm_, __opts__, search_global=False, default=None
)
if userdata is not None and os.path.isfile(userdata):
try:
with __utils__['files.fopen'](userdata, 'r') as fp_:
kwargs['userdata'] = __utils__['cloud.userdata_template'](
__opts__, vm_, fp_.read()
)
except Exception as exc:
log.exception(
'Failed to read userdata from %s: %s', userdata, exc)
if 'size' in kwargs:
kwargs['flavor'] = kwargs.pop('size')
kwargs['key_name'] = config.get_cloud_config_value(
'ssh_key_name', vm_, __opts__, search_global=False, default=None
)
kwargs['wait'] = True
try:
conn.create_server(**_clean_create_kwargs(**kwargs))
except shade.exc.OpenStackCloudException as exc:
log.error('Error creating server %s: %s', vm_['name'], exc)
destroy(vm_['name'], conn=conn, call='action')
raise SaltCloudSystemExit(six.text_type(exc))
return show_instance(vm_['name'], conn=conn, call='action')
def create(vm_):
'''
Create a single VM from a data dict
'''
deploy = config.get_cloud_config_value('deploy', vm_, __opts__)
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 ssh_key_file \'{0}\' does not exist'.format(
key_filename
)
)
vm_['key_filename'] = key_filename
__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']
)
conn = get_conn()
if 'instance_id' in vm_:
# This was probably created via another process, and doesn't have
# things like salt keys created yet, so let's create them now.
if 'pub_key' not in vm_ and 'priv_key' not in vm_:
log.debug('Generating minion keys for \'%s\'', vm_['name'])
vm_['priv_key'], vm_['pub_key'] = __utils__['cloud.gen_keys'](
config.get_cloud_config_value(
'keysize',
vm_,
__opts__
)
)
else:
# Put together all of the information required to request the instance,
# and then fire off the request for it
request_instance(conn=conn, call='action', vm_=vm_)
data = show_instance(vm_.get('instance_id', vm_['name']), conn=conn, call='action')
log.debug('VM is now running')
def __query_node(vm_):
data = show_instance(vm_['name'], conn=conn, call='action')
if 'wait_for_metadata' in vm_:
for key, value in six.iteritems(vm_.get('wait_for_metadata', {})):
log.debug('Waiting for metadata: %s=%s', key, value)
if data['metadata'].get(key, None) != value:
log.debug('Metadata is not ready: %s=%s', key, data['metadata'].get(key))
return False
return preferred_ip(vm_, data[ssh_interface(vm_)])
try:
ip_address = __utils__['cloud.wait_for_fun'](
__query_node,
vm_=vm_
)
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))
log.debug('Using IP address %s', ip_address)
salt_interface = __utils__['cloud.get_salt_interface'](vm_, __opts__)
salt_ip_address = preferred_ip(vm_, data[salt_interface])
log.debug('Salt interface set to: %s', salt_ip_address)
if not ip_address:
raise SaltCloudSystemExit('A valid IP address was not found')
vm_['ssh_host'] = ip_address
vm_['salt_host'] = salt_ip_address
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)
)
event_data = {
'name': vm_['name'],
'profile': vm_['profile'],
'provider': vm_['driver'],
'instance_id': data['id'],
'floating_ips': data['floating_ips'],
'fixed_ips': data['fixed_ips'],
'private_ips': data['private_ips'],
'public_ips': data['public_ips'],
}
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args=__utils__['cloud.filter_event']('created', event_data, list(event_data)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
__utils__['cloud.cachedir_index_add'](vm_['name'], vm_['profile'], 'nova', vm_['driver'])
return ret
def destroy(name, conn=None, call=None):
'''
Delete a single VM
'''
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']
)
if not conn:
conn = get_conn()
node = show_instance(name, conn=conn, call='action')
log.info('Destroying VM: %s', name)
ret = conn.delete_server(name)
if ret:
log.info('Destroyed VM: %s', name)
# Fire destroy action
__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('delete_sshkeys', False) is True:
__utils__['cloud.remove_sshkey'](getattr(node, __opts__.get('ssh_interface', 'public_ips'))[0])
if __opts__.get('update_cachedir', False) is True:
__utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__)
__utils__['cloud.cachedir_index_del'](name)
return True
log.error('Failed to Destroy VM: %s', name)
return False
def call(conn=None, call=None, kwargs=None):
'''
Call function from shade.
func
function to call from shade.openstackcloud library
CLI Example
.. code-block:: bash
salt-cloud -f call myopenstack func=list_images
t sujksalt-cloud -f call myopenstack func=create_network name=mysubnet
'''
if call == 'action':
raise SaltCloudSystemExit(
'The call function must be called with '
'-f or --function.'
)
if 'func' not in kwargs:
raise SaltCloudSystemExit(
'No `func` argument passed'
)
if conn is None:
conn = get_conn()
func = kwargs.pop('func')
for key, value in kwargs.items():
try:
kwargs[key] = __utils__['json.loads'](value)
except ValueError:
continue
try:
return getattr(conn, func)(**kwargs)
except shade.exc.OpenStackCloudException as exc:
log.error('Error running %s: %s', func, exc)
raise SaltCloudSystemExit(six.text_type(exc))
|
saltstack/salt
|
salt/cloud/clouds/openstack.py
|
get_conn
|
python
|
def get_conn():
'''
Return a conn object for the passed VM data
'''
if __active_provider_name__ in __context__:
return __context__[__active_provider_name__]
vm_ = get_configured_provider()
profile = vm_.pop('profile', None)
if profile is not None:
vm_ = __utils__['dictupdate.update'](os_client_config.vendors.get_profile(profile), vm_)
conn = shade.openstackcloud.OpenStackCloud(cloud_config=None, **vm_)
if __active_provider_name__ is not None:
__context__[__active_provider_name__] = conn
return conn
|
Return a conn object for the passed VM data
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/openstack.py#L314-L327
|
[
"def get_configured_provider():\n '''\n Return the first configured instance.\n '''\n return config.is_provider_configured(\n __opts__, __active_provider_name__ or __virtualname__,\n ('auth', 'region_name'), log_message=False,\n ) or config.is_provider_configured(\n __opts__, __active_provider_name__ or __virtualname__,\n ('cloud', 'region_name')\n )\n"
] |
# -*- coding: utf-8 -*-
'''
Openstack Cloud Driver
======================
:depends: `shade>=1.19.0 <https://pypi.python.org/pypi/shade>`_
OpenStack is an open source project that is in use by a number a cloud
providers, each of which have their own ways of using it.
This OpenStack driver uses a the shade python module which is managed by the
OpenStack Infra team. This module is written to handle all the different
versions of different OpenStack tools for salt, so most commands are just passed
over to the module to handle everything.
Provider
--------
There are two ways to configure providers for this driver. The first one is to
just let shade handle everything, and configure using os-client-config_ and
setting up `/etc/openstack/clouds.yml`.
.. code-block:: yaml
clouds:
democloud:
region_name: RegionOne
auth:
username: 'demo'
password: secret
project_name: 'demo'
auth_url: 'http://openstack/identity'
And then this can be referenced in the salt provider based on the `democloud`
name.
.. code-block:: yaml
myopenstack:
driver: openstack
cloud: democloud
region_name: RegionOne
This allows for just using one configuration for salt-cloud and for any other
openstack tools which are all using `/etc/openstack/clouds.yml`
The other method allows for specifying everything in the provider config,
instead of using the extra configuration file. This will allow for passing
salt-cloud configs only through pillars for minions without having to write a
clouds.yml file on each minion.abs
.. code-block:: yaml
myopenstack:
driver: openstack
region_name: RegionOne
auth:
username: 'demo'
password: secret
project_name: 'demo'
auth_url: 'http://openstack/identity'
Or if you need to use a profile to setup some extra stuff, it can be passed as a
`profile` to use any of the vendor_ config options.
.. code-block:: yaml
myrackspace:
driver: openstack
profile: rackspace
auth:
username: rackusername
api_key: myapikey
region_name: ORD
auth_type: rackspace_apikey
And this will pull in the profile for rackspace and setup all the correct
options for the auth_url and different api versions for services.
Profile
-------
Most of the options for building servers are just passed on to the
create_server_ function from shade.
The salt specific ones are:
- ssh_key_file: The path to the ssh key that should be used to login to the machine to bootstrap it
- ssh_key_file: The name of the keypair in openstack
- userdata_template: The renderer to use if the userdata is a file that is templated. Default: False
- ssh_interface: The interface to use to login for bootstrapping: public_ips, private_ips, floating_ips, fixed_ips
.. code-block:: yaml
centos:
provider: myopenstack
image: CentOS 7
size: ds1G
ssh_key_name: mykey
ssh_key_file: /root/.ssh/id_rsa
This is the minimum setup required.
If metadata is set to make sure that the host has finished setting up the
`wait_for_metadata` can be set.
.. code-block:: yaml
centos:
provider: myopenstack
image: CentOS 7
size: ds1G
ssh_key_name: mykey
ssh_key_file: /root/.ssh/id_rsa
meta:
build_config: rack_user_only
wait_for_metadata:
rax_service_level_automation: Complete
rackconnect_automation_status: DEPLOYED
Anything else from the create_server_ docs can be passed through here.
- **image**: Image dict, name or ID to boot with. image is required
unless boot_volume is given.
- **flavor**: Flavor dict, name or ID to boot onto.
- **auto_ip**: Whether to take actions to find a routable IP for
the server. (defaults to True)
- **ips**: List of IPs to attach to the server (defaults to None)
- **ip_pool**: Name of the network or floating IP pool to get an
address from. (defaults to None)
- **root_volume**: Name or ID of a volume to boot from
(defaults to None - deprecated, use boot_volume)
- **boot_volume**: Name or ID of a volume to boot from
(defaults to None)
- **terminate_volume**: If booting from a volume, whether it should
be deleted when the server is destroyed.
(defaults to False)
- **volumes**: (optional) A list of volumes to attach to the server
- **meta**: (optional) A dict of arbitrary key/value metadata to
store for this server. Both keys and values must be
<=255 characters.
- **files**: (optional, deprecated) A dict of files to overwrite
on the server upon boot. Keys are file names (i.e.
``/etc/passwd``) and values
are the file contents (either as a string or as a
file-like object). A maximum of five entries is allowed,
and each file must be 10k or less.
- **reservation_id**: a UUID for the set of servers being requested.
- **min_count**: (optional extension) The minimum number of
servers to launch.
- **max_count**: (optional extension) The maximum number of
servers to launch.
- **security_groups**: A list of security group names
- **userdata**: user data to pass to be exposed by the metadata
server this can be a file type object as well or a
string.
- **key_name**: (optional extension) name of previously created
keypair to inject into the instance.
- **availability_zone**: Name of the availability zone for instance
placement.
- **block_device_mapping**: (optional) A dict of block
device mappings for this server.
- **block_device_mapping_v2**: (optional) A dict of block
device mappings for this server.
- **nics**: (optional extension) an ordered list of nics to be
added to this server, with information about
connected networks, fixed IPs, port etc.
- **scheduler_hints**: (optional extension) arbitrary key-value pairs
specified by the client to help boot an instance
- **config_drive**: (optional extension) value for config drive
either boolean, or volume-id
- **disk_config**: (optional extension) control how the disk is
partitioned when the server is created. possible
values are 'AUTO' or 'MANUAL'.
- **admin_pass**: (optional extension) add a user supplied admin
password.
- **timeout**: (optional) Seconds to wait, defaults to 60.
See the ``wait`` parameter.
- **reuse_ips**: (optional) Whether to attempt to reuse pre-existing
floating ips should a floating IP be
needed (defaults to True)
- **network**: (optional) Network dict or name or ID to attach the
server to. Mutually exclusive with the nics parameter.
Can also be be a list of network names or IDs or
network dicts.
- **boot_from_volume**: Whether to boot from volume. 'boot_volume'
implies True, but boot_from_volume=True with
no boot_volume is valid and will create a
volume from the image and use that.
- **volume_size**: When booting an image from volume, how big should
the created volume be? Defaults to 50.
- **nat_destination**: Which network should a created floating IP
be attached to, if it's not possible to
infer from the cloud's configuration.
(Optional, defaults to None)
- **group**: ServerGroup dict, name or id to boot the server in.
If a group is provided in both scheduler_hints and in
the group param, the group param will win.
(Optional, defaults to None)
.. note::
If there is anything added, that is not in this list, it can be added to an `extras`
dictionary for the profile, and that will be to the create_server function.
.. _create_server: https://docs.openstack.org/shade/latest/user/usage.html#shade.OpenStackCloud.create_server
.. _vendor: https://docs.openstack.org/os-client-config/latest/user/vendor-support.html
.. _os-client-config: https://docs.openstack.org/os-client-config/latest/user/configuration.html#config-files
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import Python Libs
import copy
import logging
import os
import pprint
import socket
# Import Salt Libs
import salt.utils.versions
import salt.config as config
from salt.ext import six
from salt.exceptions import (
SaltCloudSystemExit,
SaltCloudExecutionTimeout,
SaltCloudExecutionFailure,
SaltCloudConfigError,
)
# Import 3rd-Party Libs
try:
import shade
import shade.openstackcloud
import shade.exc
import os_client_config
HAS_SHADE = (
salt.utils.versions._LooseVersion(shade.__version__) >= salt.utils.versions._LooseVersion('1.19.0'),
'Please install newer version of shade: >= 1.19.0'
)
except ImportError:
HAS_SHADE = (False, 'Install pypi module shade >= 1.19.0')
log = logging.getLogger(__name__)
__virtualname__ = 'openstack'
def __virtual__():
'''
Check for OpenStack dependencies
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return HAS_SHADE
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__, __active_provider_name__ or __virtualname__,
('auth', 'region_name'), log_message=False,
) or config.is_provider_configured(
__opts__, __active_provider_name__ or __virtualname__,
('cloud', 'region_name')
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
deps = {
'shade': shade[0],
'os_client_config': shade[0],
}
return config.check_driver_dependencies(
__virtualname__,
deps
)
def preferred_ip(vm_, ips):
'''
Return the preferred Internet protocol. Either 'ipv4' (default) or 'ipv6'.
'''
proto = config.get_cloud_config_value(
'protocol', vm_, __opts__, default='ipv4', search_global=False
)
family = socket.AF_INET
if proto == 'ipv6':
family = socket.AF_INET6
for ip in ips:
try:
socket.inet_pton(family, ip)
return ip
except Exception:
continue
return False
def ssh_interface(vm_):
'''
Return the ssh_interface type to connect to. Either 'public_ips' (default)
or 'private_ips'.
'''
return config.get_cloud_config_value('ssh_interface', vm_, __opts__, default='public_ips', search_global=False)
def list_nodes(conn=None, call=None):
'''
Return a list of VMs
CLI Example
.. code-block:: bash
salt-cloud -f list_nodes myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
ret = {}
for node, info in list_nodes_full(conn=conn).items():
for key in ('id', 'name', 'size', 'state', 'private_ips', 'public_ips', 'floating_ips', 'fixed_ips', 'image'):
ret.setdefault(node, {}).setdefault(key, info.get(key))
return ret
def list_nodes_min(conn=None, call=None):
'''
Return a list of VMs with minimal information
CLI Example
.. code-block:: bash
salt-cloud -f list_nodes_min myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_min function must be called with -f or --function.'
)
if conn is None:
conn = get_conn()
ret = {}
for node in conn.list_servers(bare=True):
ret[node.name] = {'id': node.id, 'state': node.status}
return ret
def _get_ips(node, addr_type='public'):
ret = []
for _, interface in node.addresses.items():
for addr in interface:
if addr_type in ('floating', 'fixed') and addr_type == addr.get('OS-EXT-IPS:type'):
ret.append(addr['addr'])
elif addr_type == 'public' and __utils__['cloud.is_public_ip'](addr['addr']):
ret.append(addr['addr'])
elif addr_type == 'private' and not __utils__['cloud.is_public_ip'](addr['addr']):
ret.append(addr['addr'])
return ret
def list_nodes_full(conn=None, call=None):
'''
Return a list of VMs with all the information about them
CLI Example
.. code-block:: bash
salt-cloud -f list_nodes_full myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or --function.'
)
if conn is None:
conn = get_conn()
ret = {}
for node in conn.list_servers(detailed=True):
ret[node.name] = dict(node)
ret[node.name]['id'] = node.id
ret[node.name]['name'] = node.name
ret[node.name]['size'] = node.flavor.name
ret[node.name]['state'] = node.status
ret[node.name]['private_ips'] = _get_ips(node, 'private')
ret[node.name]['public_ips'] = _get_ips(node, 'public')
ret[node.name]['floating_ips'] = _get_ips(node, 'floating')
ret[node.name]['fixed_ips'] = _get_ips(node, 'fixed')
ret[node.name]['image'] = node.image.name
return ret
def list_nodes_select(conn=None, call=None):
'''
Return a list of VMs with the fields from `query.selection`
CLI Example
.. code-block:: bash
salt-cloud -f list_nodes_full myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_select function must be called with -f or --function.'
)
return __utils__['cloud.list_nodes_select'](
list_nodes(conn, 'function'), __opts__['query.selection'], call,
)
def show_instance(name, conn=None, call=None):
'''
Get VM on this OpenStack account
name
name of the instance
CLI Example
.. code-block:: bash
salt-cloud -a show_instance myserver
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
if conn is None:
conn = get_conn()
node = conn.get_server(name, bare=True)
ret = dict(node)
ret['id'] = node.id
ret['name'] = node.name
ret['size'] = conn.get_flavor(node.flavor.id).name
ret['state'] = node.status
ret['private_ips'] = _get_ips(node, 'private')
ret['public_ips'] = _get_ips(node, 'public')
ret['floating_ips'] = _get_ips(node, 'floating')
ret['fixed_ips'] = _get_ips(node, 'fixed')
if isinstance(node.image, six.string_types):
ret['image'] = node.image
else:
ret['image'] = conn.get_image(node.image.id).name
return ret
def avail_images(conn=None, call=None):
'''
List available images for OpenStack
CLI Example
.. code-block:: bash
salt-cloud -f avail_images myopenstack
salt-cloud --list-images myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
if conn is None:
conn = get_conn()
return conn.list_images()
def avail_sizes(conn=None, call=None):
'''
List available sizes for OpenStack
CLI Example
.. code-block:: bash
salt-cloud -f avail_sizes myopenstack
salt-cloud --list-sizes myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
if conn is None:
conn = get_conn()
return conn.list_flavors()
def list_networks(conn=None, call=None):
'''
List networks for OpenStack
CLI Example
.. code-block:: bash
salt-cloud -f list_networks myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_networks function must be called with '
'-f or --function'
)
if conn is None:
conn = get_conn()
return conn.list_networks()
def list_subnets(conn=None, call=None, kwargs=None):
'''
List subnets in a virtual network
network
network to list subnets of
.. code-block:: bash
salt-cloud -f list_subnets myopenstack network=salt-net
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_subnets function must be called with '
'-f or --function.'
)
if conn is None:
conn = get_conn()
if kwargs is None or (isinstance(kwargs, dict) and 'network' not in kwargs):
raise SaltCloudSystemExit(
'A `network` must be specified'
)
return conn.list_subnets(filters={'network': kwargs['network']})
def _clean_create_kwargs(**kwargs):
'''
Sanatize kwargs to be sent to create_server
'''
VALID_OPTS = {
'name': six.string_types,
'image': six.string_types,
'flavor': six.string_types,
'auto_ip': bool,
'ips': list,
'ip_pool': six.string_types,
'root_volume': six.string_types,
'boot_volume': six.string_types,
'terminate_volume': bool,
'volumes': list,
'meta': dict,
'files': dict,
'reservation_id': six.string_types,
'security_groups': list,
'key_name': six.string_types,
'availability_zone': six.string_types,
'block_device_mapping': dict,
'block_device_mapping_v2': dict,
'nics': list,
'scheduler_hints': dict,
'config_drive': bool,
'disk_config': six.string_types, # AUTO or MANUAL
'admin_pass': six.string_types,
'wait': bool,
'timeout': int,
'reuse_ips': bool,
'network': dict,
'boot_from_volume': bool,
'volume_size': int,
'nat_destination': six.string_types,
'group': six.string_types,
'userdata': six.string_types,
}
extra = kwargs.pop('extra', {})
for key, value in six.iteritems(kwargs.copy()):
if key in VALID_OPTS:
if isinstance(value, VALID_OPTS[key]):
continue
log.error('Error %s: %s is not of type %s', key, value, VALID_OPTS[key])
kwargs.pop(key)
return __utils__['dictupdate.update'](kwargs, extra)
def request_instance(vm_, conn=None, call=None):
'''
Request an instance to be built
'''
if call == 'function':
# Technically this function may be called other ways too, but it
# definitely cannot be called with --function.
raise SaltCloudSystemExit(
'The request_instance action must be called with -a or --action.'
)
kwargs = copy.deepcopy(vm_)
log.info('Creating Cloud VM %s', vm_['name'])
__utils__['cloud.check_name'](vm_['name'], 'a-zA-Z0-9._-')
conn = get_conn()
userdata = config.get_cloud_config_value(
'userdata', vm_, __opts__, search_global=False, default=None
)
if userdata is not None and os.path.isfile(userdata):
try:
with __utils__['files.fopen'](userdata, 'r') as fp_:
kwargs['userdata'] = __utils__['cloud.userdata_template'](
__opts__, vm_, fp_.read()
)
except Exception as exc:
log.exception(
'Failed to read userdata from %s: %s', userdata, exc)
if 'size' in kwargs:
kwargs['flavor'] = kwargs.pop('size')
kwargs['key_name'] = config.get_cloud_config_value(
'ssh_key_name', vm_, __opts__, search_global=False, default=None
)
kwargs['wait'] = True
try:
conn.create_server(**_clean_create_kwargs(**kwargs))
except shade.exc.OpenStackCloudException as exc:
log.error('Error creating server %s: %s', vm_['name'], exc)
destroy(vm_['name'], conn=conn, call='action')
raise SaltCloudSystemExit(six.text_type(exc))
return show_instance(vm_['name'], conn=conn, call='action')
def create(vm_):
'''
Create a single VM from a data dict
'''
deploy = config.get_cloud_config_value('deploy', vm_, __opts__)
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 ssh_key_file \'{0}\' does not exist'.format(
key_filename
)
)
vm_['key_filename'] = key_filename
__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']
)
conn = get_conn()
if 'instance_id' in vm_:
# This was probably created via another process, and doesn't have
# things like salt keys created yet, so let's create them now.
if 'pub_key' not in vm_ and 'priv_key' not in vm_:
log.debug('Generating minion keys for \'%s\'', vm_['name'])
vm_['priv_key'], vm_['pub_key'] = __utils__['cloud.gen_keys'](
config.get_cloud_config_value(
'keysize',
vm_,
__opts__
)
)
else:
# Put together all of the information required to request the instance,
# and then fire off the request for it
request_instance(conn=conn, call='action', vm_=vm_)
data = show_instance(vm_.get('instance_id', vm_['name']), conn=conn, call='action')
log.debug('VM is now running')
def __query_node(vm_):
data = show_instance(vm_['name'], conn=conn, call='action')
if 'wait_for_metadata' in vm_:
for key, value in six.iteritems(vm_.get('wait_for_metadata', {})):
log.debug('Waiting for metadata: %s=%s', key, value)
if data['metadata'].get(key, None) != value:
log.debug('Metadata is not ready: %s=%s', key, data['metadata'].get(key))
return False
return preferred_ip(vm_, data[ssh_interface(vm_)])
try:
ip_address = __utils__['cloud.wait_for_fun'](
__query_node,
vm_=vm_
)
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))
log.debug('Using IP address %s', ip_address)
salt_interface = __utils__['cloud.get_salt_interface'](vm_, __opts__)
salt_ip_address = preferred_ip(vm_, data[salt_interface])
log.debug('Salt interface set to: %s', salt_ip_address)
if not ip_address:
raise SaltCloudSystemExit('A valid IP address was not found')
vm_['ssh_host'] = ip_address
vm_['salt_host'] = salt_ip_address
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)
)
event_data = {
'name': vm_['name'],
'profile': vm_['profile'],
'provider': vm_['driver'],
'instance_id': data['id'],
'floating_ips': data['floating_ips'],
'fixed_ips': data['fixed_ips'],
'private_ips': data['private_ips'],
'public_ips': data['public_ips'],
}
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args=__utils__['cloud.filter_event']('created', event_data, list(event_data)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
__utils__['cloud.cachedir_index_add'](vm_['name'], vm_['profile'], 'nova', vm_['driver'])
return ret
def destroy(name, conn=None, call=None):
'''
Delete a single VM
'''
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']
)
if not conn:
conn = get_conn()
node = show_instance(name, conn=conn, call='action')
log.info('Destroying VM: %s', name)
ret = conn.delete_server(name)
if ret:
log.info('Destroyed VM: %s', name)
# Fire destroy action
__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('delete_sshkeys', False) is True:
__utils__['cloud.remove_sshkey'](getattr(node, __opts__.get('ssh_interface', 'public_ips'))[0])
if __opts__.get('update_cachedir', False) is True:
__utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__)
__utils__['cloud.cachedir_index_del'](name)
return True
log.error('Failed to Destroy VM: %s', name)
return False
def call(conn=None, call=None, kwargs=None):
'''
Call function from shade.
func
function to call from shade.openstackcloud library
CLI Example
.. code-block:: bash
salt-cloud -f call myopenstack func=list_images
t sujksalt-cloud -f call myopenstack func=create_network name=mysubnet
'''
if call == 'action':
raise SaltCloudSystemExit(
'The call function must be called with '
'-f or --function.'
)
if 'func' not in kwargs:
raise SaltCloudSystemExit(
'No `func` argument passed'
)
if conn is None:
conn = get_conn()
func = kwargs.pop('func')
for key, value in kwargs.items():
try:
kwargs[key] = __utils__['json.loads'](value)
except ValueError:
continue
try:
return getattr(conn, func)(**kwargs)
except shade.exc.OpenStackCloudException as exc:
log.error('Error running %s: %s', func, exc)
raise SaltCloudSystemExit(six.text_type(exc))
|
saltstack/salt
|
salt/cloud/clouds/openstack.py
|
list_nodes
|
python
|
def list_nodes(conn=None, call=None):
'''
Return a list of VMs
CLI Example
.. code-block:: bash
salt-cloud -f list_nodes myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
ret = {}
for node, info in list_nodes_full(conn=conn).items():
for key in ('id', 'name', 'size', 'state', 'private_ips', 'public_ips', 'floating_ips', 'fixed_ips', 'image'):
ret.setdefault(node, {}).setdefault(key, info.get(key))
return ret
|
Return a list of VMs
CLI Example
.. code-block:: bash
salt-cloud -f list_nodes myopenstack
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/openstack.py#L330-L350
|
[
"def list_nodes_full(conn=None, call=None):\n '''\n Return a list of VMs with all the information about them\n\n CLI Example\n\n .. code-block:: bash\n\n salt-cloud -f list_nodes_full myopenstack\n\n '''\n if call == 'action':\n raise SaltCloudSystemExit(\n 'The list_nodes_full function must be called with -f or --function.'\n )\n if conn is None:\n conn = get_conn()\n ret = {}\n for node in conn.list_servers(detailed=True):\n ret[node.name] = dict(node)\n ret[node.name]['id'] = node.id\n ret[node.name]['name'] = node.name\n ret[node.name]['size'] = node.flavor.name\n ret[node.name]['state'] = node.status\n ret[node.name]['private_ips'] = _get_ips(node, 'private')\n ret[node.name]['public_ips'] = _get_ips(node, 'public')\n ret[node.name]['floating_ips'] = _get_ips(node, 'floating')\n ret[node.name]['fixed_ips'] = _get_ips(node, 'fixed')\n ret[node.name]['image'] = node.image.name\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Openstack Cloud Driver
======================
:depends: `shade>=1.19.0 <https://pypi.python.org/pypi/shade>`_
OpenStack is an open source project that is in use by a number a cloud
providers, each of which have their own ways of using it.
This OpenStack driver uses a the shade python module which is managed by the
OpenStack Infra team. This module is written to handle all the different
versions of different OpenStack tools for salt, so most commands are just passed
over to the module to handle everything.
Provider
--------
There are two ways to configure providers for this driver. The first one is to
just let shade handle everything, and configure using os-client-config_ and
setting up `/etc/openstack/clouds.yml`.
.. code-block:: yaml
clouds:
democloud:
region_name: RegionOne
auth:
username: 'demo'
password: secret
project_name: 'demo'
auth_url: 'http://openstack/identity'
And then this can be referenced in the salt provider based on the `democloud`
name.
.. code-block:: yaml
myopenstack:
driver: openstack
cloud: democloud
region_name: RegionOne
This allows for just using one configuration for salt-cloud and for any other
openstack tools which are all using `/etc/openstack/clouds.yml`
The other method allows for specifying everything in the provider config,
instead of using the extra configuration file. This will allow for passing
salt-cloud configs only through pillars for minions without having to write a
clouds.yml file on each minion.abs
.. code-block:: yaml
myopenstack:
driver: openstack
region_name: RegionOne
auth:
username: 'demo'
password: secret
project_name: 'demo'
auth_url: 'http://openstack/identity'
Or if you need to use a profile to setup some extra stuff, it can be passed as a
`profile` to use any of the vendor_ config options.
.. code-block:: yaml
myrackspace:
driver: openstack
profile: rackspace
auth:
username: rackusername
api_key: myapikey
region_name: ORD
auth_type: rackspace_apikey
And this will pull in the profile for rackspace and setup all the correct
options for the auth_url and different api versions for services.
Profile
-------
Most of the options for building servers are just passed on to the
create_server_ function from shade.
The salt specific ones are:
- ssh_key_file: The path to the ssh key that should be used to login to the machine to bootstrap it
- ssh_key_file: The name of the keypair in openstack
- userdata_template: The renderer to use if the userdata is a file that is templated. Default: False
- ssh_interface: The interface to use to login for bootstrapping: public_ips, private_ips, floating_ips, fixed_ips
.. code-block:: yaml
centos:
provider: myopenstack
image: CentOS 7
size: ds1G
ssh_key_name: mykey
ssh_key_file: /root/.ssh/id_rsa
This is the minimum setup required.
If metadata is set to make sure that the host has finished setting up the
`wait_for_metadata` can be set.
.. code-block:: yaml
centos:
provider: myopenstack
image: CentOS 7
size: ds1G
ssh_key_name: mykey
ssh_key_file: /root/.ssh/id_rsa
meta:
build_config: rack_user_only
wait_for_metadata:
rax_service_level_automation: Complete
rackconnect_automation_status: DEPLOYED
Anything else from the create_server_ docs can be passed through here.
- **image**: Image dict, name or ID to boot with. image is required
unless boot_volume is given.
- **flavor**: Flavor dict, name or ID to boot onto.
- **auto_ip**: Whether to take actions to find a routable IP for
the server. (defaults to True)
- **ips**: List of IPs to attach to the server (defaults to None)
- **ip_pool**: Name of the network or floating IP pool to get an
address from. (defaults to None)
- **root_volume**: Name or ID of a volume to boot from
(defaults to None - deprecated, use boot_volume)
- **boot_volume**: Name or ID of a volume to boot from
(defaults to None)
- **terminate_volume**: If booting from a volume, whether it should
be deleted when the server is destroyed.
(defaults to False)
- **volumes**: (optional) A list of volumes to attach to the server
- **meta**: (optional) A dict of arbitrary key/value metadata to
store for this server. Both keys and values must be
<=255 characters.
- **files**: (optional, deprecated) A dict of files to overwrite
on the server upon boot. Keys are file names (i.e.
``/etc/passwd``) and values
are the file contents (either as a string or as a
file-like object). A maximum of five entries is allowed,
and each file must be 10k or less.
- **reservation_id**: a UUID for the set of servers being requested.
- **min_count**: (optional extension) The minimum number of
servers to launch.
- **max_count**: (optional extension) The maximum number of
servers to launch.
- **security_groups**: A list of security group names
- **userdata**: user data to pass to be exposed by the metadata
server this can be a file type object as well or a
string.
- **key_name**: (optional extension) name of previously created
keypair to inject into the instance.
- **availability_zone**: Name of the availability zone for instance
placement.
- **block_device_mapping**: (optional) A dict of block
device mappings for this server.
- **block_device_mapping_v2**: (optional) A dict of block
device mappings for this server.
- **nics**: (optional extension) an ordered list of nics to be
added to this server, with information about
connected networks, fixed IPs, port etc.
- **scheduler_hints**: (optional extension) arbitrary key-value pairs
specified by the client to help boot an instance
- **config_drive**: (optional extension) value for config drive
either boolean, or volume-id
- **disk_config**: (optional extension) control how the disk is
partitioned when the server is created. possible
values are 'AUTO' or 'MANUAL'.
- **admin_pass**: (optional extension) add a user supplied admin
password.
- **timeout**: (optional) Seconds to wait, defaults to 60.
See the ``wait`` parameter.
- **reuse_ips**: (optional) Whether to attempt to reuse pre-existing
floating ips should a floating IP be
needed (defaults to True)
- **network**: (optional) Network dict or name or ID to attach the
server to. Mutually exclusive with the nics parameter.
Can also be be a list of network names or IDs or
network dicts.
- **boot_from_volume**: Whether to boot from volume. 'boot_volume'
implies True, but boot_from_volume=True with
no boot_volume is valid and will create a
volume from the image and use that.
- **volume_size**: When booting an image from volume, how big should
the created volume be? Defaults to 50.
- **nat_destination**: Which network should a created floating IP
be attached to, if it's not possible to
infer from the cloud's configuration.
(Optional, defaults to None)
- **group**: ServerGroup dict, name or id to boot the server in.
If a group is provided in both scheduler_hints and in
the group param, the group param will win.
(Optional, defaults to None)
.. note::
If there is anything added, that is not in this list, it can be added to an `extras`
dictionary for the profile, and that will be to the create_server function.
.. _create_server: https://docs.openstack.org/shade/latest/user/usage.html#shade.OpenStackCloud.create_server
.. _vendor: https://docs.openstack.org/os-client-config/latest/user/vendor-support.html
.. _os-client-config: https://docs.openstack.org/os-client-config/latest/user/configuration.html#config-files
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import Python Libs
import copy
import logging
import os
import pprint
import socket
# Import Salt Libs
import salt.utils.versions
import salt.config as config
from salt.ext import six
from salt.exceptions import (
SaltCloudSystemExit,
SaltCloudExecutionTimeout,
SaltCloudExecutionFailure,
SaltCloudConfigError,
)
# Import 3rd-Party Libs
try:
import shade
import shade.openstackcloud
import shade.exc
import os_client_config
HAS_SHADE = (
salt.utils.versions._LooseVersion(shade.__version__) >= salt.utils.versions._LooseVersion('1.19.0'),
'Please install newer version of shade: >= 1.19.0'
)
except ImportError:
HAS_SHADE = (False, 'Install pypi module shade >= 1.19.0')
log = logging.getLogger(__name__)
__virtualname__ = 'openstack'
def __virtual__():
'''
Check for OpenStack dependencies
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return HAS_SHADE
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__, __active_provider_name__ or __virtualname__,
('auth', 'region_name'), log_message=False,
) or config.is_provider_configured(
__opts__, __active_provider_name__ or __virtualname__,
('cloud', 'region_name')
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
deps = {
'shade': shade[0],
'os_client_config': shade[0],
}
return config.check_driver_dependencies(
__virtualname__,
deps
)
def preferred_ip(vm_, ips):
'''
Return the preferred Internet protocol. Either 'ipv4' (default) or 'ipv6'.
'''
proto = config.get_cloud_config_value(
'protocol', vm_, __opts__, default='ipv4', search_global=False
)
family = socket.AF_INET
if proto == 'ipv6':
family = socket.AF_INET6
for ip in ips:
try:
socket.inet_pton(family, ip)
return ip
except Exception:
continue
return False
def ssh_interface(vm_):
'''
Return the ssh_interface type to connect to. Either 'public_ips' (default)
or 'private_ips'.
'''
return config.get_cloud_config_value('ssh_interface', vm_, __opts__, default='public_ips', search_global=False)
def get_conn():
'''
Return a conn object for the passed VM data
'''
if __active_provider_name__ in __context__:
return __context__[__active_provider_name__]
vm_ = get_configured_provider()
profile = vm_.pop('profile', None)
if profile is not None:
vm_ = __utils__['dictupdate.update'](os_client_config.vendors.get_profile(profile), vm_)
conn = shade.openstackcloud.OpenStackCloud(cloud_config=None, **vm_)
if __active_provider_name__ is not None:
__context__[__active_provider_name__] = conn
return conn
def list_nodes_min(conn=None, call=None):
'''
Return a list of VMs with minimal information
CLI Example
.. code-block:: bash
salt-cloud -f list_nodes_min myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_min function must be called with -f or --function.'
)
if conn is None:
conn = get_conn()
ret = {}
for node in conn.list_servers(bare=True):
ret[node.name] = {'id': node.id, 'state': node.status}
return ret
def _get_ips(node, addr_type='public'):
ret = []
for _, interface in node.addresses.items():
for addr in interface:
if addr_type in ('floating', 'fixed') and addr_type == addr.get('OS-EXT-IPS:type'):
ret.append(addr['addr'])
elif addr_type == 'public' and __utils__['cloud.is_public_ip'](addr['addr']):
ret.append(addr['addr'])
elif addr_type == 'private' and not __utils__['cloud.is_public_ip'](addr['addr']):
ret.append(addr['addr'])
return ret
def list_nodes_full(conn=None, call=None):
'''
Return a list of VMs with all the information about them
CLI Example
.. code-block:: bash
salt-cloud -f list_nodes_full myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or --function.'
)
if conn is None:
conn = get_conn()
ret = {}
for node in conn.list_servers(detailed=True):
ret[node.name] = dict(node)
ret[node.name]['id'] = node.id
ret[node.name]['name'] = node.name
ret[node.name]['size'] = node.flavor.name
ret[node.name]['state'] = node.status
ret[node.name]['private_ips'] = _get_ips(node, 'private')
ret[node.name]['public_ips'] = _get_ips(node, 'public')
ret[node.name]['floating_ips'] = _get_ips(node, 'floating')
ret[node.name]['fixed_ips'] = _get_ips(node, 'fixed')
ret[node.name]['image'] = node.image.name
return ret
def list_nodes_select(conn=None, call=None):
'''
Return a list of VMs with the fields from `query.selection`
CLI Example
.. code-block:: bash
salt-cloud -f list_nodes_full myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_select function must be called with -f or --function.'
)
return __utils__['cloud.list_nodes_select'](
list_nodes(conn, 'function'), __opts__['query.selection'], call,
)
def show_instance(name, conn=None, call=None):
'''
Get VM on this OpenStack account
name
name of the instance
CLI Example
.. code-block:: bash
salt-cloud -a show_instance myserver
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
if conn is None:
conn = get_conn()
node = conn.get_server(name, bare=True)
ret = dict(node)
ret['id'] = node.id
ret['name'] = node.name
ret['size'] = conn.get_flavor(node.flavor.id).name
ret['state'] = node.status
ret['private_ips'] = _get_ips(node, 'private')
ret['public_ips'] = _get_ips(node, 'public')
ret['floating_ips'] = _get_ips(node, 'floating')
ret['fixed_ips'] = _get_ips(node, 'fixed')
if isinstance(node.image, six.string_types):
ret['image'] = node.image
else:
ret['image'] = conn.get_image(node.image.id).name
return ret
def avail_images(conn=None, call=None):
'''
List available images for OpenStack
CLI Example
.. code-block:: bash
salt-cloud -f avail_images myopenstack
salt-cloud --list-images myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
if conn is None:
conn = get_conn()
return conn.list_images()
def avail_sizes(conn=None, call=None):
'''
List available sizes for OpenStack
CLI Example
.. code-block:: bash
salt-cloud -f avail_sizes myopenstack
salt-cloud --list-sizes myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
if conn is None:
conn = get_conn()
return conn.list_flavors()
def list_networks(conn=None, call=None):
'''
List networks for OpenStack
CLI Example
.. code-block:: bash
salt-cloud -f list_networks myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_networks function must be called with '
'-f or --function'
)
if conn is None:
conn = get_conn()
return conn.list_networks()
def list_subnets(conn=None, call=None, kwargs=None):
'''
List subnets in a virtual network
network
network to list subnets of
.. code-block:: bash
salt-cloud -f list_subnets myopenstack network=salt-net
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_subnets function must be called with '
'-f or --function.'
)
if conn is None:
conn = get_conn()
if kwargs is None or (isinstance(kwargs, dict) and 'network' not in kwargs):
raise SaltCloudSystemExit(
'A `network` must be specified'
)
return conn.list_subnets(filters={'network': kwargs['network']})
def _clean_create_kwargs(**kwargs):
'''
Sanatize kwargs to be sent to create_server
'''
VALID_OPTS = {
'name': six.string_types,
'image': six.string_types,
'flavor': six.string_types,
'auto_ip': bool,
'ips': list,
'ip_pool': six.string_types,
'root_volume': six.string_types,
'boot_volume': six.string_types,
'terminate_volume': bool,
'volumes': list,
'meta': dict,
'files': dict,
'reservation_id': six.string_types,
'security_groups': list,
'key_name': six.string_types,
'availability_zone': six.string_types,
'block_device_mapping': dict,
'block_device_mapping_v2': dict,
'nics': list,
'scheduler_hints': dict,
'config_drive': bool,
'disk_config': six.string_types, # AUTO or MANUAL
'admin_pass': six.string_types,
'wait': bool,
'timeout': int,
'reuse_ips': bool,
'network': dict,
'boot_from_volume': bool,
'volume_size': int,
'nat_destination': six.string_types,
'group': six.string_types,
'userdata': six.string_types,
}
extra = kwargs.pop('extra', {})
for key, value in six.iteritems(kwargs.copy()):
if key in VALID_OPTS:
if isinstance(value, VALID_OPTS[key]):
continue
log.error('Error %s: %s is not of type %s', key, value, VALID_OPTS[key])
kwargs.pop(key)
return __utils__['dictupdate.update'](kwargs, extra)
def request_instance(vm_, conn=None, call=None):
'''
Request an instance to be built
'''
if call == 'function':
# Technically this function may be called other ways too, but it
# definitely cannot be called with --function.
raise SaltCloudSystemExit(
'The request_instance action must be called with -a or --action.'
)
kwargs = copy.deepcopy(vm_)
log.info('Creating Cloud VM %s', vm_['name'])
__utils__['cloud.check_name'](vm_['name'], 'a-zA-Z0-9._-')
conn = get_conn()
userdata = config.get_cloud_config_value(
'userdata', vm_, __opts__, search_global=False, default=None
)
if userdata is not None and os.path.isfile(userdata):
try:
with __utils__['files.fopen'](userdata, 'r') as fp_:
kwargs['userdata'] = __utils__['cloud.userdata_template'](
__opts__, vm_, fp_.read()
)
except Exception as exc:
log.exception(
'Failed to read userdata from %s: %s', userdata, exc)
if 'size' in kwargs:
kwargs['flavor'] = kwargs.pop('size')
kwargs['key_name'] = config.get_cloud_config_value(
'ssh_key_name', vm_, __opts__, search_global=False, default=None
)
kwargs['wait'] = True
try:
conn.create_server(**_clean_create_kwargs(**kwargs))
except shade.exc.OpenStackCloudException as exc:
log.error('Error creating server %s: %s', vm_['name'], exc)
destroy(vm_['name'], conn=conn, call='action')
raise SaltCloudSystemExit(six.text_type(exc))
return show_instance(vm_['name'], conn=conn, call='action')
def create(vm_):
'''
Create a single VM from a data dict
'''
deploy = config.get_cloud_config_value('deploy', vm_, __opts__)
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 ssh_key_file \'{0}\' does not exist'.format(
key_filename
)
)
vm_['key_filename'] = key_filename
__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']
)
conn = get_conn()
if 'instance_id' in vm_:
# This was probably created via another process, and doesn't have
# things like salt keys created yet, so let's create them now.
if 'pub_key' not in vm_ and 'priv_key' not in vm_:
log.debug('Generating minion keys for \'%s\'', vm_['name'])
vm_['priv_key'], vm_['pub_key'] = __utils__['cloud.gen_keys'](
config.get_cloud_config_value(
'keysize',
vm_,
__opts__
)
)
else:
# Put together all of the information required to request the instance,
# and then fire off the request for it
request_instance(conn=conn, call='action', vm_=vm_)
data = show_instance(vm_.get('instance_id', vm_['name']), conn=conn, call='action')
log.debug('VM is now running')
def __query_node(vm_):
data = show_instance(vm_['name'], conn=conn, call='action')
if 'wait_for_metadata' in vm_:
for key, value in six.iteritems(vm_.get('wait_for_metadata', {})):
log.debug('Waiting for metadata: %s=%s', key, value)
if data['metadata'].get(key, None) != value:
log.debug('Metadata is not ready: %s=%s', key, data['metadata'].get(key))
return False
return preferred_ip(vm_, data[ssh_interface(vm_)])
try:
ip_address = __utils__['cloud.wait_for_fun'](
__query_node,
vm_=vm_
)
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))
log.debug('Using IP address %s', ip_address)
salt_interface = __utils__['cloud.get_salt_interface'](vm_, __opts__)
salt_ip_address = preferred_ip(vm_, data[salt_interface])
log.debug('Salt interface set to: %s', salt_ip_address)
if not ip_address:
raise SaltCloudSystemExit('A valid IP address was not found')
vm_['ssh_host'] = ip_address
vm_['salt_host'] = salt_ip_address
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)
)
event_data = {
'name': vm_['name'],
'profile': vm_['profile'],
'provider': vm_['driver'],
'instance_id': data['id'],
'floating_ips': data['floating_ips'],
'fixed_ips': data['fixed_ips'],
'private_ips': data['private_ips'],
'public_ips': data['public_ips'],
}
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args=__utils__['cloud.filter_event']('created', event_data, list(event_data)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
__utils__['cloud.cachedir_index_add'](vm_['name'], vm_['profile'], 'nova', vm_['driver'])
return ret
def destroy(name, conn=None, call=None):
'''
Delete a single VM
'''
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']
)
if not conn:
conn = get_conn()
node = show_instance(name, conn=conn, call='action')
log.info('Destroying VM: %s', name)
ret = conn.delete_server(name)
if ret:
log.info('Destroyed VM: %s', name)
# Fire destroy action
__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('delete_sshkeys', False) is True:
__utils__['cloud.remove_sshkey'](getattr(node, __opts__.get('ssh_interface', 'public_ips'))[0])
if __opts__.get('update_cachedir', False) is True:
__utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__)
__utils__['cloud.cachedir_index_del'](name)
return True
log.error('Failed to Destroy VM: %s', name)
return False
def call(conn=None, call=None, kwargs=None):
'''
Call function from shade.
func
function to call from shade.openstackcloud library
CLI Example
.. code-block:: bash
salt-cloud -f call myopenstack func=list_images
t sujksalt-cloud -f call myopenstack func=create_network name=mysubnet
'''
if call == 'action':
raise SaltCloudSystemExit(
'The call function must be called with '
'-f or --function.'
)
if 'func' not in kwargs:
raise SaltCloudSystemExit(
'No `func` argument passed'
)
if conn is None:
conn = get_conn()
func = kwargs.pop('func')
for key, value in kwargs.items():
try:
kwargs[key] = __utils__['json.loads'](value)
except ValueError:
continue
try:
return getattr(conn, func)(**kwargs)
except shade.exc.OpenStackCloudException as exc:
log.error('Error running %s: %s', func, exc)
raise SaltCloudSystemExit(six.text_type(exc))
|
saltstack/salt
|
salt/cloud/clouds/openstack.py
|
list_nodes_min
|
python
|
def list_nodes_min(conn=None, call=None):
'''
Return a list of VMs with minimal information
CLI Example
.. code-block:: bash
salt-cloud -f list_nodes_min myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_min function must be called with -f or --function.'
)
if conn is None:
conn = get_conn()
ret = {}
for node in conn.list_servers(bare=True):
ret[node.name] = {'id': node.id, 'state': node.status}
return ret
|
Return a list of VMs with minimal information
CLI Example
.. code-block:: bash
salt-cloud -f list_nodes_min myopenstack
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/openstack.py#L353-L373
|
[
"def get_conn():\n '''\n Return a conn object for the passed VM data\n '''\n if __active_provider_name__ in __context__:\n return __context__[__active_provider_name__]\n vm_ = get_configured_provider()\n profile = vm_.pop('profile', None)\n if profile is not None:\n vm_ = __utils__['dictupdate.update'](os_client_config.vendors.get_profile(profile), vm_)\n conn = shade.openstackcloud.OpenStackCloud(cloud_config=None, **vm_)\n if __active_provider_name__ is not None:\n __context__[__active_provider_name__] = conn\n return conn\n"
] |
# -*- coding: utf-8 -*-
'''
Openstack Cloud Driver
======================
:depends: `shade>=1.19.0 <https://pypi.python.org/pypi/shade>`_
OpenStack is an open source project that is in use by a number a cloud
providers, each of which have their own ways of using it.
This OpenStack driver uses a the shade python module which is managed by the
OpenStack Infra team. This module is written to handle all the different
versions of different OpenStack tools for salt, so most commands are just passed
over to the module to handle everything.
Provider
--------
There are two ways to configure providers for this driver. The first one is to
just let shade handle everything, and configure using os-client-config_ and
setting up `/etc/openstack/clouds.yml`.
.. code-block:: yaml
clouds:
democloud:
region_name: RegionOne
auth:
username: 'demo'
password: secret
project_name: 'demo'
auth_url: 'http://openstack/identity'
And then this can be referenced in the salt provider based on the `democloud`
name.
.. code-block:: yaml
myopenstack:
driver: openstack
cloud: democloud
region_name: RegionOne
This allows for just using one configuration for salt-cloud and for any other
openstack tools which are all using `/etc/openstack/clouds.yml`
The other method allows for specifying everything in the provider config,
instead of using the extra configuration file. This will allow for passing
salt-cloud configs only through pillars for minions without having to write a
clouds.yml file on each minion.abs
.. code-block:: yaml
myopenstack:
driver: openstack
region_name: RegionOne
auth:
username: 'demo'
password: secret
project_name: 'demo'
auth_url: 'http://openstack/identity'
Or if you need to use a profile to setup some extra stuff, it can be passed as a
`profile` to use any of the vendor_ config options.
.. code-block:: yaml
myrackspace:
driver: openstack
profile: rackspace
auth:
username: rackusername
api_key: myapikey
region_name: ORD
auth_type: rackspace_apikey
And this will pull in the profile for rackspace and setup all the correct
options for the auth_url and different api versions for services.
Profile
-------
Most of the options for building servers are just passed on to the
create_server_ function from shade.
The salt specific ones are:
- ssh_key_file: The path to the ssh key that should be used to login to the machine to bootstrap it
- ssh_key_file: The name of the keypair in openstack
- userdata_template: The renderer to use if the userdata is a file that is templated. Default: False
- ssh_interface: The interface to use to login for bootstrapping: public_ips, private_ips, floating_ips, fixed_ips
.. code-block:: yaml
centos:
provider: myopenstack
image: CentOS 7
size: ds1G
ssh_key_name: mykey
ssh_key_file: /root/.ssh/id_rsa
This is the minimum setup required.
If metadata is set to make sure that the host has finished setting up the
`wait_for_metadata` can be set.
.. code-block:: yaml
centos:
provider: myopenstack
image: CentOS 7
size: ds1G
ssh_key_name: mykey
ssh_key_file: /root/.ssh/id_rsa
meta:
build_config: rack_user_only
wait_for_metadata:
rax_service_level_automation: Complete
rackconnect_automation_status: DEPLOYED
Anything else from the create_server_ docs can be passed through here.
- **image**: Image dict, name or ID to boot with. image is required
unless boot_volume is given.
- **flavor**: Flavor dict, name or ID to boot onto.
- **auto_ip**: Whether to take actions to find a routable IP for
the server. (defaults to True)
- **ips**: List of IPs to attach to the server (defaults to None)
- **ip_pool**: Name of the network or floating IP pool to get an
address from. (defaults to None)
- **root_volume**: Name or ID of a volume to boot from
(defaults to None - deprecated, use boot_volume)
- **boot_volume**: Name or ID of a volume to boot from
(defaults to None)
- **terminate_volume**: If booting from a volume, whether it should
be deleted when the server is destroyed.
(defaults to False)
- **volumes**: (optional) A list of volumes to attach to the server
- **meta**: (optional) A dict of arbitrary key/value metadata to
store for this server. Both keys and values must be
<=255 characters.
- **files**: (optional, deprecated) A dict of files to overwrite
on the server upon boot. Keys are file names (i.e.
``/etc/passwd``) and values
are the file contents (either as a string or as a
file-like object). A maximum of five entries is allowed,
and each file must be 10k or less.
- **reservation_id**: a UUID for the set of servers being requested.
- **min_count**: (optional extension) The minimum number of
servers to launch.
- **max_count**: (optional extension) The maximum number of
servers to launch.
- **security_groups**: A list of security group names
- **userdata**: user data to pass to be exposed by the metadata
server this can be a file type object as well or a
string.
- **key_name**: (optional extension) name of previously created
keypair to inject into the instance.
- **availability_zone**: Name of the availability zone for instance
placement.
- **block_device_mapping**: (optional) A dict of block
device mappings for this server.
- **block_device_mapping_v2**: (optional) A dict of block
device mappings for this server.
- **nics**: (optional extension) an ordered list of nics to be
added to this server, with information about
connected networks, fixed IPs, port etc.
- **scheduler_hints**: (optional extension) arbitrary key-value pairs
specified by the client to help boot an instance
- **config_drive**: (optional extension) value for config drive
either boolean, or volume-id
- **disk_config**: (optional extension) control how the disk is
partitioned when the server is created. possible
values are 'AUTO' or 'MANUAL'.
- **admin_pass**: (optional extension) add a user supplied admin
password.
- **timeout**: (optional) Seconds to wait, defaults to 60.
See the ``wait`` parameter.
- **reuse_ips**: (optional) Whether to attempt to reuse pre-existing
floating ips should a floating IP be
needed (defaults to True)
- **network**: (optional) Network dict or name or ID to attach the
server to. Mutually exclusive with the nics parameter.
Can also be be a list of network names or IDs or
network dicts.
- **boot_from_volume**: Whether to boot from volume. 'boot_volume'
implies True, but boot_from_volume=True with
no boot_volume is valid and will create a
volume from the image and use that.
- **volume_size**: When booting an image from volume, how big should
the created volume be? Defaults to 50.
- **nat_destination**: Which network should a created floating IP
be attached to, if it's not possible to
infer from the cloud's configuration.
(Optional, defaults to None)
- **group**: ServerGroup dict, name or id to boot the server in.
If a group is provided in both scheduler_hints and in
the group param, the group param will win.
(Optional, defaults to None)
.. note::
If there is anything added, that is not in this list, it can be added to an `extras`
dictionary for the profile, and that will be to the create_server function.
.. _create_server: https://docs.openstack.org/shade/latest/user/usage.html#shade.OpenStackCloud.create_server
.. _vendor: https://docs.openstack.org/os-client-config/latest/user/vendor-support.html
.. _os-client-config: https://docs.openstack.org/os-client-config/latest/user/configuration.html#config-files
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import Python Libs
import copy
import logging
import os
import pprint
import socket
# Import Salt Libs
import salt.utils.versions
import salt.config as config
from salt.ext import six
from salt.exceptions import (
SaltCloudSystemExit,
SaltCloudExecutionTimeout,
SaltCloudExecutionFailure,
SaltCloudConfigError,
)
# Import 3rd-Party Libs
try:
import shade
import shade.openstackcloud
import shade.exc
import os_client_config
HAS_SHADE = (
salt.utils.versions._LooseVersion(shade.__version__) >= salt.utils.versions._LooseVersion('1.19.0'),
'Please install newer version of shade: >= 1.19.0'
)
except ImportError:
HAS_SHADE = (False, 'Install pypi module shade >= 1.19.0')
log = logging.getLogger(__name__)
__virtualname__ = 'openstack'
def __virtual__():
'''
Check for OpenStack dependencies
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return HAS_SHADE
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__, __active_provider_name__ or __virtualname__,
('auth', 'region_name'), log_message=False,
) or config.is_provider_configured(
__opts__, __active_provider_name__ or __virtualname__,
('cloud', 'region_name')
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
deps = {
'shade': shade[0],
'os_client_config': shade[0],
}
return config.check_driver_dependencies(
__virtualname__,
deps
)
def preferred_ip(vm_, ips):
'''
Return the preferred Internet protocol. Either 'ipv4' (default) or 'ipv6'.
'''
proto = config.get_cloud_config_value(
'protocol', vm_, __opts__, default='ipv4', search_global=False
)
family = socket.AF_INET
if proto == 'ipv6':
family = socket.AF_INET6
for ip in ips:
try:
socket.inet_pton(family, ip)
return ip
except Exception:
continue
return False
def ssh_interface(vm_):
'''
Return the ssh_interface type to connect to. Either 'public_ips' (default)
or 'private_ips'.
'''
return config.get_cloud_config_value('ssh_interface', vm_, __opts__, default='public_ips', search_global=False)
def get_conn():
'''
Return a conn object for the passed VM data
'''
if __active_provider_name__ in __context__:
return __context__[__active_provider_name__]
vm_ = get_configured_provider()
profile = vm_.pop('profile', None)
if profile is not None:
vm_ = __utils__['dictupdate.update'](os_client_config.vendors.get_profile(profile), vm_)
conn = shade.openstackcloud.OpenStackCloud(cloud_config=None, **vm_)
if __active_provider_name__ is not None:
__context__[__active_provider_name__] = conn
return conn
def list_nodes(conn=None, call=None):
'''
Return a list of VMs
CLI Example
.. code-block:: bash
salt-cloud -f list_nodes myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
ret = {}
for node, info in list_nodes_full(conn=conn).items():
for key in ('id', 'name', 'size', 'state', 'private_ips', 'public_ips', 'floating_ips', 'fixed_ips', 'image'):
ret.setdefault(node, {}).setdefault(key, info.get(key))
return ret
def _get_ips(node, addr_type='public'):
ret = []
for _, interface in node.addresses.items():
for addr in interface:
if addr_type in ('floating', 'fixed') and addr_type == addr.get('OS-EXT-IPS:type'):
ret.append(addr['addr'])
elif addr_type == 'public' and __utils__['cloud.is_public_ip'](addr['addr']):
ret.append(addr['addr'])
elif addr_type == 'private' and not __utils__['cloud.is_public_ip'](addr['addr']):
ret.append(addr['addr'])
return ret
def list_nodes_full(conn=None, call=None):
'''
Return a list of VMs with all the information about them
CLI Example
.. code-block:: bash
salt-cloud -f list_nodes_full myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or --function.'
)
if conn is None:
conn = get_conn()
ret = {}
for node in conn.list_servers(detailed=True):
ret[node.name] = dict(node)
ret[node.name]['id'] = node.id
ret[node.name]['name'] = node.name
ret[node.name]['size'] = node.flavor.name
ret[node.name]['state'] = node.status
ret[node.name]['private_ips'] = _get_ips(node, 'private')
ret[node.name]['public_ips'] = _get_ips(node, 'public')
ret[node.name]['floating_ips'] = _get_ips(node, 'floating')
ret[node.name]['fixed_ips'] = _get_ips(node, 'fixed')
ret[node.name]['image'] = node.image.name
return ret
def list_nodes_select(conn=None, call=None):
'''
Return a list of VMs with the fields from `query.selection`
CLI Example
.. code-block:: bash
salt-cloud -f list_nodes_full myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_select function must be called with -f or --function.'
)
return __utils__['cloud.list_nodes_select'](
list_nodes(conn, 'function'), __opts__['query.selection'], call,
)
def show_instance(name, conn=None, call=None):
'''
Get VM on this OpenStack account
name
name of the instance
CLI Example
.. code-block:: bash
salt-cloud -a show_instance myserver
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
if conn is None:
conn = get_conn()
node = conn.get_server(name, bare=True)
ret = dict(node)
ret['id'] = node.id
ret['name'] = node.name
ret['size'] = conn.get_flavor(node.flavor.id).name
ret['state'] = node.status
ret['private_ips'] = _get_ips(node, 'private')
ret['public_ips'] = _get_ips(node, 'public')
ret['floating_ips'] = _get_ips(node, 'floating')
ret['fixed_ips'] = _get_ips(node, 'fixed')
if isinstance(node.image, six.string_types):
ret['image'] = node.image
else:
ret['image'] = conn.get_image(node.image.id).name
return ret
def avail_images(conn=None, call=None):
'''
List available images for OpenStack
CLI Example
.. code-block:: bash
salt-cloud -f avail_images myopenstack
salt-cloud --list-images myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
if conn is None:
conn = get_conn()
return conn.list_images()
def avail_sizes(conn=None, call=None):
'''
List available sizes for OpenStack
CLI Example
.. code-block:: bash
salt-cloud -f avail_sizes myopenstack
salt-cloud --list-sizes myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
if conn is None:
conn = get_conn()
return conn.list_flavors()
def list_networks(conn=None, call=None):
'''
List networks for OpenStack
CLI Example
.. code-block:: bash
salt-cloud -f list_networks myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_networks function must be called with '
'-f or --function'
)
if conn is None:
conn = get_conn()
return conn.list_networks()
def list_subnets(conn=None, call=None, kwargs=None):
'''
List subnets in a virtual network
network
network to list subnets of
.. code-block:: bash
salt-cloud -f list_subnets myopenstack network=salt-net
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_subnets function must be called with '
'-f or --function.'
)
if conn is None:
conn = get_conn()
if kwargs is None or (isinstance(kwargs, dict) and 'network' not in kwargs):
raise SaltCloudSystemExit(
'A `network` must be specified'
)
return conn.list_subnets(filters={'network': kwargs['network']})
def _clean_create_kwargs(**kwargs):
'''
Sanatize kwargs to be sent to create_server
'''
VALID_OPTS = {
'name': six.string_types,
'image': six.string_types,
'flavor': six.string_types,
'auto_ip': bool,
'ips': list,
'ip_pool': six.string_types,
'root_volume': six.string_types,
'boot_volume': six.string_types,
'terminate_volume': bool,
'volumes': list,
'meta': dict,
'files': dict,
'reservation_id': six.string_types,
'security_groups': list,
'key_name': six.string_types,
'availability_zone': six.string_types,
'block_device_mapping': dict,
'block_device_mapping_v2': dict,
'nics': list,
'scheduler_hints': dict,
'config_drive': bool,
'disk_config': six.string_types, # AUTO or MANUAL
'admin_pass': six.string_types,
'wait': bool,
'timeout': int,
'reuse_ips': bool,
'network': dict,
'boot_from_volume': bool,
'volume_size': int,
'nat_destination': six.string_types,
'group': six.string_types,
'userdata': six.string_types,
}
extra = kwargs.pop('extra', {})
for key, value in six.iteritems(kwargs.copy()):
if key in VALID_OPTS:
if isinstance(value, VALID_OPTS[key]):
continue
log.error('Error %s: %s is not of type %s', key, value, VALID_OPTS[key])
kwargs.pop(key)
return __utils__['dictupdate.update'](kwargs, extra)
def request_instance(vm_, conn=None, call=None):
'''
Request an instance to be built
'''
if call == 'function':
# Technically this function may be called other ways too, but it
# definitely cannot be called with --function.
raise SaltCloudSystemExit(
'The request_instance action must be called with -a or --action.'
)
kwargs = copy.deepcopy(vm_)
log.info('Creating Cloud VM %s', vm_['name'])
__utils__['cloud.check_name'](vm_['name'], 'a-zA-Z0-9._-')
conn = get_conn()
userdata = config.get_cloud_config_value(
'userdata', vm_, __opts__, search_global=False, default=None
)
if userdata is not None and os.path.isfile(userdata):
try:
with __utils__['files.fopen'](userdata, 'r') as fp_:
kwargs['userdata'] = __utils__['cloud.userdata_template'](
__opts__, vm_, fp_.read()
)
except Exception as exc:
log.exception(
'Failed to read userdata from %s: %s', userdata, exc)
if 'size' in kwargs:
kwargs['flavor'] = kwargs.pop('size')
kwargs['key_name'] = config.get_cloud_config_value(
'ssh_key_name', vm_, __opts__, search_global=False, default=None
)
kwargs['wait'] = True
try:
conn.create_server(**_clean_create_kwargs(**kwargs))
except shade.exc.OpenStackCloudException as exc:
log.error('Error creating server %s: %s', vm_['name'], exc)
destroy(vm_['name'], conn=conn, call='action')
raise SaltCloudSystemExit(six.text_type(exc))
return show_instance(vm_['name'], conn=conn, call='action')
def create(vm_):
'''
Create a single VM from a data dict
'''
deploy = config.get_cloud_config_value('deploy', vm_, __opts__)
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 ssh_key_file \'{0}\' does not exist'.format(
key_filename
)
)
vm_['key_filename'] = key_filename
__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']
)
conn = get_conn()
if 'instance_id' in vm_:
# This was probably created via another process, and doesn't have
# things like salt keys created yet, so let's create them now.
if 'pub_key' not in vm_ and 'priv_key' not in vm_:
log.debug('Generating minion keys for \'%s\'', vm_['name'])
vm_['priv_key'], vm_['pub_key'] = __utils__['cloud.gen_keys'](
config.get_cloud_config_value(
'keysize',
vm_,
__opts__
)
)
else:
# Put together all of the information required to request the instance,
# and then fire off the request for it
request_instance(conn=conn, call='action', vm_=vm_)
data = show_instance(vm_.get('instance_id', vm_['name']), conn=conn, call='action')
log.debug('VM is now running')
def __query_node(vm_):
data = show_instance(vm_['name'], conn=conn, call='action')
if 'wait_for_metadata' in vm_:
for key, value in six.iteritems(vm_.get('wait_for_metadata', {})):
log.debug('Waiting for metadata: %s=%s', key, value)
if data['metadata'].get(key, None) != value:
log.debug('Metadata is not ready: %s=%s', key, data['metadata'].get(key))
return False
return preferred_ip(vm_, data[ssh_interface(vm_)])
try:
ip_address = __utils__['cloud.wait_for_fun'](
__query_node,
vm_=vm_
)
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))
log.debug('Using IP address %s', ip_address)
salt_interface = __utils__['cloud.get_salt_interface'](vm_, __opts__)
salt_ip_address = preferred_ip(vm_, data[salt_interface])
log.debug('Salt interface set to: %s', salt_ip_address)
if not ip_address:
raise SaltCloudSystemExit('A valid IP address was not found')
vm_['ssh_host'] = ip_address
vm_['salt_host'] = salt_ip_address
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)
)
event_data = {
'name': vm_['name'],
'profile': vm_['profile'],
'provider': vm_['driver'],
'instance_id': data['id'],
'floating_ips': data['floating_ips'],
'fixed_ips': data['fixed_ips'],
'private_ips': data['private_ips'],
'public_ips': data['public_ips'],
}
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args=__utils__['cloud.filter_event']('created', event_data, list(event_data)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
__utils__['cloud.cachedir_index_add'](vm_['name'], vm_['profile'], 'nova', vm_['driver'])
return ret
def destroy(name, conn=None, call=None):
'''
Delete a single VM
'''
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']
)
if not conn:
conn = get_conn()
node = show_instance(name, conn=conn, call='action')
log.info('Destroying VM: %s', name)
ret = conn.delete_server(name)
if ret:
log.info('Destroyed VM: %s', name)
# Fire destroy action
__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('delete_sshkeys', False) is True:
__utils__['cloud.remove_sshkey'](getattr(node, __opts__.get('ssh_interface', 'public_ips'))[0])
if __opts__.get('update_cachedir', False) is True:
__utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__)
__utils__['cloud.cachedir_index_del'](name)
return True
log.error('Failed to Destroy VM: %s', name)
return False
def call(conn=None, call=None, kwargs=None):
'''
Call function from shade.
func
function to call from shade.openstackcloud library
CLI Example
.. code-block:: bash
salt-cloud -f call myopenstack func=list_images
t sujksalt-cloud -f call myopenstack func=create_network name=mysubnet
'''
if call == 'action':
raise SaltCloudSystemExit(
'The call function must be called with '
'-f or --function.'
)
if 'func' not in kwargs:
raise SaltCloudSystemExit(
'No `func` argument passed'
)
if conn is None:
conn = get_conn()
func = kwargs.pop('func')
for key, value in kwargs.items():
try:
kwargs[key] = __utils__['json.loads'](value)
except ValueError:
continue
try:
return getattr(conn, func)(**kwargs)
except shade.exc.OpenStackCloudException as exc:
log.error('Error running %s: %s', func, exc)
raise SaltCloudSystemExit(six.text_type(exc))
|
saltstack/salt
|
salt/cloud/clouds/openstack.py
|
list_nodes_full
|
python
|
def list_nodes_full(conn=None, call=None):
'''
Return a list of VMs with all the information about them
CLI Example
.. code-block:: bash
salt-cloud -f list_nodes_full myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or --function.'
)
if conn is None:
conn = get_conn()
ret = {}
for node in conn.list_servers(detailed=True):
ret[node.name] = dict(node)
ret[node.name]['id'] = node.id
ret[node.name]['name'] = node.name
ret[node.name]['size'] = node.flavor.name
ret[node.name]['state'] = node.status
ret[node.name]['private_ips'] = _get_ips(node, 'private')
ret[node.name]['public_ips'] = _get_ips(node, 'public')
ret[node.name]['floating_ips'] = _get_ips(node, 'floating')
ret[node.name]['fixed_ips'] = _get_ips(node, 'fixed')
ret[node.name]['image'] = node.image.name
return ret
|
Return a list of VMs with all the information about them
CLI Example
.. code-block:: bash
salt-cloud -f list_nodes_full myopenstack
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/openstack.py#L389-L418
|
[
"def get_conn():\n '''\n Return a conn object for the passed VM data\n '''\n if __active_provider_name__ in __context__:\n return __context__[__active_provider_name__]\n vm_ = get_configured_provider()\n profile = vm_.pop('profile', None)\n if profile is not None:\n vm_ = __utils__['dictupdate.update'](os_client_config.vendors.get_profile(profile), vm_)\n conn = shade.openstackcloud.OpenStackCloud(cloud_config=None, **vm_)\n if __active_provider_name__ is not None:\n __context__[__active_provider_name__] = conn\n return conn\n",
"def _get_ips(node, addr_type='public'):\n ret = []\n for _, interface in node.addresses.items():\n for addr in interface:\n if addr_type in ('floating', 'fixed') and addr_type == addr.get('OS-EXT-IPS:type'):\n ret.append(addr['addr'])\n elif addr_type == 'public' and __utils__['cloud.is_public_ip'](addr['addr']):\n ret.append(addr['addr'])\n elif addr_type == 'private' and not __utils__['cloud.is_public_ip'](addr['addr']):\n ret.append(addr['addr'])\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Openstack Cloud Driver
======================
:depends: `shade>=1.19.0 <https://pypi.python.org/pypi/shade>`_
OpenStack is an open source project that is in use by a number a cloud
providers, each of which have their own ways of using it.
This OpenStack driver uses a the shade python module which is managed by the
OpenStack Infra team. This module is written to handle all the different
versions of different OpenStack tools for salt, so most commands are just passed
over to the module to handle everything.
Provider
--------
There are two ways to configure providers for this driver. The first one is to
just let shade handle everything, and configure using os-client-config_ and
setting up `/etc/openstack/clouds.yml`.
.. code-block:: yaml
clouds:
democloud:
region_name: RegionOne
auth:
username: 'demo'
password: secret
project_name: 'demo'
auth_url: 'http://openstack/identity'
And then this can be referenced in the salt provider based on the `democloud`
name.
.. code-block:: yaml
myopenstack:
driver: openstack
cloud: democloud
region_name: RegionOne
This allows for just using one configuration for salt-cloud and for any other
openstack tools which are all using `/etc/openstack/clouds.yml`
The other method allows for specifying everything in the provider config,
instead of using the extra configuration file. This will allow for passing
salt-cloud configs only through pillars for minions without having to write a
clouds.yml file on each minion.abs
.. code-block:: yaml
myopenstack:
driver: openstack
region_name: RegionOne
auth:
username: 'demo'
password: secret
project_name: 'demo'
auth_url: 'http://openstack/identity'
Or if you need to use a profile to setup some extra stuff, it can be passed as a
`profile` to use any of the vendor_ config options.
.. code-block:: yaml
myrackspace:
driver: openstack
profile: rackspace
auth:
username: rackusername
api_key: myapikey
region_name: ORD
auth_type: rackspace_apikey
And this will pull in the profile for rackspace and setup all the correct
options for the auth_url and different api versions for services.
Profile
-------
Most of the options for building servers are just passed on to the
create_server_ function from shade.
The salt specific ones are:
- ssh_key_file: The path to the ssh key that should be used to login to the machine to bootstrap it
- ssh_key_file: The name of the keypair in openstack
- userdata_template: The renderer to use if the userdata is a file that is templated. Default: False
- ssh_interface: The interface to use to login for bootstrapping: public_ips, private_ips, floating_ips, fixed_ips
.. code-block:: yaml
centos:
provider: myopenstack
image: CentOS 7
size: ds1G
ssh_key_name: mykey
ssh_key_file: /root/.ssh/id_rsa
This is the minimum setup required.
If metadata is set to make sure that the host has finished setting up the
`wait_for_metadata` can be set.
.. code-block:: yaml
centos:
provider: myopenstack
image: CentOS 7
size: ds1G
ssh_key_name: mykey
ssh_key_file: /root/.ssh/id_rsa
meta:
build_config: rack_user_only
wait_for_metadata:
rax_service_level_automation: Complete
rackconnect_automation_status: DEPLOYED
Anything else from the create_server_ docs can be passed through here.
- **image**: Image dict, name or ID to boot with. image is required
unless boot_volume is given.
- **flavor**: Flavor dict, name or ID to boot onto.
- **auto_ip**: Whether to take actions to find a routable IP for
the server. (defaults to True)
- **ips**: List of IPs to attach to the server (defaults to None)
- **ip_pool**: Name of the network or floating IP pool to get an
address from. (defaults to None)
- **root_volume**: Name or ID of a volume to boot from
(defaults to None - deprecated, use boot_volume)
- **boot_volume**: Name or ID of a volume to boot from
(defaults to None)
- **terminate_volume**: If booting from a volume, whether it should
be deleted when the server is destroyed.
(defaults to False)
- **volumes**: (optional) A list of volumes to attach to the server
- **meta**: (optional) A dict of arbitrary key/value metadata to
store for this server. Both keys and values must be
<=255 characters.
- **files**: (optional, deprecated) A dict of files to overwrite
on the server upon boot. Keys are file names (i.e.
``/etc/passwd``) and values
are the file contents (either as a string or as a
file-like object). A maximum of five entries is allowed,
and each file must be 10k or less.
- **reservation_id**: a UUID for the set of servers being requested.
- **min_count**: (optional extension) The minimum number of
servers to launch.
- **max_count**: (optional extension) The maximum number of
servers to launch.
- **security_groups**: A list of security group names
- **userdata**: user data to pass to be exposed by the metadata
server this can be a file type object as well or a
string.
- **key_name**: (optional extension) name of previously created
keypair to inject into the instance.
- **availability_zone**: Name of the availability zone for instance
placement.
- **block_device_mapping**: (optional) A dict of block
device mappings for this server.
- **block_device_mapping_v2**: (optional) A dict of block
device mappings for this server.
- **nics**: (optional extension) an ordered list of nics to be
added to this server, with information about
connected networks, fixed IPs, port etc.
- **scheduler_hints**: (optional extension) arbitrary key-value pairs
specified by the client to help boot an instance
- **config_drive**: (optional extension) value for config drive
either boolean, or volume-id
- **disk_config**: (optional extension) control how the disk is
partitioned when the server is created. possible
values are 'AUTO' or 'MANUAL'.
- **admin_pass**: (optional extension) add a user supplied admin
password.
- **timeout**: (optional) Seconds to wait, defaults to 60.
See the ``wait`` parameter.
- **reuse_ips**: (optional) Whether to attempt to reuse pre-existing
floating ips should a floating IP be
needed (defaults to True)
- **network**: (optional) Network dict or name or ID to attach the
server to. Mutually exclusive with the nics parameter.
Can also be be a list of network names or IDs or
network dicts.
- **boot_from_volume**: Whether to boot from volume. 'boot_volume'
implies True, but boot_from_volume=True with
no boot_volume is valid and will create a
volume from the image and use that.
- **volume_size**: When booting an image from volume, how big should
the created volume be? Defaults to 50.
- **nat_destination**: Which network should a created floating IP
be attached to, if it's not possible to
infer from the cloud's configuration.
(Optional, defaults to None)
- **group**: ServerGroup dict, name or id to boot the server in.
If a group is provided in both scheduler_hints and in
the group param, the group param will win.
(Optional, defaults to None)
.. note::
If there is anything added, that is not in this list, it can be added to an `extras`
dictionary for the profile, and that will be to the create_server function.
.. _create_server: https://docs.openstack.org/shade/latest/user/usage.html#shade.OpenStackCloud.create_server
.. _vendor: https://docs.openstack.org/os-client-config/latest/user/vendor-support.html
.. _os-client-config: https://docs.openstack.org/os-client-config/latest/user/configuration.html#config-files
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import Python Libs
import copy
import logging
import os
import pprint
import socket
# Import Salt Libs
import salt.utils.versions
import salt.config as config
from salt.ext import six
from salt.exceptions import (
SaltCloudSystemExit,
SaltCloudExecutionTimeout,
SaltCloudExecutionFailure,
SaltCloudConfigError,
)
# Import 3rd-Party Libs
try:
import shade
import shade.openstackcloud
import shade.exc
import os_client_config
HAS_SHADE = (
salt.utils.versions._LooseVersion(shade.__version__) >= salt.utils.versions._LooseVersion('1.19.0'),
'Please install newer version of shade: >= 1.19.0'
)
except ImportError:
HAS_SHADE = (False, 'Install pypi module shade >= 1.19.0')
log = logging.getLogger(__name__)
__virtualname__ = 'openstack'
def __virtual__():
'''
Check for OpenStack dependencies
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return HAS_SHADE
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__, __active_provider_name__ or __virtualname__,
('auth', 'region_name'), log_message=False,
) or config.is_provider_configured(
__opts__, __active_provider_name__ or __virtualname__,
('cloud', 'region_name')
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
deps = {
'shade': shade[0],
'os_client_config': shade[0],
}
return config.check_driver_dependencies(
__virtualname__,
deps
)
def preferred_ip(vm_, ips):
'''
Return the preferred Internet protocol. Either 'ipv4' (default) or 'ipv6'.
'''
proto = config.get_cloud_config_value(
'protocol', vm_, __opts__, default='ipv4', search_global=False
)
family = socket.AF_INET
if proto == 'ipv6':
family = socket.AF_INET6
for ip in ips:
try:
socket.inet_pton(family, ip)
return ip
except Exception:
continue
return False
def ssh_interface(vm_):
'''
Return the ssh_interface type to connect to. Either 'public_ips' (default)
or 'private_ips'.
'''
return config.get_cloud_config_value('ssh_interface', vm_, __opts__, default='public_ips', search_global=False)
def get_conn():
'''
Return a conn object for the passed VM data
'''
if __active_provider_name__ in __context__:
return __context__[__active_provider_name__]
vm_ = get_configured_provider()
profile = vm_.pop('profile', None)
if profile is not None:
vm_ = __utils__['dictupdate.update'](os_client_config.vendors.get_profile(profile), vm_)
conn = shade.openstackcloud.OpenStackCloud(cloud_config=None, **vm_)
if __active_provider_name__ is not None:
__context__[__active_provider_name__] = conn
return conn
def list_nodes(conn=None, call=None):
'''
Return a list of VMs
CLI Example
.. code-block:: bash
salt-cloud -f list_nodes myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
ret = {}
for node, info in list_nodes_full(conn=conn).items():
for key in ('id', 'name', 'size', 'state', 'private_ips', 'public_ips', 'floating_ips', 'fixed_ips', 'image'):
ret.setdefault(node, {}).setdefault(key, info.get(key))
return ret
def list_nodes_min(conn=None, call=None):
'''
Return a list of VMs with minimal information
CLI Example
.. code-block:: bash
salt-cloud -f list_nodes_min myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_min function must be called with -f or --function.'
)
if conn is None:
conn = get_conn()
ret = {}
for node in conn.list_servers(bare=True):
ret[node.name] = {'id': node.id, 'state': node.status}
return ret
def _get_ips(node, addr_type='public'):
ret = []
for _, interface in node.addresses.items():
for addr in interface:
if addr_type in ('floating', 'fixed') and addr_type == addr.get('OS-EXT-IPS:type'):
ret.append(addr['addr'])
elif addr_type == 'public' and __utils__['cloud.is_public_ip'](addr['addr']):
ret.append(addr['addr'])
elif addr_type == 'private' and not __utils__['cloud.is_public_ip'](addr['addr']):
ret.append(addr['addr'])
return ret
def list_nodes_select(conn=None, call=None):
'''
Return a list of VMs with the fields from `query.selection`
CLI Example
.. code-block:: bash
salt-cloud -f list_nodes_full myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_select function must be called with -f or --function.'
)
return __utils__['cloud.list_nodes_select'](
list_nodes(conn, 'function'), __opts__['query.selection'], call,
)
def show_instance(name, conn=None, call=None):
'''
Get VM on this OpenStack account
name
name of the instance
CLI Example
.. code-block:: bash
salt-cloud -a show_instance myserver
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
if conn is None:
conn = get_conn()
node = conn.get_server(name, bare=True)
ret = dict(node)
ret['id'] = node.id
ret['name'] = node.name
ret['size'] = conn.get_flavor(node.flavor.id).name
ret['state'] = node.status
ret['private_ips'] = _get_ips(node, 'private')
ret['public_ips'] = _get_ips(node, 'public')
ret['floating_ips'] = _get_ips(node, 'floating')
ret['fixed_ips'] = _get_ips(node, 'fixed')
if isinstance(node.image, six.string_types):
ret['image'] = node.image
else:
ret['image'] = conn.get_image(node.image.id).name
return ret
def avail_images(conn=None, call=None):
'''
List available images for OpenStack
CLI Example
.. code-block:: bash
salt-cloud -f avail_images myopenstack
salt-cloud --list-images myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
if conn is None:
conn = get_conn()
return conn.list_images()
def avail_sizes(conn=None, call=None):
'''
List available sizes for OpenStack
CLI Example
.. code-block:: bash
salt-cloud -f avail_sizes myopenstack
salt-cloud --list-sizes myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
if conn is None:
conn = get_conn()
return conn.list_flavors()
def list_networks(conn=None, call=None):
'''
List networks for OpenStack
CLI Example
.. code-block:: bash
salt-cloud -f list_networks myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_networks function must be called with '
'-f or --function'
)
if conn is None:
conn = get_conn()
return conn.list_networks()
def list_subnets(conn=None, call=None, kwargs=None):
'''
List subnets in a virtual network
network
network to list subnets of
.. code-block:: bash
salt-cloud -f list_subnets myopenstack network=salt-net
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_subnets function must be called with '
'-f or --function.'
)
if conn is None:
conn = get_conn()
if kwargs is None or (isinstance(kwargs, dict) and 'network' not in kwargs):
raise SaltCloudSystemExit(
'A `network` must be specified'
)
return conn.list_subnets(filters={'network': kwargs['network']})
def _clean_create_kwargs(**kwargs):
'''
Sanatize kwargs to be sent to create_server
'''
VALID_OPTS = {
'name': six.string_types,
'image': six.string_types,
'flavor': six.string_types,
'auto_ip': bool,
'ips': list,
'ip_pool': six.string_types,
'root_volume': six.string_types,
'boot_volume': six.string_types,
'terminate_volume': bool,
'volumes': list,
'meta': dict,
'files': dict,
'reservation_id': six.string_types,
'security_groups': list,
'key_name': six.string_types,
'availability_zone': six.string_types,
'block_device_mapping': dict,
'block_device_mapping_v2': dict,
'nics': list,
'scheduler_hints': dict,
'config_drive': bool,
'disk_config': six.string_types, # AUTO or MANUAL
'admin_pass': six.string_types,
'wait': bool,
'timeout': int,
'reuse_ips': bool,
'network': dict,
'boot_from_volume': bool,
'volume_size': int,
'nat_destination': six.string_types,
'group': six.string_types,
'userdata': six.string_types,
}
extra = kwargs.pop('extra', {})
for key, value in six.iteritems(kwargs.copy()):
if key in VALID_OPTS:
if isinstance(value, VALID_OPTS[key]):
continue
log.error('Error %s: %s is not of type %s', key, value, VALID_OPTS[key])
kwargs.pop(key)
return __utils__['dictupdate.update'](kwargs, extra)
def request_instance(vm_, conn=None, call=None):
'''
Request an instance to be built
'''
if call == 'function':
# Technically this function may be called other ways too, but it
# definitely cannot be called with --function.
raise SaltCloudSystemExit(
'The request_instance action must be called with -a or --action.'
)
kwargs = copy.deepcopy(vm_)
log.info('Creating Cloud VM %s', vm_['name'])
__utils__['cloud.check_name'](vm_['name'], 'a-zA-Z0-9._-')
conn = get_conn()
userdata = config.get_cloud_config_value(
'userdata', vm_, __opts__, search_global=False, default=None
)
if userdata is not None and os.path.isfile(userdata):
try:
with __utils__['files.fopen'](userdata, 'r') as fp_:
kwargs['userdata'] = __utils__['cloud.userdata_template'](
__opts__, vm_, fp_.read()
)
except Exception as exc:
log.exception(
'Failed to read userdata from %s: %s', userdata, exc)
if 'size' in kwargs:
kwargs['flavor'] = kwargs.pop('size')
kwargs['key_name'] = config.get_cloud_config_value(
'ssh_key_name', vm_, __opts__, search_global=False, default=None
)
kwargs['wait'] = True
try:
conn.create_server(**_clean_create_kwargs(**kwargs))
except shade.exc.OpenStackCloudException as exc:
log.error('Error creating server %s: %s', vm_['name'], exc)
destroy(vm_['name'], conn=conn, call='action')
raise SaltCloudSystemExit(six.text_type(exc))
return show_instance(vm_['name'], conn=conn, call='action')
def create(vm_):
'''
Create a single VM from a data dict
'''
deploy = config.get_cloud_config_value('deploy', vm_, __opts__)
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 ssh_key_file \'{0}\' does not exist'.format(
key_filename
)
)
vm_['key_filename'] = key_filename
__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']
)
conn = get_conn()
if 'instance_id' in vm_:
# This was probably created via another process, and doesn't have
# things like salt keys created yet, so let's create them now.
if 'pub_key' not in vm_ and 'priv_key' not in vm_:
log.debug('Generating minion keys for \'%s\'', vm_['name'])
vm_['priv_key'], vm_['pub_key'] = __utils__['cloud.gen_keys'](
config.get_cloud_config_value(
'keysize',
vm_,
__opts__
)
)
else:
# Put together all of the information required to request the instance,
# and then fire off the request for it
request_instance(conn=conn, call='action', vm_=vm_)
data = show_instance(vm_.get('instance_id', vm_['name']), conn=conn, call='action')
log.debug('VM is now running')
def __query_node(vm_):
data = show_instance(vm_['name'], conn=conn, call='action')
if 'wait_for_metadata' in vm_:
for key, value in six.iteritems(vm_.get('wait_for_metadata', {})):
log.debug('Waiting for metadata: %s=%s', key, value)
if data['metadata'].get(key, None) != value:
log.debug('Metadata is not ready: %s=%s', key, data['metadata'].get(key))
return False
return preferred_ip(vm_, data[ssh_interface(vm_)])
try:
ip_address = __utils__['cloud.wait_for_fun'](
__query_node,
vm_=vm_
)
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))
log.debug('Using IP address %s', ip_address)
salt_interface = __utils__['cloud.get_salt_interface'](vm_, __opts__)
salt_ip_address = preferred_ip(vm_, data[salt_interface])
log.debug('Salt interface set to: %s', salt_ip_address)
if not ip_address:
raise SaltCloudSystemExit('A valid IP address was not found')
vm_['ssh_host'] = ip_address
vm_['salt_host'] = salt_ip_address
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)
)
event_data = {
'name': vm_['name'],
'profile': vm_['profile'],
'provider': vm_['driver'],
'instance_id': data['id'],
'floating_ips': data['floating_ips'],
'fixed_ips': data['fixed_ips'],
'private_ips': data['private_ips'],
'public_ips': data['public_ips'],
}
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args=__utils__['cloud.filter_event']('created', event_data, list(event_data)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
__utils__['cloud.cachedir_index_add'](vm_['name'], vm_['profile'], 'nova', vm_['driver'])
return ret
def destroy(name, conn=None, call=None):
'''
Delete a single VM
'''
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']
)
if not conn:
conn = get_conn()
node = show_instance(name, conn=conn, call='action')
log.info('Destroying VM: %s', name)
ret = conn.delete_server(name)
if ret:
log.info('Destroyed VM: %s', name)
# Fire destroy action
__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('delete_sshkeys', False) is True:
__utils__['cloud.remove_sshkey'](getattr(node, __opts__.get('ssh_interface', 'public_ips'))[0])
if __opts__.get('update_cachedir', False) is True:
__utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__)
__utils__['cloud.cachedir_index_del'](name)
return True
log.error('Failed to Destroy VM: %s', name)
return False
def call(conn=None, call=None, kwargs=None):
'''
Call function from shade.
func
function to call from shade.openstackcloud library
CLI Example
.. code-block:: bash
salt-cloud -f call myopenstack func=list_images
t sujksalt-cloud -f call myopenstack func=create_network name=mysubnet
'''
if call == 'action':
raise SaltCloudSystemExit(
'The call function must be called with '
'-f or --function.'
)
if 'func' not in kwargs:
raise SaltCloudSystemExit(
'No `func` argument passed'
)
if conn is None:
conn = get_conn()
func = kwargs.pop('func')
for key, value in kwargs.items():
try:
kwargs[key] = __utils__['json.loads'](value)
except ValueError:
continue
try:
return getattr(conn, func)(**kwargs)
except shade.exc.OpenStackCloudException as exc:
log.error('Error running %s: %s', func, exc)
raise SaltCloudSystemExit(six.text_type(exc))
|
saltstack/salt
|
salt/cloud/clouds/openstack.py
|
list_nodes_select
|
python
|
def list_nodes_select(conn=None, call=None):
'''
Return a list of VMs with the fields from `query.selection`
CLI Example
.. code-block:: bash
salt-cloud -f list_nodes_full myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_select function must be called with -f or --function.'
)
return __utils__['cloud.list_nodes_select'](
list_nodes(conn, 'function'), __opts__['query.selection'], call,
)
|
Return a list of VMs with the fields from `query.selection`
CLI Example
.. code-block:: bash
salt-cloud -f list_nodes_full myopenstack
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/openstack.py#L421-L438
|
[
"def list_nodes(conn=None, call=None):\n '''\n Return a list of VMs\n\n CLI Example\n\n .. code-block:: bash\n\n salt-cloud -f list_nodes myopenstack\n\n '''\n if call == 'action':\n raise SaltCloudSystemExit(\n 'The list_nodes function must be called with -f or --function.'\n )\n ret = {}\n for node, info in list_nodes_full(conn=conn).items():\n for key in ('id', 'name', 'size', 'state', 'private_ips', 'public_ips', 'floating_ips', 'fixed_ips', 'image'):\n ret.setdefault(node, {}).setdefault(key, info.get(key))\n\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Openstack Cloud Driver
======================
:depends: `shade>=1.19.0 <https://pypi.python.org/pypi/shade>`_
OpenStack is an open source project that is in use by a number a cloud
providers, each of which have their own ways of using it.
This OpenStack driver uses a the shade python module which is managed by the
OpenStack Infra team. This module is written to handle all the different
versions of different OpenStack tools for salt, so most commands are just passed
over to the module to handle everything.
Provider
--------
There are two ways to configure providers for this driver. The first one is to
just let shade handle everything, and configure using os-client-config_ and
setting up `/etc/openstack/clouds.yml`.
.. code-block:: yaml
clouds:
democloud:
region_name: RegionOne
auth:
username: 'demo'
password: secret
project_name: 'demo'
auth_url: 'http://openstack/identity'
And then this can be referenced in the salt provider based on the `democloud`
name.
.. code-block:: yaml
myopenstack:
driver: openstack
cloud: democloud
region_name: RegionOne
This allows for just using one configuration for salt-cloud and for any other
openstack tools which are all using `/etc/openstack/clouds.yml`
The other method allows for specifying everything in the provider config,
instead of using the extra configuration file. This will allow for passing
salt-cloud configs only through pillars for minions without having to write a
clouds.yml file on each minion.abs
.. code-block:: yaml
myopenstack:
driver: openstack
region_name: RegionOne
auth:
username: 'demo'
password: secret
project_name: 'demo'
auth_url: 'http://openstack/identity'
Or if you need to use a profile to setup some extra stuff, it can be passed as a
`profile` to use any of the vendor_ config options.
.. code-block:: yaml
myrackspace:
driver: openstack
profile: rackspace
auth:
username: rackusername
api_key: myapikey
region_name: ORD
auth_type: rackspace_apikey
And this will pull in the profile for rackspace and setup all the correct
options for the auth_url and different api versions for services.
Profile
-------
Most of the options for building servers are just passed on to the
create_server_ function from shade.
The salt specific ones are:
- ssh_key_file: The path to the ssh key that should be used to login to the machine to bootstrap it
- ssh_key_file: The name of the keypair in openstack
- userdata_template: The renderer to use if the userdata is a file that is templated. Default: False
- ssh_interface: The interface to use to login for bootstrapping: public_ips, private_ips, floating_ips, fixed_ips
.. code-block:: yaml
centos:
provider: myopenstack
image: CentOS 7
size: ds1G
ssh_key_name: mykey
ssh_key_file: /root/.ssh/id_rsa
This is the minimum setup required.
If metadata is set to make sure that the host has finished setting up the
`wait_for_metadata` can be set.
.. code-block:: yaml
centos:
provider: myopenstack
image: CentOS 7
size: ds1G
ssh_key_name: mykey
ssh_key_file: /root/.ssh/id_rsa
meta:
build_config: rack_user_only
wait_for_metadata:
rax_service_level_automation: Complete
rackconnect_automation_status: DEPLOYED
Anything else from the create_server_ docs can be passed through here.
- **image**: Image dict, name or ID to boot with. image is required
unless boot_volume is given.
- **flavor**: Flavor dict, name or ID to boot onto.
- **auto_ip**: Whether to take actions to find a routable IP for
the server. (defaults to True)
- **ips**: List of IPs to attach to the server (defaults to None)
- **ip_pool**: Name of the network or floating IP pool to get an
address from. (defaults to None)
- **root_volume**: Name or ID of a volume to boot from
(defaults to None - deprecated, use boot_volume)
- **boot_volume**: Name or ID of a volume to boot from
(defaults to None)
- **terminate_volume**: If booting from a volume, whether it should
be deleted when the server is destroyed.
(defaults to False)
- **volumes**: (optional) A list of volumes to attach to the server
- **meta**: (optional) A dict of arbitrary key/value metadata to
store for this server. Both keys and values must be
<=255 characters.
- **files**: (optional, deprecated) A dict of files to overwrite
on the server upon boot. Keys are file names (i.e.
``/etc/passwd``) and values
are the file contents (either as a string or as a
file-like object). A maximum of five entries is allowed,
and each file must be 10k or less.
- **reservation_id**: a UUID for the set of servers being requested.
- **min_count**: (optional extension) The minimum number of
servers to launch.
- **max_count**: (optional extension) The maximum number of
servers to launch.
- **security_groups**: A list of security group names
- **userdata**: user data to pass to be exposed by the metadata
server this can be a file type object as well or a
string.
- **key_name**: (optional extension) name of previously created
keypair to inject into the instance.
- **availability_zone**: Name of the availability zone for instance
placement.
- **block_device_mapping**: (optional) A dict of block
device mappings for this server.
- **block_device_mapping_v2**: (optional) A dict of block
device mappings for this server.
- **nics**: (optional extension) an ordered list of nics to be
added to this server, with information about
connected networks, fixed IPs, port etc.
- **scheduler_hints**: (optional extension) arbitrary key-value pairs
specified by the client to help boot an instance
- **config_drive**: (optional extension) value for config drive
either boolean, or volume-id
- **disk_config**: (optional extension) control how the disk is
partitioned when the server is created. possible
values are 'AUTO' or 'MANUAL'.
- **admin_pass**: (optional extension) add a user supplied admin
password.
- **timeout**: (optional) Seconds to wait, defaults to 60.
See the ``wait`` parameter.
- **reuse_ips**: (optional) Whether to attempt to reuse pre-existing
floating ips should a floating IP be
needed (defaults to True)
- **network**: (optional) Network dict or name or ID to attach the
server to. Mutually exclusive with the nics parameter.
Can also be be a list of network names or IDs or
network dicts.
- **boot_from_volume**: Whether to boot from volume. 'boot_volume'
implies True, but boot_from_volume=True with
no boot_volume is valid and will create a
volume from the image and use that.
- **volume_size**: When booting an image from volume, how big should
the created volume be? Defaults to 50.
- **nat_destination**: Which network should a created floating IP
be attached to, if it's not possible to
infer from the cloud's configuration.
(Optional, defaults to None)
- **group**: ServerGroup dict, name or id to boot the server in.
If a group is provided in both scheduler_hints and in
the group param, the group param will win.
(Optional, defaults to None)
.. note::
If there is anything added, that is not in this list, it can be added to an `extras`
dictionary for the profile, and that will be to the create_server function.
.. _create_server: https://docs.openstack.org/shade/latest/user/usage.html#shade.OpenStackCloud.create_server
.. _vendor: https://docs.openstack.org/os-client-config/latest/user/vendor-support.html
.. _os-client-config: https://docs.openstack.org/os-client-config/latest/user/configuration.html#config-files
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import Python Libs
import copy
import logging
import os
import pprint
import socket
# Import Salt Libs
import salt.utils.versions
import salt.config as config
from salt.ext import six
from salt.exceptions import (
SaltCloudSystemExit,
SaltCloudExecutionTimeout,
SaltCloudExecutionFailure,
SaltCloudConfigError,
)
# Import 3rd-Party Libs
try:
import shade
import shade.openstackcloud
import shade.exc
import os_client_config
HAS_SHADE = (
salt.utils.versions._LooseVersion(shade.__version__) >= salt.utils.versions._LooseVersion('1.19.0'),
'Please install newer version of shade: >= 1.19.0'
)
except ImportError:
HAS_SHADE = (False, 'Install pypi module shade >= 1.19.0')
log = logging.getLogger(__name__)
__virtualname__ = 'openstack'
def __virtual__():
'''
Check for OpenStack dependencies
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return HAS_SHADE
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__, __active_provider_name__ or __virtualname__,
('auth', 'region_name'), log_message=False,
) or config.is_provider_configured(
__opts__, __active_provider_name__ or __virtualname__,
('cloud', 'region_name')
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
deps = {
'shade': shade[0],
'os_client_config': shade[0],
}
return config.check_driver_dependencies(
__virtualname__,
deps
)
def preferred_ip(vm_, ips):
'''
Return the preferred Internet protocol. Either 'ipv4' (default) or 'ipv6'.
'''
proto = config.get_cloud_config_value(
'protocol', vm_, __opts__, default='ipv4', search_global=False
)
family = socket.AF_INET
if proto == 'ipv6':
family = socket.AF_INET6
for ip in ips:
try:
socket.inet_pton(family, ip)
return ip
except Exception:
continue
return False
def ssh_interface(vm_):
'''
Return the ssh_interface type to connect to. Either 'public_ips' (default)
or 'private_ips'.
'''
return config.get_cloud_config_value('ssh_interface', vm_, __opts__, default='public_ips', search_global=False)
def get_conn():
'''
Return a conn object for the passed VM data
'''
if __active_provider_name__ in __context__:
return __context__[__active_provider_name__]
vm_ = get_configured_provider()
profile = vm_.pop('profile', None)
if profile is not None:
vm_ = __utils__['dictupdate.update'](os_client_config.vendors.get_profile(profile), vm_)
conn = shade.openstackcloud.OpenStackCloud(cloud_config=None, **vm_)
if __active_provider_name__ is not None:
__context__[__active_provider_name__] = conn
return conn
def list_nodes(conn=None, call=None):
'''
Return a list of VMs
CLI Example
.. code-block:: bash
salt-cloud -f list_nodes myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
ret = {}
for node, info in list_nodes_full(conn=conn).items():
for key in ('id', 'name', 'size', 'state', 'private_ips', 'public_ips', 'floating_ips', 'fixed_ips', 'image'):
ret.setdefault(node, {}).setdefault(key, info.get(key))
return ret
def list_nodes_min(conn=None, call=None):
'''
Return a list of VMs with minimal information
CLI Example
.. code-block:: bash
salt-cloud -f list_nodes_min myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_min function must be called with -f or --function.'
)
if conn is None:
conn = get_conn()
ret = {}
for node in conn.list_servers(bare=True):
ret[node.name] = {'id': node.id, 'state': node.status}
return ret
def _get_ips(node, addr_type='public'):
ret = []
for _, interface in node.addresses.items():
for addr in interface:
if addr_type in ('floating', 'fixed') and addr_type == addr.get('OS-EXT-IPS:type'):
ret.append(addr['addr'])
elif addr_type == 'public' and __utils__['cloud.is_public_ip'](addr['addr']):
ret.append(addr['addr'])
elif addr_type == 'private' and not __utils__['cloud.is_public_ip'](addr['addr']):
ret.append(addr['addr'])
return ret
def list_nodes_full(conn=None, call=None):
'''
Return a list of VMs with all the information about them
CLI Example
.. code-block:: bash
salt-cloud -f list_nodes_full myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or --function.'
)
if conn is None:
conn = get_conn()
ret = {}
for node in conn.list_servers(detailed=True):
ret[node.name] = dict(node)
ret[node.name]['id'] = node.id
ret[node.name]['name'] = node.name
ret[node.name]['size'] = node.flavor.name
ret[node.name]['state'] = node.status
ret[node.name]['private_ips'] = _get_ips(node, 'private')
ret[node.name]['public_ips'] = _get_ips(node, 'public')
ret[node.name]['floating_ips'] = _get_ips(node, 'floating')
ret[node.name]['fixed_ips'] = _get_ips(node, 'fixed')
ret[node.name]['image'] = node.image.name
return ret
def show_instance(name, conn=None, call=None):
'''
Get VM on this OpenStack account
name
name of the instance
CLI Example
.. code-block:: bash
salt-cloud -a show_instance myserver
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
if conn is None:
conn = get_conn()
node = conn.get_server(name, bare=True)
ret = dict(node)
ret['id'] = node.id
ret['name'] = node.name
ret['size'] = conn.get_flavor(node.flavor.id).name
ret['state'] = node.status
ret['private_ips'] = _get_ips(node, 'private')
ret['public_ips'] = _get_ips(node, 'public')
ret['floating_ips'] = _get_ips(node, 'floating')
ret['fixed_ips'] = _get_ips(node, 'fixed')
if isinstance(node.image, six.string_types):
ret['image'] = node.image
else:
ret['image'] = conn.get_image(node.image.id).name
return ret
def avail_images(conn=None, call=None):
'''
List available images for OpenStack
CLI Example
.. code-block:: bash
salt-cloud -f avail_images myopenstack
salt-cloud --list-images myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
if conn is None:
conn = get_conn()
return conn.list_images()
def avail_sizes(conn=None, call=None):
'''
List available sizes for OpenStack
CLI Example
.. code-block:: bash
salt-cloud -f avail_sizes myopenstack
salt-cloud --list-sizes myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
if conn is None:
conn = get_conn()
return conn.list_flavors()
def list_networks(conn=None, call=None):
'''
List networks for OpenStack
CLI Example
.. code-block:: bash
salt-cloud -f list_networks myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_networks function must be called with '
'-f or --function'
)
if conn is None:
conn = get_conn()
return conn.list_networks()
def list_subnets(conn=None, call=None, kwargs=None):
'''
List subnets in a virtual network
network
network to list subnets of
.. code-block:: bash
salt-cloud -f list_subnets myopenstack network=salt-net
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_subnets function must be called with '
'-f or --function.'
)
if conn is None:
conn = get_conn()
if kwargs is None or (isinstance(kwargs, dict) and 'network' not in kwargs):
raise SaltCloudSystemExit(
'A `network` must be specified'
)
return conn.list_subnets(filters={'network': kwargs['network']})
def _clean_create_kwargs(**kwargs):
'''
Sanatize kwargs to be sent to create_server
'''
VALID_OPTS = {
'name': six.string_types,
'image': six.string_types,
'flavor': six.string_types,
'auto_ip': bool,
'ips': list,
'ip_pool': six.string_types,
'root_volume': six.string_types,
'boot_volume': six.string_types,
'terminate_volume': bool,
'volumes': list,
'meta': dict,
'files': dict,
'reservation_id': six.string_types,
'security_groups': list,
'key_name': six.string_types,
'availability_zone': six.string_types,
'block_device_mapping': dict,
'block_device_mapping_v2': dict,
'nics': list,
'scheduler_hints': dict,
'config_drive': bool,
'disk_config': six.string_types, # AUTO or MANUAL
'admin_pass': six.string_types,
'wait': bool,
'timeout': int,
'reuse_ips': bool,
'network': dict,
'boot_from_volume': bool,
'volume_size': int,
'nat_destination': six.string_types,
'group': six.string_types,
'userdata': six.string_types,
}
extra = kwargs.pop('extra', {})
for key, value in six.iteritems(kwargs.copy()):
if key in VALID_OPTS:
if isinstance(value, VALID_OPTS[key]):
continue
log.error('Error %s: %s is not of type %s', key, value, VALID_OPTS[key])
kwargs.pop(key)
return __utils__['dictupdate.update'](kwargs, extra)
def request_instance(vm_, conn=None, call=None):
'''
Request an instance to be built
'''
if call == 'function':
# Technically this function may be called other ways too, but it
# definitely cannot be called with --function.
raise SaltCloudSystemExit(
'The request_instance action must be called with -a or --action.'
)
kwargs = copy.deepcopy(vm_)
log.info('Creating Cloud VM %s', vm_['name'])
__utils__['cloud.check_name'](vm_['name'], 'a-zA-Z0-9._-')
conn = get_conn()
userdata = config.get_cloud_config_value(
'userdata', vm_, __opts__, search_global=False, default=None
)
if userdata is not None and os.path.isfile(userdata):
try:
with __utils__['files.fopen'](userdata, 'r') as fp_:
kwargs['userdata'] = __utils__['cloud.userdata_template'](
__opts__, vm_, fp_.read()
)
except Exception as exc:
log.exception(
'Failed to read userdata from %s: %s', userdata, exc)
if 'size' in kwargs:
kwargs['flavor'] = kwargs.pop('size')
kwargs['key_name'] = config.get_cloud_config_value(
'ssh_key_name', vm_, __opts__, search_global=False, default=None
)
kwargs['wait'] = True
try:
conn.create_server(**_clean_create_kwargs(**kwargs))
except shade.exc.OpenStackCloudException as exc:
log.error('Error creating server %s: %s', vm_['name'], exc)
destroy(vm_['name'], conn=conn, call='action')
raise SaltCloudSystemExit(six.text_type(exc))
return show_instance(vm_['name'], conn=conn, call='action')
def create(vm_):
'''
Create a single VM from a data dict
'''
deploy = config.get_cloud_config_value('deploy', vm_, __opts__)
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 ssh_key_file \'{0}\' does not exist'.format(
key_filename
)
)
vm_['key_filename'] = key_filename
__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']
)
conn = get_conn()
if 'instance_id' in vm_:
# This was probably created via another process, and doesn't have
# things like salt keys created yet, so let's create them now.
if 'pub_key' not in vm_ and 'priv_key' not in vm_:
log.debug('Generating minion keys for \'%s\'', vm_['name'])
vm_['priv_key'], vm_['pub_key'] = __utils__['cloud.gen_keys'](
config.get_cloud_config_value(
'keysize',
vm_,
__opts__
)
)
else:
# Put together all of the information required to request the instance,
# and then fire off the request for it
request_instance(conn=conn, call='action', vm_=vm_)
data = show_instance(vm_.get('instance_id', vm_['name']), conn=conn, call='action')
log.debug('VM is now running')
def __query_node(vm_):
data = show_instance(vm_['name'], conn=conn, call='action')
if 'wait_for_metadata' in vm_:
for key, value in six.iteritems(vm_.get('wait_for_metadata', {})):
log.debug('Waiting for metadata: %s=%s', key, value)
if data['metadata'].get(key, None) != value:
log.debug('Metadata is not ready: %s=%s', key, data['metadata'].get(key))
return False
return preferred_ip(vm_, data[ssh_interface(vm_)])
try:
ip_address = __utils__['cloud.wait_for_fun'](
__query_node,
vm_=vm_
)
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))
log.debug('Using IP address %s', ip_address)
salt_interface = __utils__['cloud.get_salt_interface'](vm_, __opts__)
salt_ip_address = preferred_ip(vm_, data[salt_interface])
log.debug('Salt interface set to: %s', salt_ip_address)
if not ip_address:
raise SaltCloudSystemExit('A valid IP address was not found')
vm_['ssh_host'] = ip_address
vm_['salt_host'] = salt_ip_address
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)
)
event_data = {
'name': vm_['name'],
'profile': vm_['profile'],
'provider': vm_['driver'],
'instance_id': data['id'],
'floating_ips': data['floating_ips'],
'fixed_ips': data['fixed_ips'],
'private_ips': data['private_ips'],
'public_ips': data['public_ips'],
}
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args=__utils__['cloud.filter_event']('created', event_data, list(event_data)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
__utils__['cloud.cachedir_index_add'](vm_['name'], vm_['profile'], 'nova', vm_['driver'])
return ret
def destroy(name, conn=None, call=None):
'''
Delete a single VM
'''
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']
)
if not conn:
conn = get_conn()
node = show_instance(name, conn=conn, call='action')
log.info('Destroying VM: %s', name)
ret = conn.delete_server(name)
if ret:
log.info('Destroyed VM: %s', name)
# Fire destroy action
__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('delete_sshkeys', False) is True:
__utils__['cloud.remove_sshkey'](getattr(node, __opts__.get('ssh_interface', 'public_ips'))[0])
if __opts__.get('update_cachedir', False) is True:
__utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__)
__utils__['cloud.cachedir_index_del'](name)
return True
log.error('Failed to Destroy VM: %s', name)
return False
def call(conn=None, call=None, kwargs=None):
'''
Call function from shade.
func
function to call from shade.openstackcloud library
CLI Example
.. code-block:: bash
salt-cloud -f call myopenstack func=list_images
t sujksalt-cloud -f call myopenstack func=create_network name=mysubnet
'''
if call == 'action':
raise SaltCloudSystemExit(
'The call function must be called with '
'-f or --function.'
)
if 'func' not in kwargs:
raise SaltCloudSystemExit(
'No `func` argument passed'
)
if conn is None:
conn = get_conn()
func = kwargs.pop('func')
for key, value in kwargs.items():
try:
kwargs[key] = __utils__['json.loads'](value)
except ValueError:
continue
try:
return getattr(conn, func)(**kwargs)
except shade.exc.OpenStackCloudException as exc:
log.error('Error running %s: %s', func, exc)
raise SaltCloudSystemExit(six.text_type(exc))
|
saltstack/salt
|
salt/cloud/clouds/openstack.py
|
show_instance
|
python
|
def show_instance(name, conn=None, call=None):
'''
Get VM on this OpenStack account
name
name of the instance
CLI Example
.. code-block:: bash
salt-cloud -a show_instance myserver
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
if conn is None:
conn = get_conn()
node = conn.get_server(name, bare=True)
ret = dict(node)
ret['id'] = node.id
ret['name'] = node.name
ret['size'] = conn.get_flavor(node.flavor.id).name
ret['state'] = node.status
ret['private_ips'] = _get_ips(node, 'private')
ret['public_ips'] = _get_ips(node, 'public')
ret['floating_ips'] = _get_ips(node, 'floating')
ret['fixed_ips'] = _get_ips(node, 'fixed')
if isinstance(node.image, six.string_types):
ret['image'] = node.image
else:
ret['image'] = conn.get_image(node.image.id).name
return ret
|
Get VM on this OpenStack account
name
name of the instance
CLI Example
.. code-block:: bash
salt-cloud -a show_instance myserver
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/openstack.py#L441-L477
|
[
"def get_conn():\n '''\n Return a conn object for the passed VM data\n '''\n if __active_provider_name__ in __context__:\n return __context__[__active_provider_name__]\n vm_ = get_configured_provider()\n profile = vm_.pop('profile', None)\n if profile is not None:\n vm_ = __utils__['dictupdate.update'](os_client_config.vendors.get_profile(profile), vm_)\n conn = shade.openstackcloud.OpenStackCloud(cloud_config=None, **vm_)\n if __active_provider_name__ is not None:\n __context__[__active_provider_name__] = conn\n return conn\n",
"def _get_ips(node, addr_type='public'):\n ret = []\n for _, interface in node.addresses.items():\n for addr in interface:\n if addr_type in ('floating', 'fixed') and addr_type == addr.get('OS-EXT-IPS:type'):\n ret.append(addr['addr'])\n elif addr_type == 'public' and __utils__['cloud.is_public_ip'](addr['addr']):\n ret.append(addr['addr'])\n elif addr_type == 'private' and not __utils__['cloud.is_public_ip'](addr['addr']):\n ret.append(addr['addr'])\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Openstack Cloud Driver
======================
:depends: `shade>=1.19.0 <https://pypi.python.org/pypi/shade>`_
OpenStack is an open source project that is in use by a number a cloud
providers, each of which have their own ways of using it.
This OpenStack driver uses a the shade python module which is managed by the
OpenStack Infra team. This module is written to handle all the different
versions of different OpenStack tools for salt, so most commands are just passed
over to the module to handle everything.
Provider
--------
There are two ways to configure providers for this driver. The first one is to
just let shade handle everything, and configure using os-client-config_ and
setting up `/etc/openstack/clouds.yml`.
.. code-block:: yaml
clouds:
democloud:
region_name: RegionOne
auth:
username: 'demo'
password: secret
project_name: 'demo'
auth_url: 'http://openstack/identity'
And then this can be referenced in the salt provider based on the `democloud`
name.
.. code-block:: yaml
myopenstack:
driver: openstack
cloud: democloud
region_name: RegionOne
This allows for just using one configuration for salt-cloud and for any other
openstack tools which are all using `/etc/openstack/clouds.yml`
The other method allows for specifying everything in the provider config,
instead of using the extra configuration file. This will allow for passing
salt-cloud configs only through pillars for minions without having to write a
clouds.yml file on each minion.abs
.. code-block:: yaml
myopenstack:
driver: openstack
region_name: RegionOne
auth:
username: 'demo'
password: secret
project_name: 'demo'
auth_url: 'http://openstack/identity'
Or if you need to use a profile to setup some extra stuff, it can be passed as a
`profile` to use any of the vendor_ config options.
.. code-block:: yaml
myrackspace:
driver: openstack
profile: rackspace
auth:
username: rackusername
api_key: myapikey
region_name: ORD
auth_type: rackspace_apikey
And this will pull in the profile for rackspace and setup all the correct
options for the auth_url and different api versions for services.
Profile
-------
Most of the options for building servers are just passed on to the
create_server_ function from shade.
The salt specific ones are:
- ssh_key_file: The path to the ssh key that should be used to login to the machine to bootstrap it
- ssh_key_file: The name of the keypair in openstack
- userdata_template: The renderer to use if the userdata is a file that is templated. Default: False
- ssh_interface: The interface to use to login for bootstrapping: public_ips, private_ips, floating_ips, fixed_ips
.. code-block:: yaml
centos:
provider: myopenstack
image: CentOS 7
size: ds1G
ssh_key_name: mykey
ssh_key_file: /root/.ssh/id_rsa
This is the minimum setup required.
If metadata is set to make sure that the host has finished setting up the
`wait_for_metadata` can be set.
.. code-block:: yaml
centos:
provider: myopenstack
image: CentOS 7
size: ds1G
ssh_key_name: mykey
ssh_key_file: /root/.ssh/id_rsa
meta:
build_config: rack_user_only
wait_for_metadata:
rax_service_level_automation: Complete
rackconnect_automation_status: DEPLOYED
Anything else from the create_server_ docs can be passed through here.
- **image**: Image dict, name or ID to boot with. image is required
unless boot_volume is given.
- **flavor**: Flavor dict, name or ID to boot onto.
- **auto_ip**: Whether to take actions to find a routable IP for
the server. (defaults to True)
- **ips**: List of IPs to attach to the server (defaults to None)
- **ip_pool**: Name of the network or floating IP pool to get an
address from. (defaults to None)
- **root_volume**: Name or ID of a volume to boot from
(defaults to None - deprecated, use boot_volume)
- **boot_volume**: Name or ID of a volume to boot from
(defaults to None)
- **terminate_volume**: If booting from a volume, whether it should
be deleted when the server is destroyed.
(defaults to False)
- **volumes**: (optional) A list of volumes to attach to the server
- **meta**: (optional) A dict of arbitrary key/value metadata to
store for this server. Both keys and values must be
<=255 characters.
- **files**: (optional, deprecated) A dict of files to overwrite
on the server upon boot. Keys are file names (i.e.
``/etc/passwd``) and values
are the file contents (either as a string or as a
file-like object). A maximum of five entries is allowed,
and each file must be 10k or less.
- **reservation_id**: a UUID for the set of servers being requested.
- **min_count**: (optional extension) The minimum number of
servers to launch.
- **max_count**: (optional extension) The maximum number of
servers to launch.
- **security_groups**: A list of security group names
- **userdata**: user data to pass to be exposed by the metadata
server this can be a file type object as well or a
string.
- **key_name**: (optional extension) name of previously created
keypair to inject into the instance.
- **availability_zone**: Name of the availability zone for instance
placement.
- **block_device_mapping**: (optional) A dict of block
device mappings for this server.
- **block_device_mapping_v2**: (optional) A dict of block
device mappings for this server.
- **nics**: (optional extension) an ordered list of nics to be
added to this server, with information about
connected networks, fixed IPs, port etc.
- **scheduler_hints**: (optional extension) arbitrary key-value pairs
specified by the client to help boot an instance
- **config_drive**: (optional extension) value for config drive
either boolean, or volume-id
- **disk_config**: (optional extension) control how the disk is
partitioned when the server is created. possible
values are 'AUTO' or 'MANUAL'.
- **admin_pass**: (optional extension) add a user supplied admin
password.
- **timeout**: (optional) Seconds to wait, defaults to 60.
See the ``wait`` parameter.
- **reuse_ips**: (optional) Whether to attempt to reuse pre-existing
floating ips should a floating IP be
needed (defaults to True)
- **network**: (optional) Network dict or name or ID to attach the
server to. Mutually exclusive with the nics parameter.
Can also be be a list of network names or IDs or
network dicts.
- **boot_from_volume**: Whether to boot from volume. 'boot_volume'
implies True, but boot_from_volume=True with
no boot_volume is valid and will create a
volume from the image and use that.
- **volume_size**: When booting an image from volume, how big should
the created volume be? Defaults to 50.
- **nat_destination**: Which network should a created floating IP
be attached to, if it's not possible to
infer from the cloud's configuration.
(Optional, defaults to None)
- **group**: ServerGroup dict, name or id to boot the server in.
If a group is provided in both scheduler_hints and in
the group param, the group param will win.
(Optional, defaults to None)
.. note::
If there is anything added, that is not in this list, it can be added to an `extras`
dictionary for the profile, and that will be to the create_server function.
.. _create_server: https://docs.openstack.org/shade/latest/user/usage.html#shade.OpenStackCloud.create_server
.. _vendor: https://docs.openstack.org/os-client-config/latest/user/vendor-support.html
.. _os-client-config: https://docs.openstack.org/os-client-config/latest/user/configuration.html#config-files
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import Python Libs
import copy
import logging
import os
import pprint
import socket
# Import Salt Libs
import salt.utils.versions
import salt.config as config
from salt.ext import six
from salt.exceptions import (
SaltCloudSystemExit,
SaltCloudExecutionTimeout,
SaltCloudExecutionFailure,
SaltCloudConfigError,
)
# Import 3rd-Party Libs
try:
import shade
import shade.openstackcloud
import shade.exc
import os_client_config
HAS_SHADE = (
salt.utils.versions._LooseVersion(shade.__version__) >= salt.utils.versions._LooseVersion('1.19.0'),
'Please install newer version of shade: >= 1.19.0'
)
except ImportError:
HAS_SHADE = (False, 'Install pypi module shade >= 1.19.0')
log = logging.getLogger(__name__)
__virtualname__ = 'openstack'
def __virtual__():
'''
Check for OpenStack dependencies
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return HAS_SHADE
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__, __active_provider_name__ or __virtualname__,
('auth', 'region_name'), log_message=False,
) or config.is_provider_configured(
__opts__, __active_provider_name__ or __virtualname__,
('cloud', 'region_name')
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
deps = {
'shade': shade[0],
'os_client_config': shade[0],
}
return config.check_driver_dependencies(
__virtualname__,
deps
)
def preferred_ip(vm_, ips):
'''
Return the preferred Internet protocol. Either 'ipv4' (default) or 'ipv6'.
'''
proto = config.get_cloud_config_value(
'protocol', vm_, __opts__, default='ipv4', search_global=False
)
family = socket.AF_INET
if proto == 'ipv6':
family = socket.AF_INET6
for ip in ips:
try:
socket.inet_pton(family, ip)
return ip
except Exception:
continue
return False
def ssh_interface(vm_):
'''
Return the ssh_interface type to connect to. Either 'public_ips' (default)
or 'private_ips'.
'''
return config.get_cloud_config_value('ssh_interface', vm_, __opts__, default='public_ips', search_global=False)
def get_conn():
'''
Return a conn object for the passed VM data
'''
if __active_provider_name__ in __context__:
return __context__[__active_provider_name__]
vm_ = get_configured_provider()
profile = vm_.pop('profile', None)
if profile is not None:
vm_ = __utils__['dictupdate.update'](os_client_config.vendors.get_profile(profile), vm_)
conn = shade.openstackcloud.OpenStackCloud(cloud_config=None, **vm_)
if __active_provider_name__ is not None:
__context__[__active_provider_name__] = conn
return conn
def list_nodes(conn=None, call=None):
'''
Return a list of VMs
CLI Example
.. code-block:: bash
salt-cloud -f list_nodes myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
ret = {}
for node, info in list_nodes_full(conn=conn).items():
for key in ('id', 'name', 'size', 'state', 'private_ips', 'public_ips', 'floating_ips', 'fixed_ips', 'image'):
ret.setdefault(node, {}).setdefault(key, info.get(key))
return ret
def list_nodes_min(conn=None, call=None):
'''
Return a list of VMs with minimal information
CLI Example
.. code-block:: bash
salt-cloud -f list_nodes_min myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_min function must be called with -f or --function.'
)
if conn is None:
conn = get_conn()
ret = {}
for node in conn.list_servers(bare=True):
ret[node.name] = {'id': node.id, 'state': node.status}
return ret
def _get_ips(node, addr_type='public'):
ret = []
for _, interface in node.addresses.items():
for addr in interface:
if addr_type in ('floating', 'fixed') and addr_type == addr.get('OS-EXT-IPS:type'):
ret.append(addr['addr'])
elif addr_type == 'public' and __utils__['cloud.is_public_ip'](addr['addr']):
ret.append(addr['addr'])
elif addr_type == 'private' and not __utils__['cloud.is_public_ip'](addr['addr']):
ret.append(addr['addr'])
return ret
def list_nodes_full(conn=None, call=None):
'''
Return a list of VMs with all the information about them
CLI Example
.. code-block:: bash
salt-cloud -f list_nodes_full myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or --function.'
)
if conn is None:
conn = get_conn()
ret = {}
for node in conn.list_servers(detailed=True):
ret[node.name] = dict(node)
ret[node.name]['id'] = node.id
ret[node.name]['name'] = node.name
ret[node.name]['size'] = node.flavor.name
ret[node.name]['state'] = node.status
ret[node.name]['private_ips'] = _get_ips(node, 'private')
ret[node.name]['public_ips'] = _get_ips(node, 'public')
ret[node.name]['floating_ips'] = _get_ips(node, 'floating')
ret[node.name]['fixed_ips'] = _get_ips(node, 'fixed')
ret[node.name]['image'] = node.image.name
return ret
def list_nodes_select(conn=None, call=None):
'''
Return a list of VMs with the fields from `query.selection`
CLI Example
.. code-block:: bash
salt-cloud -f list_nodes_full myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_select function must be called with -f or --function.'
)
return __utils__['cloud.list_nodes_select'](
list_nodes(conn, 'function'), __opts__['query.selection'], call,
)
def avail_images(conn=None, call=None):
'''
List available images for OpenStack
CLI Example
.. code-block:: bash
salt-cloud -f avail_images myopenstack
salt-cloud --list-images myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
if conn is None:
conn = get_conn()
return conn.list_images()
def avail_sizes(conn=None, call=None):
'''
List available sizes for OpenStack
CLI Example
.. code-block:: bash
salt-cloud -f avail_sizes myopenstack
salt-cloud --list-sizes myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
if conn is None:
conn = get_conn()
return conn.list_flavors()
def list_networks(conn=None, call=None):
'''
List networks for OpenStack
CLI Example
.. code-block:: bash
salt-cloud -f list_networks myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_networks function must be called with '
'-f or --function'
)
if conn is None:
conn = get_conn()
return conn.list_networks()
def list_subnets(conn=None, call=None, kwargs=None):
'''
List subnets in a virtual network
network
network to list subnets of
.. code-block:: bash
salt-cloud -f list_subnets myopenstack network=salt-net
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_subnets function must be called with '
'-f or --function.'
)
if conn is None:
conn = get_conn()
if kwargs is None or (isinstance(kwargs, dict) and 'network' not in kwargs):
raise SaltCloudSystemExit(
'A `network` must be specified'
)
return conn.list_subnets(filters={'network': kwargs['network']})
def _clean_create_kwargs(**kwargs):
'''
Sanatize kwargs to be sent to create_server
'''
VALID_OPTS = {
'name': six.string_types,
'image': six.string_types,
'flavor': six.string_types,
'auto_ip': bool,
'ips': list,
'ip_pool': six.string_types,
'root_volume': six.string_types,
'boot_volume': six.string_types,
'terminate_volume': bool,
'volumes': list,
'meta': dict,
'files': dict,
'reservation_id': six.string_types,
'security_groups': list,
'key_name': six.string_types,
'availability_zone': six.string_types,
'block_device_mapping': dict,
'block_device_mapping_v2': dict,
'nics': list,
'scheduler_hints': dict,
'config_drive': bool,
'disk_config': six.string_types, # AUTO or MANUAL
'admin_pass': six.string_types,
'wait': bool,
'timeout': int,
'reuse_ips': bool,
'network': dict,
'boot_from_volume': bool,
'volume_size': int,
'nat_destination': six.string_types,
'group': six.string_types,
'userdata': six.string_types,
}
extra = kwargs.pop('extra', {})
for key, value in six.iteritems(kwargs.copy()):
if key in VALID_OPTS:
if isinstance(value, VALID_OPTS[key]):
continue
log.error('Error %s: %s is not of type %s', key, value, VALID_OPTS[key])
kwargs.pop(key)
return __utils__['dictupdate.update'](kwargs, extra)
def request_instance(vm_, conn=None, call=None):
'''
Request an instance to be built
'''
if call == 'function':
# Technically this function may be called other ways too, but it
# definitely cannot be called with --function.
raise SaltCloudSystemExit(
'The request_instance action must be called with -a or --action.'
)
kwargs = copy.deepcopy(vm_)
log.info('Creating Cloud VM %s', vm_['name'])
__utils__['cloud.check_name'](vm_['name'], 'a-zA-Z0-9._-')
conn = get_conn()
userdata = config.get_cloud_config_value(
'userdata', vm_, __opts__, search_global=False, default=None
)
if userdata is not None and os.path.isfile(userdata):
try:
with __utils__['files.fopen'](userdata, 'r') as fp_:
kwargs['userdata'] = __utils__['cloud.userdata_template'](
__opts__, vm_, fp_.read()
)
except Exception as exc:
log.exception(
'Failed to read userdata from %s: %s', userdata, exc)
if 'size' in kwargs:
kwargs['flavor'] = kwargs.pop('size')
kwargs['key_name'] = config.get_cloud_config_value(
'ssh_key_name', vm_, __opts__, search_global=False, default=None
)
kwargs['wait'] = True
try:
conn.create_server(**_clean_create_kwargs(**kwargs))
except shade.exc.OpenStackCloudException as exc:
log.error('Error creating server %s: %s', vm_['name'], exc)
destroy(vm_['name'], conn=conn, call='action')
raise SaltCloudSystemExit(six.text_type(exc))
return show_instance(vm_['name'], conn=conn, call='action')
def create(vm_):
'''
Create a single VM from a data dict
'''
deploy = config.get_cloud_config_value('deploy', vm_, __opts__)
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 ssh_key_file \'{0}\' does not exist'.format(
key_filename
)
)
vm_['key_filename'] = key_filename
__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']
)
conn = get_conn()
if 'instance_id' in vm_:
# This was probably created via another process, and doesn't have
# things like salt keys created yet, so let's create them now.
if 'pub_key' not in vm_ and 'priv_key' not in vm_:
log.debug('Generating minion keys for \'%s\'', vm_['name'])
vm_['priv_key'], vm_['pub_key'] = __utils__['cloud.gen_keys'](
config.get_cloud_config_value(
'keysize',
vm_,
__opts__
)
)
else:
# Put together all of the information required to request the instance,
# and then fire off the request for it
request_instance(conn=conn, call='action', vm_=vm_)
data = show_instance(vm_.get('instance_id', vm_['name']), conn=conn, call='action')
log.debug('VM is now running')
def __query_node(vm_):
data = show_instance(vm_['name'], conn=conn, call='action')
if 'wait_for_metadata' in vm_:
for key, value in six.iteritems(vm_.get('wait_for_metadata', {})):
log.debug('Waiting for metadata: %s=%s', key, value)
if data['metadata'].get(key, None) != value:
log.debug('Metadata is not ready: %s=%s', key, data['metadata'].get(key))
return False
return preferred_ip(vm_, data[ssh_interface(vm_)])
try:
ip_address = __utils__['cloud.wait_for_fun'](
__query_node,
vm_=vm_
)
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))
log.debug('Using IP address %s', ip_address)
salt_interface = __utils__['cloud.get_salt_interface'](vm_, __opts__)
salt_ip_address = preferred_ip(vm_, data[salt_interface])
log.debug('Salt interface set to: %s', salt_ip_address)
if not ip_address:
raise SaltCloudSystemExit('A valid IP address was not found')
vm_['ssh_host'] = ip_address
vm_['salt_host'] = salt_ip_address
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)
)
event_data = {
'name': vm_['name'],
'profile': vm_['profile'],
'provider': vm_['driver'],
'instance_id': data['id'],
'floating_ips': data['floating_ips'],
'fixed_ips': data['fixed_ips'],
'private_ips': data['private_ips'],
'public_ips': data['public_ips'],
}
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args=__utils__['cloud.filter_event']('created', event_data, list(event_data)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
__utils__['cloud.cachedir_index_add'](vm_['name'], vm_['profile'], 'nova', vm_['driver'])
return ret
def destroy(name, conn=None, call=None):
'''
Delete a single VM
'''
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']
)
if not conn:
conn = get_conn()
node = show_instance(name, conn=conn, call='action')
log.info('Destroying VM: %s', name)
ret = conn.delete_server(name)
if ret:
log.info('Destroyed VM: %s', name)
# Fire destroy action
__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('delete_sshkeys', False) is True:
__utils__['cloud.remove_sshkey'](getattr(node, __opts__.get('ssh_interface', 'public_ips'))[0])
if __opts__.get('update_cachedir', False) is True:
__utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__)
__utils__['cloud.cachedir_index_del'](name)
return True
log.error('Failed to Destroy VM: %s', name)
return False
def call(conn=None, call=None, kwargs=None):
'''
Call function from shade.
func
function to call from shade.openstackcloud library
CLI Example
.. code-block:: bash
salt-cloud -f call myopenstack func=list_images
t sujksalt-cloud -f call myopenstack func=create_network name=mysubnet
'''
if call == 'action':
raise SaltCloudSystemExit(
'The call function must be called with '
'-f or --function.'
)
if 'func' not in kwargs:
raise SaltCloudSystemExit(
'No `func` argument passed'
)
if conn is None:
conn = get_conn()
func = kwargs.pop('func')
for key, value in kwargs.items():
try:
kwargs[key] = __utils__['json.loads'](value)
except ValueError:
continue
try:
return getattr(conn, func)(**kwargs)
except shade.exc.OpenStackCloudException as exc:
log.error('Error running %s: %s', func, exc)
raise SaltCloudSystemExit(six.text_type(exc))
|
saltstack/salt
|
salt/cloud/clouds/openstack.py
|
avail_images
|
python
|
def avail_images(conn=None, call=None):
'''
List available images for OpenStack
CLI Example
.. code-block:: bash
salt-cloud -f avail_images myopenstack
salt-cloud --list-images myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
if conn is None:
conn = get_conn()
return conn.list_images()
|
List available images for OpenStack
CLI Example
.. code-block:: bash
salt-cloud -f avail_images myopenstack
salt-cloud --list-images myopenstack
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/openstack.py#L480-L499
|
[
"def get_conn():\n '''\n Return a conn object for the passed VM data\n '''\n if __active_provider_name__ in __context__:\n return __context__[__active_provider_name__]\n vm_ = get_configured_provider()\n profile = vm_.pop('profile', None)\n if profile is not None:\n vm_ = __utils__['dictupdate.update'](os_client_config.vendors.get_profile(profile), vm_)\n conn = shade.openstackcloud.OpenStackCloud(cloud_config=None, **vm_)\n if __active_provider_name__ is not None:\n __context__[__active_provider_name__] = conn\n return conn\n"
] |
# -*- coding: utf-8 -*-
'''
Openstack Cloud Driver
======================
:depends: `shade>=1.19.0 <https://pypi.python.org/pypi/shade>`_
OpenStack is an open source project that is in use by a number a cloud
providers, each of which have their own ways of using it.
This OpenStack driver uses a the shade python module which is managed by the
OpenStack Infra team. This module is written to handle all the different
versions of different OpenStack tools for salt, so most commands are just passed
over to the module to handle everything.
Provider
--------
There are two ways to configure providers for this driver. The first one is to
just let shade handle everything, and configure using os-client-config_ and
setting up `/etc/openstack/clouds.yml`.
.. code-block:: yaml
clouds:
democloud:
region_name: RegionOne
auth:
username: 'demo'
password: secret
project_name: 'demo'
auth_url: 'http://openstack/identity'
And then this can be referenced in the salt provider based on the `democloud`
name.
.. code-block:: yaml
myopenstack:
driver: openstack
cloud: democloud
region_name: RegionOne
This allows for just using one configuration for salt-cloud and for any other
openstack tools which are all using `/etc/openstack/clouds.yml`
The other method allows for specifying everything in the provider config,
instead of using the extra configuration file. This will allow for passing
salt-cloud configs only through pillars for minions without having to write a
clouds.yml file on each minion.abs
.. code-block:: yaml
myopenstack:
driver: openstack
region_name: RegionOne
auth:
username: 'demo'
password: secret
project_name: 'demo'
auth_url: 'http://openstack/identity'
Or if you need to use a profile to setup some extra stuff, it can be passed as a
`profile` to use any of the vendor_ config options.
.. code-block:: yaml
myrackspace:
driver: openstack
profile: rackspace
auth:
username: rackusername
api_key: myapikey
region_name: ORD
auth_type: rackspace_apikey
And this will pull in the profile for rackspace and setup all the correct
options for the auth_url and different api versions for services.
Profile
-------
Most of the options for building servers are just passed on to the
create_server_ function from shade.
The salt specific ones are:
- ssh_key_file: The path to the ssh key that should be used to login to the machine to bootstrap it
- ssh_key_file: The name of the keypair in openstack
- userdata_template: The renderer to use if the userdata is a file that is templated. Default: False
- ssh_interface: The interface to use to login for bootstrapping: public_ips, private_ips, floating_ips, fixed_ips
.. code-block:: yaml
centos:
provider: myopenstack
image: CentOS 7
size: ds1G
ssh_key_name: mykey
ssh_key_file: /root/.ssh/id_rsa
This is the minimum setup required.
If metadata is set to make sure that the host has finished setting up the
`wait_for_metadata` can be set.
.. code-block:: yaml
centos:
provider: myopenstack
image: CentOS 7
size: ds1G
ssh_key_name: mykey
ssh_key_file: /root/.ssh/id_rsa
meta:
build_config: rack_user_only
wait_for_metadata:
rax_service_level_automation: Complete
rackconnect_automation_status: DEPLOYED
Anything else from the create_server_ docs can be passed through here.
- **image**: Image dict, name or ID to boot with. image is required
unless boot_volume is given.
- **flavor**: Flavor dict, name or ID to boot onto.
- **auto_ip**: Whether to take actions to find a routable IP for
the server. (defaults to True)
- **ips**: List of IPs to attach to the server (defaults to None)
- **ip_pool**: Name of the network or floating IP pool to get an
address from. (defaults to None)
- **root_volume**: Name or ID of a volume to boot from
(defaults to None - deprecated, use boot_volume)
- **boot_volume**: Name or ID of a volume to boot from
(defaults to None)
- **terminate_volume**: If booting from a volume, whether it should
be deleted when the server is destroyed.
(defaults to False)
- **volumes**: (optional) A list of volumes to attach to the server
- **meta**: (optional) A dict of arbitrary key/value metadata to
store for this server. Both keys and values must be
<=255 characters.
- **files**: (optional, deprecated) A dict of files to overwrite
on the server upon boot. Keys are file names (i.e.
``/etc/passwd``) and values
are the file contents (either as a string or as a
file-like object). A maximum of five entries is allowed,
and each file must be 10k or less.
- **reservation_id**: a UUID for the set of servers being requested.
- **min_count**: (optional extension) The minimum number of
servers to launch.
- **max_count**: (optional extension) The maximum number of
servers to launch.
- **security_groups**: A list of security group names
- **userdata**: user data to pass to be exposed by the metadata
server this can be a file type object as well or a
string.
- **key_name**: (optional extension) name of previously created
keypair to inject into the instance.
- **availability_zone**: Name of the availability zone for instance
placement.
- **block_device_mapping**: (optional) A dict of block
device mappings for this server.
- **block_device_mapping_v2**: (optional) A dict of block
device mappings for this server.
- **nics**: (optional extension) an ordered list of nics to be
added to this server, with information about
connected networks, fixed IPs, port etc.
- **scheduler_hints**: (optional extension) arbitrary key-value pairs
specified by the client to help boot an instance
- **config_drive**: (optional extension) value for config drive
either boolean, or volume-id
- **disk_config**: (optional extension) control how the disk is
partitioned when the server is created. possible
values are 'AUTO' or 'MANUAL'.
- **admin_pass**: (optional extension) add a user supplied admin
password.
- **timeout**: (optional) Seconds to wait, defaults to 60.
See the ``wait`` parameter.
- **reuse_ips**: (optional) Whether to attempt to reuse pre-existing
floating ips should a floating IP be
needed (defaults to True)
- **network**: (optional) Network dict or name or ID to attach the
server to. Mutually exclusive with the nics parameter.
Can also be be a list of network names or IDs or
network dicts.
- **boot_from_volume**: Whether to boot from volume. 'boot_volume'
implies True, but boot_from_volume=True with
no boot_volume is valid and will create a
volume from the image and use that.
- **volume_size**: When booting an image from volume, how big should
the created volume be? Defaults to 50.
- **nat_destination**: Which network should a created floating IP
be attached to, if it's not possible to
infer from the cloud's configuration.
(Optional, defaults to None)
- **group**: ServerGroup dict, name or id to boot the server in.
If a group is provided in both scheduler_hints and in
the group param, the group param will win.
(Optional, defaults to None)
.. note::
If there is anything added, that is not in this list, it can be added to an `extras`
dictionary for the profile, and that will be to the create_server function.
.. _create_server: https://docs.openstack.org/shade/latest/user/usage.html#shade.OpenStackCloud.create_server
.. _vendor: https://docs.openstack.org/os-client-config/latest/user/vendor-support.html
.. _os-client-config: https://docs.openstack.org/os-client-config/latest/user/configuration.html#config-files
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import Python Libs
import copy
import logging
import os
import pprint
import socket
# Import Salt Libs
import salt.utils.versions
import salt.config as config
from salt.ext import six
from salt.exceptions import (
SaltCloudSystemExit,
SaltCloudExecutionTimeout,
SaltCloudExecutionFailure,
SaltCloudConfigError,
)
# Import 3rd-Party Libs
try:
import shade
import shade.openstackcloud
import shade.exc
import os_client_config
HAS_SHADE = (
salt.utils.versions._LooseVersion(shade.__version__) >= salt.utils.versions._LooseVersion('1.19.0'),
'Please install newer version of shade: >= 1.19.0'
)
except ImportError:
HAS_SHADE = (False, 'Install pypi module shade >= 1.19.0')
log = logging.getLogger(__name__)
__virtualname__ = 'openstack'
def __virtual__():
'''
Check for OpenStack dependencies
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return HAS_SHADE
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__, __active_provider_name__ or __virtualname__,
('auth', 'region_name'), log_message=False,
) or config.is_provider_configured(
__opts__, __active_provider_name__ or __virtualname__,
('cloud', 'region_name')
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
deps = {
'shade': shade[0],
'os_client_config': shade[0],
}
return config.check_driver_dependencies(
__virtualname__,
deps
)
def preferred_ip(vm_, ips):
'''
Return the preferred Internet protocol. Either 'ipv4' (default) or 'ipv6'.
'''
proto = config.get_cloud_config_value(
'protocol', vm_, __opts__, default='ipv4', search_global=False
)
family = socket.AF_INET
if proto == 'ipv6':
family = socket.AF_INET6
for ip in ips:
try:
socket.inet_pton(family, ip)
return ip
except Exception:
continue
return False
def ssh_interface(vm_):
'''
Return the ssh_interface type to connect to. Either 'public_ips' (default)
or 'private_ips'.
'''
return config.get_cloud_config_value('ssh_interface', vm_, __opts__, default='public_ips', search_global=False)
def get_conn():
'''
Return a conn object for the passed VM data
'''
if __active_provider_name__ in __context__:
return __context__[__active_provider_name__]
vm_ = get_configured_provider()
profile = vm_.pop('profile', None)
if profile is not None:
vm_ = __utils__['dictupdate.update'](os_client_config.vendors.get_profile(profile), vm_)
conn = shade.openstackcloud.OpenStackCloud(cloud_config=None, **vm_)
if __active_provider_name__ is not None:
__context__[__active_provider_name__] = conn
return conn
def list_nodes(conn=None, call=None):
'''
Return a list of VMs
CLI Example
.. code-block:: bash
salt-cloud -f list_nodes myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
ret = {}
for node, info in list_nodes_full(conn=conn).items():
for key in ('id', 'name', 'size', 'state', 'private_ips', 'public_ips', 'floating_ips', 'fixed_ips', 'image'):
ret.setdefault(node, {}).setdefault(key, info.get(key))
return ret
def list_nodes_min(conn=None, call=None):
'''
Return a list of VMs with minimal information
CLI Example
.. code-block:: bash
salt-cloud -f list_nodes_min myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_min function must be called with -f or --function.'
)
if conn is None:
conn = get_conn()
ret = {}
for node in conn.list_servers(bare=True):
ret[node.name] = {'id': node.id, 'state': node.status}
return ret
def _get_ips(node, addr_type='public'):
ret = []
for _, interface in node.addresses.items():
for addr in interface:
if addr_type in ('floating', 'fixed') and addr_type == addr.get('OS-EXT-IPS:type'):
ret.append(addr['addr'])
elif addr_type == 'public' and __utils__['cloud.is_public_ip'](addr['addr']):
ret.append(addr['addr'])
elif addr_type == 'private' and not __utils__['cloud.is_public_ip'](addr['addr']):
ret.append(addr['addr'])
return ret
def list_nodes_full(conn=None, call=None):
'''
Return a list of VMs with all the information about them
CLI Example
.. code-block:: bash
salt-cloud -f list_nodes_full myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or --function.'
)
if conn is None:
conn = get_conn()
ret = {}
for node in conn.list_servers(detailed=True):
ret[node.name] = dict(node)
ret[node.name]['id'] = node.id
ret[node.name]['name'] = node.name
ret[node.name]['size'] = node.flavor.name
ret[node.name]['state'] = node.status
ret[node.name]['private_ips'] = _get_ips(node, 'private')
ret[node.name]['public_ips'] = _get_ips(node, 'public')
ret[node.name]['floating_ips'] = _get_ips(node, 'floating')
ret[node.name]['fixed_ips'] = _get_ips(node, 'fixed')
ret[node.name]['image'] = node.image.name
return ret
def list_nodes_select(conn=None, call=None):
'''
Return a list of VMs with the fields from `query.selection`
CLI Example
.. code-block:: bash
salt-cloud -f list_nodes_full myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_select function must be called with -f or --function.'
)
return __utils__['cloud.list_nodes_select'](
list_nodes(conn, 'function'), __opts__['query.selection'], call,
)
def show_instance(name, conn=None, call=None):
'''
Get VM on this OpenStack account
name
name of the instance
CLI Example
.. code-block:: bash
salt-cloud -a show_instance myserver
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
if conn is None:
conn = get_conn()
node = conn.get_server(name, bare=True)
ret = dict(node)
ret['id'] = node.id
ret['name'] = node.name
ret['size'] = conn.get_flavor(node.flavor.id).name
ret['state'] = node.status
ret['private_ips'] = _get_ips(node, 'private')
ret['public_ips'] = _get_ips(node, 'public')
ret['floating_ips'] = _get_ips(node, 'floating')
ret['fixed_ips'] = _get_ips(node, 'fixed')
if isinstance(node.image, six.string_types):
ret['image'] = node.image
else:
ret['image'] = conn.get_image(node.image.id).name
return ret
def avail_sizes(conn=None, call=None):
'''
List available sizes for OpenStack
CLI Example
.. code-block:: bash
salt-cloud -f avail_sizes myopenstack
salt-cloud --list-sizes myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
if conn is None:
conn = get_conn()
return conn.list_flavors()
def list_networks(conn=None, call=None):
'''
List networks for OpenStack
CLI Example
.. code-block:: bash
salt-cloud -f list_networks myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_networks function must be called with '
'-f or --function'
)
if conn is None:
conn = get_conn()
return conn.list_networks()
def list_subnets(conn=None, call=None, kwargs=None):
'''
List subnets in a virtual network
network
network to list subnets of
.. code-block:: bash
salt-cloud -f list_subnets myopenstack network=salt-net
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_subnets function must be called with '
'-f or --function.'
)
if conn is None:
conn = get_conn()
if kwargs is None or (isinstance(kwargs, dict) and 'network' not in kwargs):
raise SaltCloudSystemExit(
'A `network` must be specified'
)
return conn.list_subnets(filters={'network': kwargs['network']})
def _clean_create_kwargs(**kwargs):
'''
Sanatize kwargs to be sent to create_server
'''
VALID_OPTS = {
'name': six.string_types,
'image': six.string_types,
'flavor': six.string_types,
'auto_ip': bool,
'ips': list,
'ip_pool': six.string_types,
'root_volume': six.string_types,
'boot_volume': six.string_types,
'terminate_volume': bool,
'volumes': list,
'meta': dict,
'files': dict,
'reservation_id': six.string_types,
'security_groups': list,
'key_name': six.string_types,
'availability_zone': six.string_types,
'block_device_mapping': dict,
'block_device_mapping_v2': dict,
'nics': list,
'scheduler_hints': dict,
'config_drive': bool,
'disk_config': six.string_types, # AUTO or MANUAL
'admin_pass': six.string_types,
'wait': bool,
'timeout': int,
'reuse_ips': bool,
'network': dict,
'boot_from_volume': bool,
'volume_size': int,
'nat_destination': six.string_types,
'group': six.string_types,
'userdata': six.string_types,
}
extra = kwargs.pop('extra', {})
for key, value in six.iteritems(kwargs.copy()):
if key in VALID_OPTS:
if isinstance(value, VALID_OPTS[key]):
continue
log.error('Error %s: %s is not of type %s', key, value, VALID_OPTS[key])
kwargs.pop(key)
return __utils__['dictupdate.update'](kwargs, extra)
def request_instance(vm_, conn=None, call=None):
'''
Request an instance to be built
'''
if call == 'function':
# Technically this function may be called other ways too, but it
# definitely cannot be called with --function.
raise SaltCloudSystemExit(
'The request_instance action must be called with -a or --action.'
)
kwargs = copy.deepcopy(vm_)
log.info('Creating Cloud VM %s', vm_['name'])
__utils__['cloud.check_name'](vm_['name'], 'a-zA-Z0-9._-')
conn = get_conn()
userdata = config.get_cloud_config_value(
'userdata', vm_, __opts__, search_global=False, default=None
)
if userdata is not None and os.path.isfile(userdata):
try:
with __utils__['files.fopen'](userdata, 'r') as fp_:
kwargs['userdata'] = __utils__['cloud.userdata_template'](
__opts__, vm_, fp_.read()
)
except Exception as exc:
log.exception(
'Failed to read userdata from %s: %s', userdata, exc)
if 'size' in kwargs:
kwargs['flavor'] = kwargs.pop('size')
kwargs['key_name'] = config.get_cloud_config_value(
'ssh_key_name', vm_, __opts__, search_global=False, default=None
)
kwargs['wait'] = True
try:
conn.create_server(**_clean_create_kwargs(**kwargs))
except shade.exc.OpenStackCloudException as exc:
log.error('Error creating server %s: %s', vm_['name'], exc)
destroy(vm_['name'], conn=conn, call='action')
raise SaltCloudSystemExit(six.text_type(exc))
return show_instance(vm_['name'], conn=conn, call='action')
def create(vm_):
'''
Create a single VM from a data dict
'''
deploy = config.get_cloud_config_value('deploy', vm_, __opts__)
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 ssh_key_file \'{0}\' does not exist'.format(
key_filename
)
)
vm_['key_filename'] = key_filename
__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']
)
conn = get_conn()
if 'instance_id' in vm_:
# This was probably created via another process, and doesn't have
# things like salt keys created yet, so let's create them now.
if 'pub_key' not in vm_ and 'priv_key' not in vm_:
log.debug('Generating minion keys for \'%s\'', vm_['name'])
vm_['priv_key'], vm_['pub_key'] = __utils__['cloud.gen_keys'](
config.get_cloud_config_value(
'keysize',
vm_,
__opts__
)
)
else:
# Put together all of the information required to request the instance,
# and then fire off the request for it
request_instance(conn=conn, call='action', vm_=vm_)
data = show_instance(vm_.get('instance_id', vm_['name']), conn=conn, call='action')
log.debug('VM is now running')
def __query_node(vm_):
data = show_instance(vm_['name'], conn=conn, call='action')
if 'wait_for_metadata' in vm_:
for key, value in six.iteritems(vm_.get('wait_for_metadata', {})):
log.debug('Waiting for metadata: %s=%s', key, value)
if data['metadata'].get(key, None) != value:
log.debug('Metadata is not ready: %s=%s', key, data['metadata'].get(key))
return False
return preferred_ip(vm_, data[ssh_interface(vm_)])
try:
ip_address = __utils__['cloud.wait_for_fun'](
__query_node,
vm_=vm_
)
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))
log.debug('Using IP address %s', ip_address)
salt_interface = __utils__['cloud.get_salt_interface'](vm_, __opts__)
salt_ip_address = preferred_ip(vm_, data[salt_interface])
log.debug('Salt interface set to: %s', salt_ip_address)
if not ip_address:
raise SaltCloudSystemExit('A valid IP address was not found')
vm_['ssh_host'] = ip_address
vm_['salt_host'] = salt_ip_address
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)
)
event_data = {
'name': vm_['name'],
'profile': vm_['profile'],
'provider': vm_['driver'],
'instance_id': data['id'],
'floating_ips': data['floating_ips'],
'fixed_ips': data['fixed_ips'],
'private_ips': data['private_ips'],
'public_ips': data['public_ips'],
}
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args=__utils__['cloud.filter_event']('created', event_data, list(event_data)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
__utils__['cloud.cachedir_index_add'](vm_['name'], vm_['profile'], 'nova', vm_['driver'])
return ret
def destroy(name, conn=None, call=None):
'''
Delete a single VM
'''
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']
)
if not conn:
conn = get_conn()
node = show_instance(name, conn=conn, call='action')
log.info('Destroying VM: %s', name)
ret = conn.delete_server(name)
if ret:
log.info('Destroyed VM: %s', name)
# Fire destroy action
__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('delete_sshkeys', False) is True:
__utils__['cloud.remove_sshkey'](getattr(node, __opts__.get('ssh_interface', 'public_ips'))[0])
if __opts__.get('update_cachedir', False) is True:
__utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__)
__utils__['cloud.cachedir_index_del'](name)
return True
log.error('Failed to Destroy VM: %s', name)
return False
def call(conn=None, call=None, kwargs=None):
'''
Call function from shade.
func
function to call from shade.openstackcloud library
CLI Example
.. code-block:: bash
salt-cloud -f call myopenstack func=list_images
t sujksalt-cloud -f call myopenstack func=create_network name=mysubnet
'''
if call == 'action':
raise SaltCloudSystemExit(
'The call function must be called with '
'-f or --function.'
)
if 'func' not in kwargs:
raise SaltCloudSystemExit(
'No `func` argument passed'
)
if conn is None:
conn = get_conn()
func = kwargs.pop('func')
for key, value in kwargs.items():
try:
kwargs[key] = __utils__['json.loads'](value)
except ValueError:
continue
try:
return getattr(conn, func)(**kwargs)
except shade.exc.OpenStackCloudException as exc:
log.error('Error running %s: %s', func, exc)
raise SaltCloudSystemExit(six.text_type(exc))
|
saltstack/salt
|
salt/cloud/clouds/openstack.py
|
avail_sizes
|
python
|
def avail_sizes(conn=None, call=None):
'''
List available sizes for OpenStack
CLI Example
.. code-block:: bash
salt-cloud -f avail_sizes myopenstack
salt-cloud --list-sizes myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
if conn is None:
conn = get_conn()
return conn.list_flavors()
|
List available sizes for OpenStack
CLI Example
.. code-block:: bash
salt-cloud -f avail_sizes myopenstack
salt-cloud --list-sizes myopenstack
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/openstack.py#L502-L521
|
[
"def get_conn():\n '''\n Return a conn object for the passed VM data\n '''\n if __active_provider_name__ in __context__:\n return __context__[__active_provider_name__]\n vm_ = get_configured_provider()\n profile = vm_.pop('profile', None)\n if profile is not None:\n vm_ = __utils__['dictupdate.update'](os_client_config.vendors.get_profile(profile), vm_)\n conn = shade.openstackcloud.OpenStackCloud(cloud_config=None, **vm_)\n if __active_provider_name__ is not None:\n __context__[__active_provider_name__] = conn\n return conn\n"
] |
# -*- coding: utf-8 -*-
'''
Openstack Cloud Driver
======================
:depends: `shade>=1.19.0 <https://pypi.python.org/pypi/shade>`_
OpenStack is an open source project that is in use by a number a cloud
providers, each of which have their own ways of using it.
This OpenStack driver uses a the shade python module which is managed by the
OpenStack Infra team. This module is written to handle all the different
versions of different OpenStack tools for salt, so most commands are just passed
over to the module to handle everything.
Provider
--------
There are two ways to configure providers for this driver. The first one is to
just let shade handle everything, and configure using os-client-config_ and
setting up `/etc/openstack/clouds.yml`.
.. code-block:: yaml
clouds:
democloud:
region_name: RegionOne
auth:
username: 'demo'
password: secret
project_name: 'demo'
auth_url: 'http://openstack/identity'
And then this can be referenced in the salt provider based on the `democloud`
name.
.. code-block:: yaml
myopenstack:
driver: openstack
cloud: democloud
region_name: RegionOne
This allows for just using one configuration for salt-cloud and for any other
openstack tools which are all using `/etc/openstack/clouds.yml`
The other method allows for specifying everything in the provider config,
instead of using the extra configuration file. This will allow for passing
salt-cloud configs only through pillars for minions without having to write a
clouds.yml file on each minion.abs
.. code-block:: yaml
myopenstack:
driver: openstack
region_name: RegionOne
auth:
username: 'demo'
password: secret
project_name: 'demo'
auth_url: 'http://openstack/identity'
Or if you need to use a profile to setup some extra stuff, it can be passed as a
`profile` to use any of the vendor_ config options.
.. code-block:: yaml
myrackspace:
driver: openstack
profile: rackspace
auth:
username: rackusername
api_key: myapikey
region_name: ORD
auth_type: rackspace_apikey
And this will pull in the profile for rackspace and setup all the correct
options for the auth_url and different api versions for services.
Profile
-------
Most of the options for building servers are just passed on to the
create_server_ function from shade.
The salt specific ones are:
- ssh_key_file: The path to the ssh key that should be used to login to the machine to bootstrap it
- ssh_key_file: The name of the keypair in openstack
- userdata_template: The renderer to use if the userdata is a file that is templated. Default: False
- ssh_interface: The interface to use to login for bootstrapping: public_ips, private_ips, floating_ips, fixed_ips
.. code-block:: yaml
centos:
provider: myopenstack
image: CentOS 7
size: ds1G
ssh_key_name: mykey
ssh_key_file: /root/.ssh/id_rsa
This is the minimum setup required.
If metadata is set to make sure that the host has finished setting up the
`wait_for_metadata` can be set.
.. code-block:: yaml
centos:
provider: myopenstack
image: CentOS 7
size: ds1G
ssh_key_name: mykey
ssh_key_file: /root/.ssh/id_rsa
meta:
build_config: rack_user_only
wait_for_metadata:
rax_service_level_automation: Complete
rackconnect_automation_status: DEPLOYED
Anything else from the create_server_ docs can be passed through here.
- **image**: Image dict, name or ID to boot with. image is required
unless boot_volume is given.
- **flavor**: Flavor dict, name or ID to boot onto.
- **auto_ip**: Whether to take actions to find a routable IP for
the server. (defaults to True)
- **ips**: List of IPs to attach to the server (defaults to None)
- **ip_pool**: Name of the network or floating IP pool to get an
address from. (defaults to None)
- **root_volume**: Name or ID of a volume to boot from
(defaults to None - deprecated, use boot_volume)
- **boot_volume**: Name or ID of a volume to boot from
(defaults to None)
- **terminate_volume**: If booting from a volume, whether it should
be deleted when the server is destroyed.
(defaults to False)
- **volumes**: (optional) A list of volumes to attach to the server
- **meta**: (optional) A dict of arbitrary key/value metadata to
store for this server. Both keys and values must be
<=255 characters.
- **files**: (optional, deprecated) A dict of files to overwrite
on the server upon boot. Keys are file names (i.e.
``/etc/passwd``) and values
are the file contents (either as a string or as a
file-like object). A maximum of five entries is allowed,
and each file must be 10k or less.
- **reservation_id**: a UUID for the set of servers being requested.
- **min_count**: (optional extension) The minimum number of
servers to launch.
- **max_count**: (optional extension) The maximum number of
servers to launch.
- **security_groups**: A list of security group names
- **userdata**: user data to pass to be exposed by the metadata
server this can be a file type object as well or a
string.
- **key_name**: (optional extension) name of previously created
keypair to inject into the instance.
- **availability_zone**: Name of the availability zone for instance
placement.
- **block_device_mapping**: (optional) A dict of block
device mappings for this server.
- **block_device_mapping_v2**: (optional) A dict of block
device mappings for this server.
- **nics**: (optional extension) an ordered list of nics to be
added to this server, with information about
connected networks, fixed IPs, port etc.
- **scheduler_hints**: (optional extension) arbitrary key-value pairs
specified by the client to help boot an instance
- **config_drive**: (optional extension) value for config drive
either boolean, or volume-id
- **disk_config**: (optional extension) control how the disk is
partitioned when the server is created. possible
values are 'AUTO' or 'MANUAL'.
- **admin_pass**: (optional extension) add a user supplied admin
password.
- **timeout**: (optional) Seconds to wait, defaults to 60.
See the ``wait`` parameter.
- **reuse_ips**: (optional) Whether to attempt to reuse pre-existing
floating ips should a floating IP be
needed (defaults to True)
- **network**: (optional) Network dict or name or ID to attach the
server to. Mutually exclusive with the nics parameter.
Can also be be a list of network names or IDs or
network dicts.
- **boot_from_volume**: Whether to boot from volume. 'boot_volume'
implies True, but boot_from_volume=True with
no boot_volume is valid and will create a
volume from the image and use that.
- **volume_size**: When booting an image from volume, how big should
the created volume be? Defaults to 50.
- **nat_destination**: Which network should a created floating IP
be attached to, if it's not possible to
infer from the cloud's configuration.
(Optional, defaults to None)
- **group**: ServerGroup dict, name or id to boot the server in.
If a group is provided in both scheduler_hints and in
the group param, the group param will win.
(Optional, defaults to None)
.. note::
If there is anything added, that is not in this list, it can be added to an `extras`
dictionary for the profile, and that will be to the create_server function.
.. _create_server: https://docs.openstack.org/shade/latest/user/usage.html#shade.OpenStackCloud.create_server
.. _vendor: https://docs.openstack.org/os-client-config/latest/user/vendor-support.html
.. _os-client-config: https://docs.openstack.org/os-client-config/latest/user/configuration.html#config-files
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import Python Libs
import copy
import logging
import os
import pprint
import socket
# Import Salt Libs
import salt.utils.versions
import salt.config as config
from salt.ext import six
from salt.exceptions import (
SaltCloudSystemExit,
SaltCloudExecutionTimeout,
SaltCloudExecutionFailure,
SaltCloudConfigError,
)
# Import 3rd-Party Libs
try:
import shade
import shade.openstackcloud
import shade.exc
import os_client_config
HAS_SHADE = (
salt.utils.versions._LooseVersion(shade.__version__) >= salt.utils.versions._LooseVersion('1.19.0'),
'Please install newer version of shade: >= 1.19.0'
)
except ImportError:
HAS_SHADE = (False, 'Install pypi module shade >= 1.19.0')
log = logging.getLogger(__name__)
__virtualname__ = 'openstack'
def __virtual__():
'''
Check for OpenStack dependencies
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return HAS_SHADE
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__, __active_provider_name__ or __virtualname__,
('auth', 'region_name'), log_message=False,
) or config.is_provider_configured(
__opts__, __active_provider_name__ or __virtualname__,
('cloud', 'region_name')
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
deps = {
'shade': shade[0],
'os_client_config': shade[0],
}
return config.check_driver_dependencies(
__virtualname__,
deps
)
def preferred_ip(vm_, ips):
'''
Return the preferred Internet protocol. Either 'ipv4' (default) or 'ipv6'.
'''
proto = config.get_cloud_config_value(
'protocol', vm_, __opts__, default='ipv4', search_global=False
)
family = socket.AF_INET
if proto == 'ipv6':
family = socket.AF_INET6
for ip in ips:
try:
socket.inet_pton(family, ip)
return ip
except Exception:
continue
return False
def ssh_interface(vm_):
'''
Return the ssh_interface type to connect to. Either 'public_ips' (default)
or 'private_ips'.
'''
return config.get_cloud_config_value('ssh_interface', vm_, __opts__, default='public_ips', search_global=False)
def get_conn():
'''
Return a conn object for the passed VM data
'''
if __active_provider_name__ in __context__:
return __context__[__active_provider_name__]
vm_ = get_configured_provider()
profile = vm_.pop('profile', None)
if profile is not None:
vm_ = __utils__['dictupdate.update'](os_client_config.vendors.get_profile(profile), vm_)
conn = shade.openstackcloud.OpenStackCloud(cloud_config=None, **vm_)
if __active_provider_name__ is not None:
__context__[__active_provider_name__] = conn
return conn
def list_nodes(conn=None, call=None):
'''
Return a list of VMs
CLI Example
.. code-block:: bash
salt-cloud -f list_nodes myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
ret = {}
for node, info in list_nodes_full(conn=conn).items():
for key in ('id', 'name', 'size', 'state', 'private_ips', 'public_ips', 'floating_ips', 'fixed_ips', 'image'):
ret.setdefault(node, {}).setdefault(key, info.get(key))
return ret
def list_nodes_min(conn=None, call=None):
'''
Return a list of VMs with minimal information
CLI Example
.. code-block:: bash
salt-cloud -f list_nodes_min myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_min function must be called with -f or --function.'
)
if conn is None:
conn = get_conn()
ret = {}
for node in conn.list_servers(bare=True):
ret[node.name] = {'id': node.id, 'state': node.status}
return ret
def _get_ips(node, addr_type='public'):
ret = []
for _, interface in node.addresses.items():
for addr in interface:
if addr_type in ('floating', 'fixed') and addr_type == addr.get('OS-EXT-IPS:type'):
ret.append(addr['addr'])
elif addr_type == 'public' and __utils__['cloud.is_public_ip'](addr['addr']):
ret.append(addr['addr'])
elif addr_type == 'private' and not __utils__['cloud.is_public_ip'](addr['addr']):
ret.append(addr['addr'])
return ret
def list_nodes_full(conn=None, call=None):
'''
Return a list of VMs with all the information about them
CLI Example
.. code-block:: bash
salt-cloud -f list_nodes_full myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or --function.'
)
if conn is None:
conn = get_conn()
ret = {}
for node in conn.list_servers(detailed=True):
ret[node.name] = dict(node)
ret[node.name]['id'] = node.id
ret[node.name]['name'] = node.name
ret[node.name]['size'] = node.flavor.name
ret[node.name]['state'] = node.status
ret[node.name]['private_ips'] = _get_ips(node, 'private')
ret[node.name]['public_ips'] = _get_ips(node, 'public')
ret[node.name]['floating_ips'] = _get_ips(node, 'floating')
ret[node.name]['fixed_ips'] = _get_ips(node, 'fixed')
ret[node.name]['image'] = node.image.name
return ret
def list_nodes_select(conn=None, call=None):
'''
Return a list of VMs with the fields from `query.selection`
CLI Example
.. code-block:: bash
salt-cloud -f list_nodes_full myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_select function must be called with -f or --function.'
)
return __utils__['cloud.list_nodes_select'](
list_nodes(conn, 'function'), __opts__['query.selection'], call,
)
def show_instance(name, conn=None, call=None):
'''
Get VM on this OpenStack account
name
name of the instance
CLI Example
.. code-block:: bash
salt-cloud -a show_instance myserver
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
if conn is None:
conn = get_conn()
node = conn.get_server(name, bare=True)
ret = dict(node)
ret['id'] = node.id
ret['name'] = node.name
ret['size'] = conn.get_flavor(node.flavor.id).name
ret['state'] = node.status
ret['private_ips'] = _get_ips(node, 'private')
ret['public_ips'] = _get_ips(node, 'public')
ret['floating_ips'] = _get_ips(node, 'floating')
ret['fixed_ips'] = _get_ips(node, 'fixed')
if isinstance(node.image, six.string_types):
ret['image'] = node.image
else:
ret['image'] = conn.get_image(node.image.id).name
return ret
def avail_images(conn=None, call=None):
'''
List available images for OpenStack
CLI Example
.. code-block:: bash
salt-cloud -f avail_images myopenstack
salt-cloud --list-images myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
if conn is None:
conn = get_conn()
return conn.list_images()
def list_networks(conn=None, call=None):
'''
List networks for OpenStack
CLI Example
.. code-block:: bash
salt-cloud -f list_networks myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_networks function must be called with '
'-f or --function'
)
if conn is None:
conn = get_conn()
return conn.list_networks()
def list_subnets(conn=None, call=None, kwargs=None):
'''
List subnets in a virtual network
network
network to list subnets of
.. code-block:: bash
salt-cloud -f list_subnets myopenstack network=salt-net
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_subnets function must be called with '
'-f or --function.'
)
if conn is None:
conn = get_conn()
if kwargs is None or (isinstance(kwargs, dict) and 'network' not in kwargs):
raise SaltCloudSystemExit(
'A `network` must be specified'
)
return conn.list_subnets(filters={'network': kwargs['network']})
def _clean_create_kwargs(**kwargs):
'''
Sanatize kwargs to be sent to create_server
'''
VALID_OPTS = {
'name': six.string_types,
'image': six.string_types,
'flavor': six.string_types,
'auto_ip': bool,
'ips': list,
'ip_pool': six.string_types,
'root_volume': six.string_types,
'boot_volume': six.string_types,
'terminate_volume': bool,
'volumes': list,
'meta': dict,
'files': dict,
'reservation_id': six.string_types,
'security_groups': list,
'key_name': six.string_types,
'availability_zone': six.string_types,
'block_device_mapping': dict,
'block_device_mapping_v2': dict,
'nics': list,
'scheduler_hints': dict,
'config_drive': bool,
'disk_config': six.string_types, # AUTO or MANUAL
'admin_pass': six.string_types,
'wait': bool,
'timeout': int,
'reuse_ips': bool,
'network': dict,
'boot_from_volume': bool,
'volume_size': int,
'nat_destination': six.string_types,
'group': six.string_types,
'userdata': six.string_types,
}
extra = kwargs.pop('extra', {})
for key, value in six.iteritems(kwargs.copy()):
if key in VALID_OPTS:
if isinstance(value, VALID_OPTS[key]):
continue
log.error('Error %s: %s is not of type %s', key, value, VALID_OPTS[key])
kwargs.pop(key)
return __utils__['dictupdate.update'](kwargs, extra)
def request_instance(vm_, conn=None, call=None):
'''
Request an instance to be built
'''
if call == 'function':
# Technically this function may be called other ways too, but it
# definitely cannot be called with --function.
raise SaltCloudSystemExit(
'The request_instance action must be called with -a or --action.'
)
kwargs = copy.deepcopy(vm_)
log.info('Creating Cloud VM %s', vm_['name'])
__utils__['cloud.check_name'](vm_['name'], 'a-zA-Z0-9._-')
conn = get_conn()
userdata = config.get_cloud_config_value(
'userdata', vm_, __opts__, search_global=False, default=None
)
if userdata is not None and os.path.isfile(userdata):
try:
with __utils__['files.fopen'](userdata, 'r') as fp_:
kwargs['userdata'] = __utils__['cloud.userdata_template'](
__opts__, vm_, fp_.read()
)
except Exception as exc:
log.exception(
'Failed to read userdata from %s: %s', userdata, exc)
if 'size' in kwargs:
kwargs['flavor'] = kwargs.pop('size')
kwargs['key_name'] = config.get_cloud_config_value(
'ssh_key_name', vm_, __opts__, search_global=False, default=None
)
kwargs['wait'] = True
try:
conn.create_server(**_clean_create_kwargs(**kwargs))
except shade.exc.OpenStackCloudException as exc:
log.error('Error creating server %s: %s', vm_['name'], exc)
destroy(vm_['name'], conn=conn, call='action')
raise SaltCloudSystemExit(six.text_type(exc))
return show_instance(vm_['name'], conn=conn, call='action')
def create(vm_):
'''
Create a single VM from a data dict
'''
deploy = config.get_cloud_config_value('deploy', vm_, __opts__)
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 ssh_key_file \'{0}\' does not exist'.format(
key_filename
)
)
vm_['key_filename'] = key_filename
__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']
)
conn = get_conn()
if 'instance_id' in vm_:
# This was probably created via another process, and doesn't have
# things like salt keys created yet, so let's create them now.
if 'pub_key' not in vm_ and 'priv_key' not in vm_:
log.debug('Generating minion keys for \'%s\'', vm_['name'])
vm_['priv_key'], vm_['pub_key'] = __utils__['cloud.gen_keys'](
config.get_cloud_config_value(
'keysize',
vm_,
__opts__
)
)
else:
# Put together all of the information required to request the instance,
# and then fire off the request for it
request_instance(conn=conn, call='action', vm_=vm_)
data = show_instance(vm_.get('instance_id', vm_['name']), conn=conn, call='action')
log.debug('VM is now running')
def __query_node(vm_):
data = show_instance(vm_['name'], conn=conn, call='action')
if 'wait_for_metadata' in vm_:
for key, value in six.iteritems(vm_.get('wait_for_metadata', {})):
log.debug('Waiting for metadata: %s=%s', key, value)
if data['metadata'].get(key, None) != value:
log.debug('Metadata is not ready: %s=%s', key, data['metadata'].get(key))
return False
return preferred_ip(vm_, data[ssh_interface(vm_)])
try:
ip_address = __utils__['cloud.wait_for_fun'](
__query_node,
vm_=vm_
)
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))
log.debug('Using IP address %s', ip_address)
salt_interface = __utils__['cloud.get_salt_interface'](vm_, __opts__)
salt_ip_address = preferred_ip(vm_, data[salt_interface])
log.debug('Salt interface set to: %s', salt_ip_address)
if not ip_address:
raise SaltCloudSystemExit('A valid IP address was not found')
vm_['ssh_host'] = ip_address
vm_['salt_host'] = salt_ip_address
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)
)
event_data = {
'name': vm_['name'],
'profile': vm_['profile'],
'provider': vm_['driver'],
'instance_id': data['id'],
'floating_ips': data['floating_ips'],
'fixed_ips': data['fixed_ips'],
'private_ips': data['private_ips'],
'public_ips': data['public_ips'],
}
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args=__utils__['cloud.filter_event']('created', event_data, list(event_data)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
__utils__['cloud.cachedir_index_add'](vm_['name'], vm_['profile'], 'nova', vm_['driver'])
return ret
def destroy(name, conn=None, call=None):
'''
Delete a single VM
'''
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']
)
if not conn:
conn = get_conn()
node = show_instance(name, conn=conn, call='action')
log.info('Destroying VM: %s', name)
ret = conn.delete_server(name)
if ret:
log.info('Destroyed VM: %s', name)
# Fire destroy action
__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('delete_sshkeys', False) is True:
__utils__['cloud.remove_sshkey'](getattr(node, __opts__.get('ssh_interface', 'public_ips'))[0])
if __opts__.get('update_cachedir', False) is True:
__utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__)
__utils__['cloud.cachedir_index_del'](name)
return True
log.error('Failed to Destroy VM: %s', name)
return False
def call(conn=None, call=None, kwargs=None):
'''
Call function from shade.
func
function to call from shade.openstackcloud library
CLI Example
.. code-block:: bash
salt-cloud -f call myopenstack func=list_images
t sujksalt-cloud -f call myopenstack func=create_network name=mysubnet
'''
if call == 'action':
raise SaltCloudSystemExit(
'The call function must be called with '
'-f or --function.'
)
if 'func' not in kwargs:
raise SaltCloudSystemExit(
'No `func` argument passed'
)
if conn is None:
conn = get_conn()
func = kwargs.pop('func')
for key, value in kwargs.items():
try:
kwargs[key] = __utils__['json.loads'](value)
except ValueError:
continue
try:
return getattr(conn, func)(**kwargs)
except shade.exc.OpenStackCloudException as exc:
log.error('Error running %s: %s', func, exc)
raise SaltCloudSystemExit(six.text_type(exc))
|
saltstack/salt
|
salt/cloud/clouds/openstack.py
|
list_networks
|
python
|
def list_networks(conn=None, call=None):
'''
List networks for OpenStack
CLI Example
.. code-block:: bash
salt-cloud -f list_networks myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_networks function must be called with '
'-f or --function'
)
if conn is None:
conn = get_conn()
return conn.list_networks()
|
List networks for OpenStack
CLI Example
.. code-block:: bash
salt-cloud -f list_networks myopenstack
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/openstack.py#L524-L542
|
[
"def get_conn():\n '''\n Return a conn object for the passed VM data\n '''\n if __active_provider_name__ in __context__:\n return __context__[__active_provider_name__]\n vm_ = get_configured_provider()\n profile = vm_.pop('profile', None)\n if profile is not None:\n vm_ = __utils__['dictupdate.update'](os_client_config.vendors.get_profile(profile), vm_)\n conn = shade.openstackcloud.OpenStackCloud(cloud_config=None, **vm_)\n if __active_provider_name__ is not None:\n __context__[__active_provider_name__] = conn\n return conn\n"
] |
# -*- coding: utf-8 -*-
'''
Openstack Cloud Driver
======================
:depends: `shade>=1.19.0 <https://pypi.python.org/pypi/shade>`_
OpenStack is an open source project that is in use by a number a cloud
providers, each of which have their own ways of using it.
This OpenStack driver uses a the shade python module which is managed by the
OpenStack Infra team. This module is written to handle all the different
versions of different OpenStack tools for salt, so most commands are just passed
over to the module to handle everything.
Provider
--------
There are two ways to configure providers for this driver. The first one is to
just let shade handle everything, and configure using os-client-config_ and
setting up `/etc/openstack/clouds.yml`.
.. code-block:: yaml
clouds:
democloud:
region_name: RegionOne
auth:
username: 'demo'
password: secret
project_name: 'demo'
auth_url: 'http://openstack/identity'
And then this can be referenced in the salt provider based on the `democloud`
name.
.. code-block:: yaml
myopenstack:
driver: openstack
cloud: democloud
region_name: RegionOne
This allows for just using one configuration for salt-cloud and for any other
openstack tools which are all using `/etc/openstack/clouds.yml`
The other method allows for specifying everything in the provider config,
instead of using the extra configuration file. This will allow for passing
salt-cloud configs only through pillars for minions without having to write a
clouds.yml file on each minion.abs
.. code-block:: yaml
myopenstack:
driver: openstack
region_name: RegionOne
auth:
username: 'demo'
password: secret
project_name: 'demo'
auth_url: 'http://openstack/identity'
Or if you need to use a profile to setup some extra stuff, it can be passed as a
`profile` to use any of the vendor_ config options.
.. code-block:: yaml
myrackspace:
driver: openstack
profile: rackspace
auth:
username: rackusername
api_key: myapikey
region_name: ORD
auth_type: rackspace_apikey
And this will pull in the profile for rackspace and setup all the correct
options for the auth_url and different api versions for services.
Profile
-------
Most of the options for building servers are just passed on to the
create_server_ function from shade.
The salt specific ones are:
- ssh_key_file: The path to the ssh key that should be used to login to the machine to bootstrap it
- ssh_key_file: The name of the keypair in openstack
- userdata_template: The renderer to use if the userdata is a file that is templated. Default: False
- ssh_interface: The interface to use to login for bootstrapping: public_ips, private_ips, floating_ips, fixed_ips
.. code-block:: yaml
centos:
provider: myopenstack
image: CentOS 7
size: ds1G
ssh_key_name: mykey
ssh_key_file: /root/.ssh/id_rsa
This is the minimum setup required.
If metadata is set to make sure that the host has finished setting up the
`wait_for_metadata` can be set.
.. code-block:: yaml
centos:
provider: myopenstack
image: CentOS 7
size: ds1G
ssh_key_name: mykey
ssh_key_file: /root/.ssh/id_rsa
meta:
build_config: rack_user_only
wait_for_metadata:
rax_service_level_automation: Complete
rackconnect_automation_status: DEPLOYED
Anything else from the create_server_ docs can be passed through here.
- **image**: Image dict, name or ID to boot with. image is required
unless boot_volume is given.
- **flavor**: Flavor dict, name or ID to boot onto.
- **auto_ip**: Whether to take actions to find a routable IP for
the server. (defaults to True)
- **ips**: List of IPs to attach to the server (defaults to None)
- **ip_pool**: Name of the network or floating IP pool to get an
address from. (defaults to None)
- **root_volume**: Name or ID of a volume to boot from
(defaults to None - deprecated, use boot_volume)
- **boot_volume**: Name or ID of a volume to boot from
(defaults to None)
- **terminate_volume**: If booting from a volume, whether it should
be deleted when the server is destroyed.
(defaults to False)
- **volumes**: (optional) A list of volumes to attach to the server
- **meta**: (optional) A dict of arbitrary key/value metadata to
store for this server. Both keys and values must be
<=255 characters.
- **files**: (optional, deprecated) A dict of files to overwrite
on the server upon boot. Keys are file names (i.e.
``/etc/passwd``) and values
are the file contents (either as a string or as a
file-like object). A maximum of five entries is allowed,
and each file must be 10k or less.
- **reservation_id**: a UUID for the set of servers being requested.
- **min_count**: (optional extension) The minimum number of
servers to launch.
- **max_count**: (optional extension) The maximum number of
servers to launch.
- **security_groups**: A list of security group names
- **userdata**: user data to pass to be exposed by the metadata
server this can be a file type object as well or a
string.
- **key_name**: (optional extension) name of previously created
keypair to inject into the instance.
- **availability_zone**: Name of the availability zone for instance
placement.
- **block_device_mapping**: (optional) A dict of block
device mappings for this server.
- **block_device_mapping_v2**: (optional) A dict of block
device mappings for this server.
- **nics**: (optional extension) an ordered list of nics to be
added to this server, with information about
connected networks, fixed IPs, port etc.
- **scheduler_hints**: (optional extension) arbitrary key-value pairs
specified by the client to help boot an instance
- **config_drive**: (optional extension) value for config drive
either boolean, or volume-id
- **disk_config**: (optional extension) control how the disk is
partitioned when the server is created. possible
values are 'AUTO' or 'MANUAL'.
- **admin_pass**: (optional extension) add a user supplied admin
password.
- **timeout**: (optional) Seconds to wait, defaults to 60.
See the ``wait`` parameter.
- **reuse_ips**: (optional) Whether to attempt to reuse pre-existing
floating ips should a floating IP be
needed (defaults to True)
- **network**: (optional) Network dict or name or ID to attach the
server to. Mutually exclusive with the nics parameter.
Can also be be a list of network names or IDs or
network dicts.
- **boot_from_volume**: Whether to boot from volume. 'boot_volume'
implies True, but boot_from_volume=True with
no boot_volume is valid and will create a
volume from the image and use that.
- **volume_size**: When booting an image from volume, how big should
the created volume be? Defaults to 50.
- **nat_destination**: Which network should a created floating IP
be attached to, if it's not possible to
infer from the cloud's configuration.
(Optional, defaults to None)
- **group**: ServerGroup dict, name or id to boot the server in.
If a group is provided in both scheduler_hints and in
the group param, the group param will win.
(Optional, defaults to None)
.. note::
If there is anything added, that is not in this list, it can be added to an `extras`
dictionary for the profile, and that will be to the create_server function.
.. _create_server: https://docs.openstack.org/shade/latest/user/usage.html#shade.OpenStackCloud.create_server
.. _vendor: https://docs.openstack.org/os-client-config/latest/user/vendor-support.html
.. _os-client-config: https://docs.openstack.org/os-client-config/latest/user/configuration.html#config-files
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import Python Libs
import copy
import logging
import os
import pprint
import socket
# Import Salt Libs
import salt.utils.versions
import salt.config as config
from salt.ext import six
from salt.exceptions import (
SaltCloudSystemExit,
SaltCloudExecutionTimeout,
SaltCloudExecutionFailure,
SaltCloudConfigError,
)
# Import 3rd-Party Libs
try:
import shade
import shade.openstackcloud
import shade.exc
import os_client_config
HAS_SHADE = (
salt.utils.versions._LooseVersion(shade.__version__) >= salt.utils.versions._LooseVersion('1.19.0'),
'Please install newer version of shade: >= 1.19.0'
)
except ImportError:
HAS_SHADE = (False, 'Install pypi module shade >= 1.19.0')
log = logging.getLogger(__name__)
__virtualname__ = 'openstack'
def __virtual__():
'''
Check for OpenStack dependencies
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return HAS_SHADE
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__, __active_provider_name__ or __virtualname__,
('auth', 'region_name'), log_message=False,
) or config.is_provider_configured(
__opts__, __active_provider_name__ or __virtualname__,
('cloud', 'region_name')
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
deps = {
'shade': shade[0],
'os_client_config': shade[0],
}
return config.check_driver_dependencies(
__virtualname__,
deps
)
def preferred_ip(vm_, ips):
'''
Return the preferred Internet protocol. Either 'ipv4' (default) or 'ipv6'.
'''
proto = config.get_cloud_config_value(
'protocol', vm_, __opts__, default='ipv4', search_global=False
)
family = socket.AF_INET
if proto == 'ipv6':
family = socket.AF_INET6
for ip in ips:
try:
socket.inet_pton(family, ip)
return ip
except Exception:
continue
return False
def ssh_interface(vm_):
'''
Return the ssh_interface type to connect to. Either 'public_ips' (default)
or 'private_ips'.
'''
return config.get_cloud_config_value('ssh_interface', vm_, __opts__, default='public_ips', search_global=False)
def get_conn():
'''
Return a conn object for the passed VM data
'''
if __active_provider_name__ in __context__:
return __context__[__active_provider_name__]
vm_ = get_configured_provider()
profile = vm_.pop('profile', None)
if profile is not None:
vm_ = __utils__['dictupdate.update'](os_client_config.vendors.get_profile(profile), vm_)
conn = shade.openstackcloud.OpenStackCloud(cloud_config=None, **vm_)
if __active_provider_name__ is not None:
__context__[__active_provider_name__] = conn
return conn
def list_nodes(conn=None, call=None):
'''
Return a list of VMs
CLI Example
.. code-block:: bash
salt-cloud -f list_nodes myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
ret = {}
for node, info in list_nodes_full(conn=conn).items():
for key in ('id', 'name', 'size', 'state', 'private_ips', 'public_ips', 'floating_ips', 'fixed_ips', 'image'):
ret.setdefault(node, {}).setdefault(key, info.get(key))
return ret
def list_nodes_min(conn=None, call=None):
'''
Return a list of VMs with minimal information
CLI Example
.. code-block:: bash
salt-cloud -f list_nodes_min myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_min function must be called with -f or --function.'
)
if conn is None:
conn = get_conn()
ret = {}
for node in conn.list_servers(bare=True):
ret[node.name] = {'id': node.id, 'state': node.status}
return ret
def _get_ips(node, addr_type='public'):
ret = []
for _, interface in node.addresses.items():
for addr in interface:
if addr_type in ('floating', 'fixed') and addr_type == addr.get('OS-EXT-IPS:type'):
ret.append(addr['addr'])
elif addr_type == 'public' and __utils__['cloud.is_public_ip'](addr['addr']):
ret.append(addr['addr'])
elif addr_type == 'private' and not __utils__['cloud.is_public_ip'](addr['addr']):
ret.append(addr['addr'])
return ret
def list_nodes_full(conn=None, call=None):
'''
Return a list of VMs with all the information about them
CLI Example
.. code-block:: bash
salt-cloud -f list_nodes_full myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or --function.'
)
if conn is None:
conn = get_conn()
ret = {}
for node in conn.list_servers(detailed=True):
ret[node.name] = dict(node)
ret[node.name]['id'] = node.id
ret[node.name]['name'] = node.name
ret[node.name]['size'] = node.flavor.name
ret[node.name]['state'] = node.status
ret[node.name]['private_ips'] = _get_ips(node, 'private')
ret[node.name]['public_ips'] = _get_ips(node, 'public')
ret[node.name]['floating_ips'] = _get_ips(node, 'floating')
ret[node.name]['fixed_ips'] = _get_ips(node, 'fixed')
ret[node.name]['image'] = node.image.name
return ret
def list_nodes_select(conn=None, call=None):
'''
Return a list of VMs with the fields from `query.selection`
CLI Example
.. code-block:: bash
salt-cloud -f list_nodes_full myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_select function must be called with -f or --function.'
)
return __utils__['cloud.list_nodes_select'](
list_nodes(conn, 'function'), __opts__['query.selection'], call,
)
def show_instance(name, conn=None, call=None):
'''
Get VM on this OpenStack account
name
name of the instance
CLI Example
.. code-block:: bash
salt-cloud -a show_instance myserver
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
if conn is None:
conn = get_conn()
node = conn.get_server(name, bare=True)
ret = dict(node)
ret['id'] = node.id
ret['name'] = node.name
ret['size'] = conn.get_flavor(node.flavor.id).name
ret['state'] = node.status
ret['private_ips'] = _get_ips(node, 'private')
ret['public_ips'] = _get_ips(node, 'public')
ret['floating_ips'] = _get_ips(node, 'floating')
ret['fixed_ips'] = _get_ips(node, 'fixed')
if isinstance(node.image, six.string_types):
ret['image'] = node.image
else:
ret['image'] = conn.get_image(node.image.id).name
return ret
def avail_images(conn=None, call=None):
'''
List available images for OpenStack
CLI Example
.. code-block:: bash
salt-cloud -f avail_images myopenstack
salt-cloud --list-images myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
if conn is None:
conn = get_conn()
return conn.list_images()
def avail_sizes(conn=None, call=None):
'''
List available sizes for OpenStack
CLI Example
.. code-block:: bash
salt-cloud -f avail_sizes myopenstack
salt-cloud --list-sizes myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
if conn is None:
conn = get_conn()
return conn.list_flavors()
def list_subnets(conn=None, call=None, kwargs=None):
'''
List subnets in a virtual network
network
network to list subnets of
.. code-block:: bash
salt-cloud -f list_subnets myopenstack network=salt-net
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_subnets function must be called with '
'-f or --function.'
)
if conn is None:
conn = get_conn()
if kwargs is None or (isinstance(kwargs, dict) and 'network' not in kwargs):
raise SaltCloudSystemExit(
'A `network` must be specified'
)
return conn.list_subnets(filters={'network': kwargs['network']})
def _clean_create_kwargs(**kwargs):
'''
Sanatize kwargs to be sent to create_server
'''
VALID_OPTS = {
'name': six.string_types,
'image': six.string_types,
'flavor': six.string_types,
'auto_ip': bool,
'ips': list,
'ip_pool': six.string_types,
'root_volume': six.string_types,
'boot_volume': six.string_types,
'terminate_volume': bool,
'volumes': list,
'meta': dict,
'files': dict,
'reservation_id': six.string_types,
'security_groups': list,
'key_name': six.string_types,
'availability_zone': six.string_types,
'block_device_mapping': dict,
'block_device_mapping_v2': dict,
'nics': list,
'scheduler_hints': dict,
'config_drive': bool,
'disk_config': six.string_types, # AUTO or MANUAL
'admin_pass': six.string_types,
'wait': bool,
'timeout': int,
'reuse_ips': bool,
'network': dict,
'boot_from_volume': bool,
'volume_size': int,
'nat_destination': six.string_types,
'group': six.string_types,
'userdata': six.string_types,
}
extra = kwargs.pop('extra', {})
for key, value in six.iteritems(kwargs.copy()):
if key in VALID_OPTS:
if isinstance(value, VALID_OPTS[key]):
continue
log.error('Error %s: %s is not of type %s', key, value, VALID_OPTS[key])
kwargs.pop(key)
return __utils__['dictupdate.update'](kwargs, extra)
def request_instance(vm_, conn=None, call=None):
'''
Request an instance to be built
'''
if call == 'function':
# Technically this function may be called other ways too, but it
# definitely cannot be called with --function.
raise SaltCloudSystemExit(
'The request_instance action must be called with -a or --action.'
)
kwargs = copy.deepcopy(vm_)
log.info('Creating Cloud VM %s', vm_['name'])
__utils__['cloud.check_name'](vm_['name'], 'a-zA-Z0-9._-')
conn = get_conn()
userdata = config.get_cloud_config_value(
'userdata', vm_, __opts__, search_global=False, default=None
)
if userdata is not None and os.path.isfile(userdata):
try:
with __utils__['files.fopen'](userdata, 'r') as fp_:
kwargs['userdata'] = __utils__['cloud.userdata_template'](
__opts__, vm_, fp_.read()
)
except Exception as exc:
log.exception(
'Failed to read userdata from %s: %s', userdata, exc)
if 'size' in kwargs:
kwargs['flavor'] = kwargs.pop('size')
kwargs['key_name'] = config.get_cloud_config_value(
'ssh_key_name', vm_, __opts__, search_global=False, default=None
)
kwargs['wait'] = True
try:
conn.create_server(**_clean_create_kwargs(**kwargs))
except shade.exc.OpenStackCloudException as exc:
log.error('Error creating server %s: %s', vm_['name'], exc)
destroy(vm_['name'], conn=conn, call='action')
raise SaltCloudSystemExit(six.text_type(exc))
return show_instance(vm_['name'], conn=conn, call='action')
def create(vm_):
'''
Create a single VM from a data dict
'''
deploy = config.get_cloud_config_value('deploy', vm_, __opts__)
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 ssh_key_file \'{0}\' does not exist'.format(
key_filename
)
)
vm_['key_filename'] = key_filename
__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']
)
conn = get_conn()
if 'instance_id' in vm_:
# This was probably created via another process, and doesn't have
# things like salt keys created yet, so let's create them now.
if 'pub_key' not in vm_ and 'priv_key' not in vm_:
log.debug('Generating minion keys for \'%s\'', vm_['name'])
vm_['priv_key'], vm_['pub_key'] = __utils__['cloud.gen_keys'](
config.get_cloud_config_value(
'keysize',
vm_,
__opts__
)
)
else:
# Put together all of the information required to request the instance,
# and then fire off the request for it
request_instance(conn=conn, call='action', vm_=vm_)
data = show_instance(vm_.get('instance_id', vm_['name']), conn=conn, call='action')
log.debug('VM is now running')
def __query_node(vm_):
data = show_instance(vm_['name'], conn=conn, call='action')
if 'wait_for_metadata' in vm_:
for key, value in six.iteritems(vm_.get('wait_for_metadata', {})):
log.debug('Waiting for metadata: %s=%s', key, value)
if data['metadata'].get(key, None) != value:
log.debug('Metadata is not ready: %s=%s', key, data['metadata'].get(key))
return False
return preferred_ip(vm_, data[ssh_interface(vm_)])
try:
ip_address = __utils__['cloud.wait_for_fun'](
__query_node,
vm_=vm_
)
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))
log.debug('Using IP address %s', ip_address)
salt_interface = __utils__['cloud.get_salt_interface'](vm_, __opts__)
salt_ip_address = preferred_ip(vm_, data[salt_interface])
log.debug('Salt interface set to: %s', salt_ip_address)
if not ip_address:
raise SaltCloudSystemExit('A valid IP address was not found')
vm_['ssh_host'] = ip_address
vm_['salt_host'] = salt_ip_address
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)
)
event_data = {
'name': vm_['name'],
'profile': vm_['profile'],
'provider': vm_['driver'],
'instance_id': data['id'],
'floating_ips': data['floating_ips'],
'fixed_ips': data['fixed_ips'],
'private_ips': data['private_ips'],
'public_ips': data['public_ips'],
}
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args=__utils__['cloud.filter_event']('created', event_data, list(event_data)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
__utils__['cloud.cachedir_index_add'](vm_['name'], vm_['profile'], 'nova', vm_['driver'])
return ret
def destroy(name, conn=None, call=None):
'''
Delete a single VM
'''
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']
)
if not conn:
conn = get_conn()
node = show_instance(name, conn=conn, call='action')
log.info('Destroying VM: %s', name)
ret = conn.delete_server(name)
if ret:
log.info('Destroyed VM: %s', name)
# Fire destroy action
__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('delete_sshkeys', False) is True:
__utils__['cloud.remove_sshkey'](getattr(node, __opts__.get('ssh_interface', 'public_ips'))[0])
if __opts__.get('update_cachedir', False) is True:
__utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__)
__utils__['cloud.cachedir_index_del'](name)
return True
log.error('Failed to Destroy VM: %s', name)
return False
def call(conn=None, call=None, kwargs=None):
'''
Call function from shade.
func
function to call from shade.openstackcloud library
CLI Example
.. code-block:: bash
salt-cloud -f call myopenstack func=list_images
t sujksalt-cloud -f call myopenstack func=create_network name=mysubnet
'''
if call == 'action':
raise SaltCloudSystemExit(
'The call function must be called with '
'-f or --function.'
)
if 'func' not in kwargs:
raise SaltCloudSystemExit(
'No `func` argument passed'
)
if conn is None:
conn = get_conn()
func = kwargs.pop('func')
for key, value in kwargs.items():
try:
kwargs[key] = __utils__['json.loads'](value)
except ValueError:
continue
try:
return getattr(conn, func)(**kwargs)
except shade.exc.OpenStackCloudException as exc:
log.error('Error running %s: %s', func, exc)
raise SaltCloudSystemExit(six.text_type(exc))
|
saltstack/salt
|
salt/cloud/clouds/openstack.py
|
list_subnets
|
python
|
def list_subnets(conn=None, call=None, kwargs=None):
'''
List subnets in a virtual network
network
network to list subnets of
.. code-block:: bash
salt-cloud -f list_subnets myopenstack network=salt-net
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_subnets function must be called with '
'-f or --function.'
)
if conn is None:
conn = get_conn()
if kwargs is None or (isinstance(kwargs, dict) and 'network' not in kwargs):
raise SaltCloudSystemExit(
'A `network` must be specified'
)
return conn.list_subnets(filters={'network': kwargs['network']})
|
List subnets in a virtual network
network
network to list subnets of
.. code-block:: bash
salt-cloud -f list_subnets myopenstack network=salt-net
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/openstack.py#L545-L568
|
[
"def get_conn():\n '''\n Return a conn object for the passed VM data\n '''\n if __active_provider_name__ in __context__:\n return __context__[__active_provider_name__]\n vm_ = get_configured_provider()\n profile = vm_.pop('profile', None)\n if profile is not None:\n vm_ = __utils__['dictupdate.update'](os_client_config.vendors.get_profile(profile), vm_)\n conn = shade.openstackcloud.OpenStackCloud(cloud_config=None, **vm_)\n if __active_provider_name__ is not None:\n __context__[__active_provider_name__] = conn\n return conn\n"
] |
# -*- coding: utf-8 -*-
'''
Openstack Cloud Driver
======================
:depends: `shade>=1.19.0 <https://pypi.python.org/pypi/shade>`_
OpenStack is an open source project that is in use by a number a cloud
providers, each of which have their own ways of using it.
This OpenStack driver uses a the shade python module which is managed by the
OpenStack Infra team. This module is written to handle all the different
versions of different OpenStack tools for salt, so most commands are just passed
over to the module to handle everything.
Provider
--------
There are two ways to configure providers for this driver. The first one is to
just let shade handle everything, and configure using os-client-config_ and
setting up `/etc/openstack/clouds.yml`.
.. code-block:: yaml
clouds:
democloud:
region_name: RegionOne
auth:
username: 'demo'
password: secret
project_name: 'demo'
auth_url: 'http://openstack/identity'
And then this can be referenced in the salt provider based on the `democloud`
name.
.. code-block:: yaml
myopenstack:
driver: openstack
cloud: democloud
region_name: RegionOne
This allows for just using one configuration for salt-cloud and for any other
openstack tools which are all using `/etc/openstack/clouds.yml`
The other method allows for specifying everything in the provider config,
instead of using the extra configuration file. This will allow for passing
salt-cloud configs only through pillars for minions without having to write a
clouds.yml file on each minion.abs
.. code-block:: yaml
myopenstack:
driver: openstack
region_name: RegionOne
auth:
username: 'demo'
password: secret
project_name: 'demo'
auth_url: 'http://openstack/identity'
Or if you need to use a profile to setup some extra stuff, it can be passed as a
`profile` to use any of the vendor_ config options.
.. code-block:: yaml
myrackspace:
driver: openstack
profile: rackspace
auth:
username: rackusername
api_key: myapikey
region_name: ORD
auth_type: rackspace_apikey
And this will pull in the profile for rackspace and setup all the correct
options for the auth_url and different api versions for services.
Profile
-------
Most of the options for building servers are just passed on to the
create_server_ function from shade.
The salt specific ones are:
- ssh_key_file: The path to the ssh key that should be used to login to the machine to bootstrap it
- ssh_key_file: The name of the keypair in openstack
- userdata_template: The renderer to use if the userdata is a file that is templated. Default: False
- ssh_interface: The interface to use to login for bootstrapping: public_ips, private_ips, floating_ips, fixed_ips
.. code-block:: yaml
centos:
provider: myopenstack
image: CentOS 7
size: ds1G
ssh_key_name: mykey
ssh_key_file: /root/.ssh/id_rsa
This is the minimum setup required.
If metadata is set to make sure that the host has finished setting up the
`wait_for_metadata` can be set.
.. code-block:: yaml
centos:
provider: myopenstack
image: CentOS 7
size: ds1G
ssh_key_name: mykey
ssh_key_file: /root/.ssh/id_rsa
meta:
build_config: rack_user_only
wait_for_metadata:
rax_service_level_automation: Complete
rackconnect_automation_status: DEPLOYED
Anything else from the create_server_ docs can be passed through here.
- **image**: Image dict, name or ID to boot with. image is required
unless boot_volume is given.
- **flavor**: Flavor dict, name or ID to boot onto.
- **auto_ip**: Whether to take actions to find a routable IP for
the server. (defaults to True)
- **ips**: List of IPs to attach to the server (defaults to None)
- **ip_pool**: Name of the network or floating IP pool to get an
address from. (defaults to None)
- **root_volume**: Name or ID of a volume to boot from
(defaults to None - deprecated, use boot_volume)
- **boot_volume**: Name or ID of a volume to boot from
(defaults to None)
- **terminate_volume**: If booting from a volume, whether it should
be deleted when the server is destroyed.
(defaults to False)
- **volumes**: (optional) A list of volumes to attach to the server
- **meta**: (optional) A dict of arbitrary key/value metadata to
store for this server. Both keys and values must be
<=255 characters.
- **files**: (optional, deprecated) A dict of files to overwrite
on the server upon boot. Keys are file names (i.e.
``/etc/passwd``) and values
are the file contents (either as a string or as a
file-like object). A maximum of five entries is allowed,
and each file must be 10k or less.
- **reservation_id**: a UUID for the set of servers being requested.
- **min_count**: (optional extension) The minimum number of
servers to launch.
- **max_count**: (optional extension) The maximum number of
servers to launch.
- **security_groups**: A list of security group names
- **userdata**: user data to pass to be exposed by the metadata
server this can be a file type object as well or a
string.
- **key_name**: (optional extension) name of previously created
keypair to inject into the instance.
- **availability_zone**: Name of the availability zone for instance
placement.
- **block_device_mapping**: (optional) A dict of block
device mappings for this server.
- **block_device_mapping_v2**: (optional) A dict of block
device mappings for this server.
- **nics**: (optional extension) an ordered list of nics to be
added to this server, with information about
connected networks, fixed IPs, port etc.
- **scheduler_hints**: (optional extension) arbitrary key-value pairs
specified by the client to help boot an instance
- **config_drive**: (optional extension) value for config drive
either boolean, or volume-id
- **disk_config**: (optional extension) control how the disk is
partitioned when the server is created. possible
values are 'AUTO' or 'MANUAL'.
- **admin_pass**: (optional extension) add a user supplied admin
password.
- **timeout**: (optional) Seconds to wait, defaults to 60.
See the ``wait`` parameter.
- **reuse_ips**: (optional) Whether to attempt to reuse pre-existing
floating ips should a floating IP be
needed (defaults to True)
- **network**: (optional) Network dict or name or ID to attach the
server to. Mutually exclusive with the nics parameter.
Can also be be a list of network names or IDs or
network dicts.
- **boot_from_volume**: Whether to boot from volume. 'boot_volume'
implies True, but boot_from_volume=True with
no boot_volume is valid and will create a
volume from the image and use that.
- **volume_size**: When booting an image from volume, how big should
the created volume be? Defaults to 50.
- **nat_destination**: Which network should a created floating IP
be attached to, if it's not possible to
infer from the cloud's configuration.
(Optional, defaults to None)
- **group**: ServerGroup dict, name or id to boot the server in.
If a group is provided in both scheduler_hints and in
the group param, the group param will win.
(Optional, defaults to None)
.. note::
If there is anything added, that is not in this list, it can be added to an `extras`
dictionary for the profile, and that will be to the create_server function.
.. _create_server: https://docs.openstack.org/shade/latest/user/usage.html#shade.OpenStackCloud.create_server
.. _vendor: https://docs.openstack.org/os-client-config/latest/user/vendor-support.html
.. _os-client-config: https://docs.openstack.org/os-client-config/latest/user/configuration.html#config-files
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import Python Libs
import copy
import logging
import os
import pprint
import socket
# Import Salt Libs
import salt.utils.versions
import salt.config as config
from salt.ext import six
from salt.exceptions import (
SaltCloudSystemExit,
SaltCloudExecutionTimeout,
SaltCloudExecutionFailure,
SaltCloudConfigError,
)
# Import 3rd-Party Libs
try:
import shade
import shade.openstackcloud
import shade.exc
import os_client_config
HAS_SHADE = (
salt.utils.versions._LooseVersion(shade.__version__) >= salt.utils.versions._LooseVersion('1.19.0'),
'Please install newer version of shade: >= 1.19.0'
)
except ImportError:
HAS_SHADE = (False, 'Install pypi module shade >= 1.19.0')
log = logging.getLogger(__name__)
__virtualname__ = 'openstack'
def __virtual__():
'''
Check for OpenStack dependencies
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return HAS_SHADE
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__, __active_provider_name__ or __virtualname__,
('auth', 'region_name'), log_message=False,
) or config.is_provider_configured(
__opts__, __active_provider_name__ or __virtualname__,
('cloud', 'region_name')
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
deps = {
'shade': shade[0],
'os_client_config': shade[0],
}
return config.check_driver_dependencies(
__virtualname__,
deps
)
def preferred_ip(vm_, ips):
'''
Return the preferred Internet protocol. Either 'ipv4' (default) or 'ipv6'.
'''
proto = config.get_cloud_config_value(
'protocol', vm_, __opts__, default='ipv4', search_global=False
)
family = socket.AF_INET
if proto == 'ipv6':
family = socket.AF_INET6
for ip in ips:
try:
socket.inet_pton(family, ip)
return ip
except Exception:
continue
return False
def ssh_interface(vm_):
'''
Return the ssh_interface type to connect to. Either 'public_ips' (default)
or 'private_ips'.
'''
return config.get_cloud_config_value('ssh_interface', vm_, __opts__, default='public_ips', search_global=False)
def get_conn():
'''
Return a conn object for the passed VM data
'''
if __active_provider_name__ in __context__:
return __context__[__active_provider_name__]
vm_ = get_configured_provider()
profile = vm_.pop('profile', None)
if profile is not None:
vm_ = __utils__['dictupdate.update'](os_client_config.vendors.get_profile(profile), vm_)
conn = shade.openstackcloud.OpenStackCloud(cloud_config=None, **vm_)
if __active_provider_name__ is not None:
__context__[__active_provider_name__] = conn
return conn
def list_nodes(conn=None, call=None):
'''
Return a list of VMs
CLI Example
.. code-block:: bash
salt-cloud -f list_nodes myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
ret = {}
for node, info in list_nodes_full(conn=conn).items():
for key in ('id', 'name', 'size', 'state', 'private_ips', 'public_ips', 'floating_ips', 'fixed_ips', 'image'):
ret.setdefault(node, {}).setdefault(key, info.get(key))
return ret
def list_nodes_min(conn=None, call=None):
'''
Return a list of VMs with minimal information
CLI Example
.. code-block:: bash
salt-cloud -f list_nodes_min myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_min function must be called with -f or --function.'
)
if conn is None:
conn = get_conn()
ret = {}
for node in conn.list_servers(bare=True):
ret[node.name] = {'id': node.id, 'state': node.status}
return ret
def _get_ips(node, addr_type='public'):
ret = []
for _, interface in node.addresses.items():
for addr in interface:
if addr_type in ('floating', 'fixed') and addr_type == addr.get('OS-EXT-IPS:type'):
ret.append(addr['addr'])
elif addr_type == 'public' and __utils__['cloud.is_public_ip'](addr['addr']):
ret.append(addr['addr'])
elif addr_type == 'private' and not __utils__['cloud.is_public_ip'](addr['addr']):
ret.append(addr['addr'])
return ret
def list_nodes_full(conn=None, call=None):
'''
Return a list of VMs with all the information about them
CLI Example
.. code-block:: bash
salt-cloud -f list_nodes_full myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or --function.'
)
if conn is None:
conn = get_conn()
ret = {}
for node in conn.list_servers(detailed=True):
ret[node.name] = dict(node)
ret[node.name]['id'] = node.id
ret[node.name]['name'] = node.name
ret[node.name]['size'] = node.flavor.name
ret[node.name]['state'] = node.status
ret[node.name]['private_ips'] = _get_ips(node, 'private')
ret[node.name]['public_ips'] = _get_ips(node, 'public')
ret[node.name]['floating_ips'] = _get_ips(node, 'floating')
ret[node.name]['fixed_ips'] = _get_ips(node, 'fixed')
ret[node.name]['image'] = node.image.name
return ret
def list_nodes_select(conn=None, call=None):
'''
Return a list of VMs with the fields from `query.selection`
CLI Example
.. code-block:: bash
salt-cloud -f list_nodes_full myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_select function must be called with -f or --function.'
)
return __utils__['cloud.list_nodes_select'](
list_nodes(conn, 'function'), __opts__['query.selection'], call,
)
def show_instance(name, conn=None, call=None):
'''
Get VM on this OpenStack account
name
name of the instance
CLI Example
.. code-block:: bash
salt-cloud -a show_instance myserver
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
if conn is None:
conn = get_conn()
node = conn.get_server(name, bare=True)
ret = dict(node)
ret['id'] = node.id
ret['name'] = node.name
ret['size'] = conn.get_flavor(node.flavor.id).name
ret['state'] = node.status
ret['private_ips'] = _get_ips(node, 'private')
ret['public_ips'] = _get_ips(node, 'public')
ret['floating_ips'] = _get_ips(node, 'floating')
ret['fixed_ips'] = _get_ips(node, 'fixed')
if isinstance(node.image, six.string_types):
ret['image'] = node.image
else:
ret['image'] = conn.get_image(node.image.id).name
return ret
def avail_images(conn=None, call=None):
'''
List available images for OpenStack
CLI Example
.. code-block:: bash
salt-cloud -f avail_images myopenstack
salt-cloud --list-images myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
if conn is None:
conn = get_conn()
return conn.list_images()
def avail_sizes(conn=None, call=None):
'''
List available sizes for OpenStack
CLI Example
.. code-block:: bash
salt-cloud -f avail_sizes myopenstack
salt-cloud --list-sizes myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
if conn is None:
conn = get_conn()
return conn.list_flavors()
def list_networks(conn=None, call=None):
'''
List networks for OpenStack
CLI Example
.. code-block:: bash
salt-cloud -f list_networks myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_networks function must be called with '
'-f or --function'
)
if conn is None:
conn = get_conn()
return conn.list_networks()
def _clean_create_kwargs(**kwargs):
'''
Sanatize kwargs to be sent to create_server
'''
VALID_OPTS = {
'name': six.string_types,
'image': six.string_types,
'flavor': six.string_types,
'auto_ip': bool,
'ips': list,
'ip_pool': six.string_types,
'root_volume': six.string_types,
'boot_volume': six.string_types,
'terminate_volume': bool,
'volumes': list,
'meta': dict,
'files': dict,
'reservation_id': six.string_types,
'security_groups': list,
'key_name': six.string_types,
'availability_zone': six.string_types,
'block_device_mapping': dict,
'block_device_mapping_v2': dict,
'nics': list,
'scheduler_hints': dict,
'config_drive': bool,
'disk_config': six.string_types, # AUTO or MANUAL
'admin_pass': six.string_types,
'wait': bool,
'timeout': int,
'reuse_ips': bool,
'network': dict,
'boot_from_volume': bool,
'volume_size': int,
'nat_destination': six.string_types,
'group': six.string_types,
'userdata': six.string_types,
}
extra = kwargs.pop('extra', {})
for key, value in six.iteritems(kwargs.copy()):
if key in VALID_OPTS:
if isinstance(value, VALID_OPTS[key]):
continue
log.error('Error %s: %s is not of type %s', key, value, VALID_OPTS[key])
kwargs.pop(key)
return __utils__['dictupdate.update'](kwargs, extra)
def request_instance(vm_, conn=None, call=None):
'''
Request an instance to be built
'''
if call == 'function':
# Technically this function may be called other ways too, but it
# definitely cannot be called with --function.
raise SaltCloudSystemExit(
'The request_instance action must be called with -a or --action.'
)
kwargs = copy.deepcopy(vm_)
log.info('Creating Cloud VM %s', vm_['name'])
__utils__['cloud.check_name'](vm_['name'], 'a-zA-Z0-9._-')
conn = get_conn()
userdata = config.get_cloud_config_value(
'userdata', vm_, __opts__, search_global=False, default=None
)
if userdata is not None and os.path.isfile(userdata):
try:
with __utils__['files.fopen'](userdata, 'r') as fp_:
kwargs['userdata'] = __utils__['cloud.userdata_template'](
__opts__, vm_, fp_.read()
)
except Exception as exc:
log.exception(
'Failed to read userdata from %s: %s', userdata, exc)
if 'size' in kwargs:
kwargs['flavor'] = kwargs.pop('size')
kwargs['key_name'] = config.get_cloud_config_value(
'ssh_key_name', vm_, __opts__, search_global=False, default=None
)
kwargs['wait'] = True
try:
conn.create_server(**_clean_create_kwargs(**kwargs))
except shade.exc.OpenStackCloudException as exc:
log.error('Error creating server %s: %s', vm_['name'], exc)
destroy(vm_['name'], conn=conn, call='action')
raise SaltCloudSystemExit(six.text_type(exc))
return show_instance(vm_['name'], conn=conn, call='action')
def create(vm_):
'''
Create a single VM from a data dict
'''
deploy = config.get_cloud_config_value('deploy', vm_, __opts__)
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 ssh_key_file \'{0}\' does not exist'.format(
key_filename
)
)
vm_['key_filename'] = key_filename
__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']
)
conn = get_conn()
if 'instance_id' in vm_:
# This was probably created via another process, and doesn't have
# things like salt keys created yet, so let's create them now.
if 'pub_key' not in vm_ and 'priv_key' not in vm_:
log.debug('Generating minion keys for \'%s\'', vm_['name'])
vm_['priv_key'], vm_['pub_key'] = __utils__['cloud.gen_keys'](
config.get_cloud_config_value(
'keysize',
vm_,
__opts__
)
)
else:
# Put together all of the information required to request the instance,
# and then fire off the request for it
request_instance(conn=conn, call='action', vm_=vm_)
data = show_instance(vm_.get('instance_id', vm_['name']), conn=conn, call='action')
log.debug('VM is now running')
def __query_node(vm_):
data = show_instance(vm_['name'], conn=conn, call='action')
if 'wait_for_metadata' in vm_:
for key, value in six.iteritems(vm_.get('wait_for_metadata', {})):
log.debug('Waiting for metadata: %s=%s', key, value)
if data['metadata'].get(key, None) != value:
log.debug('Metadata is not ready: %s=%s', key, data['metadata'].get(key))
return False
return preferred_ip(vm_, data[ssh_interface(vm_)])
try:
ip_address = __utils__['cloud.wait_for_fun'](
__query_node,
vm_=vm_
)
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))
log.debug('Using IP address %s', ip_address)
salt_interface = __utils__['cloud.get_salt_interface'](vm_, __opts__)
salt_ip_address = preferred_ip(vm_, data[salt_interface])
log.debug('Salt interface set to: %s', salt_ip_address)
if not ip_address:
raise SaltCloudSystemExit('A valid IP address was not found')
vm_['ssh_host'] = ip_address
vm_['salt_host'] = salt_ip_address
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)
)
event_data = {
'name': vm_['name'],
'profile': vm_['profile'],
'provider': vm_['driver'],
'instance_id': data['id'],
'floating_ips': data['floating_ips'],
'fixed_ips': data['fixed_ips'],
'private_ips': data['private_ips'],
'public_ips': data['public_ips'],
}
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args=__utils__['cloud.filter_event']('created', event_data, list(event_data)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
__utils__['cloud.cachedir_index_add'](vm_['name'], vm_['profile'], 'nova', vm_['driver'])
return ret
def destroy(name, conn=None, call=None):
'''
Delete a single VM
'''
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']
)
if not conn:
conn = get_conn()
node = show_instance(name, conn=conn, call='action')
log.info('Destroying VM: %s', name)
ret = conn.delete_server(name)
if ret:
log.info('Destroyed VM: %s', name)
# Fire destroy action
__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('delete_sshkeys', False) is True:
__utils__['cloud.remove_sshkey'](getattr(node, __opts__.get('ssh_interface', 'public_ips'))[0])
if __opts__.get('update_cachedir', False) is True:
__utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__)
__utils__['cloud.cachedir_index_del'](name)
return True
log.error('Failed to Destroy VM: %s', name)
return False
def call(conn=None, call=None, kwargs=None):
'''
Call function from shade.
func
function to call from shade.openstackcloud library
CLI Example
.. code-block:: bash
salt-cloud -f call myopenstack func=list_images
t sujksalt-cloud -f call myopenstack func=create_network name=mysubnet
'''
if call == 'action':
raise SaltCloudSystemExit(
'The call function must be called with '
'-f or --function.'
)
if 'func' not in kwargs:
raise SaltCloudSystemExit(
'No `func` argument passed'
)
if conn is None:
conn = get_conn()
func = kwargs.pop('func')
for key, value in kwargs.items():
try:
kwargs[key] = __utils__['json.loads'](value)
except ValueError:
continue
try:
return getattr(conn, func)(**kwargs)
except shade.exc.OpenStackCloudException as exc:
log.error('Error running %s: %s', func, exc)
raise SaltCloudSystemExit(six.text_type(exc))
|
saltstack/salt
|
salt/cloud/clouds/openstack.py
|
_clean_create_kwargs
|
python
|
def _clean_create_kwargs(**kwargs):
'''
Sanatize kwargs to be sent to create_server
'''
VALID_OPTS = {
'name': six.string_types,
'image': six.string_types,
'flavor': six.string_types,
'auto_ip': bool,
'ips': list,
'ip_pool': six.string_types,
'root_volume': six.string_types,
'boot_volume': six.string_types,
'terminate_volume': bool,
'volumes': list,
'meta': dict,
'files': dict,
'reservation_id': six.string_types,
'security_groups': list,
'key_name': six.string_types,
'availability_zone': six.string_types,
'block_device_mapping': dict,
'block_device_mapping_v2': dict,
'nics': list,
'scheduler_hints': dict,
'config_drive': bool,
'disk_config': six.string_types, # AUTO or MANUAL
'admin_pass': six.string_types,
'wait': bool,
'timeout': int,
'reuse_ips': bool,
'network': dict,
'boot_from_volume': bool,
'volume_size': int,
'nat_destination': six.string_types,
'group': six.string_types,
'userdata': six.string_types,
}
extra = kwargs.pop('extra', {})
for key, value in six.iteritems(kwargs.copy()):
if key in VALID_OPTS:
if isinstance(value, VALID_OPTS[key]):
continue
log.error('Error %s: %s is not of type %s', key, value, VALID_OPTS[key])
kwargs.pop(key)
return __utils__['dictupdate.update'](kwargs, extra)
|
Sanatize kwargs to be sent to create_server
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/openstack.py#L571-L616
|
[
"def iteritems(d, **kw):\n return d.iteritems(**kw)\n"
] |
# -*- coding: utf-8 -*-
'''
Openstack Cloud Driver
======================
:depends: `shade>=1.19.0 <https://pypi.python.org/pypi/shade>`_
OpenStack is an open source project that is in use by a number a cloud
providers, each of which have their own ways of using it.
This OpenStack driver uses a the shade python module which is managed by the
OpenStack Infra team. This module is written to handle all the different
versions of different OpenStack tools for salt, so most commands are just passed
over to the module to handle everything.
Provider
--------
There are two ways to configure providers for this driver. The first one is to
just let shade handle everything, and configure using os-client-config_ and
setting up `/etc/openstack/clouds.yml`.
.. code-block:: yaml
clouds:
democloud:
region_name: RegionOne
auth:
username: 'demo'
password: secret
project_name: 'demo'
auth_url: 'http://openstack/identity'
And then this can be referenced in the salt provider based on the `democloud`
name.
.. code-block:: yaml
myopenstack:
driver: openstack
cloud: democloud
region_name: RegionOne
This allows for just using one configuration for salt-cloud and for any other
openstack tools which are all using `/etc/openstack/clouds.yml`
The other method allows for specifying everything in the provider config,
instead of using the extra configuration file. This will allow for passing
salt-cloud configs only through pillars for minions without having to write a
clouds.yml file on each minion.abs
.. code-block:: yaml
myopenstack:
driver: openstack
region_name: RegionOne
auth:
username: 'demo'
password: secret
project_name: 'demo'
auth_url: 'http://openstack/identity'
Or if you need to use a profile to setup some extra stuff, it can be passed as a
`profile` to use any of the vendor_ config options.
.. code-block:: yaml
myrackspace:
driver: openstack
profile: rackspace
auth:
username: rackusername
api_key: myapikey
region_name: ORD
auth_type: rackspace_apikey
And this will pull in the profile for rackspace and setup all the correct
options for the auth_url and different api versions for services.
Profile
-------
Most of the options for building servers are just passed on to the
create_server_ function from shade.
The salt specific ones are:
- ssh_key_file: The path to the ssh key that should be used to login to the machine to bootstrap it
- ssh_key_file: The name of the keypair in openstack
- userdata_template: The renderer to use if the userdata is a file that is templated. Default: False
- ssh_interface: The interface to use to login for bootstrapping: public_ips, private_ips, floating_ips, fixed_ips
.. code-block:: yaml
centos:
provider: myopenstack
image: CentOS 7
size: ds1G
ssh_key_name: mykey
ssh_key_file: /root/.ssh/id_rsa
This is the minimum setup required.
If metadata is set to make sure that the host has finished setting up the
`wait_for_metadata` can be set.
.. code-block:: yaml
centos:
provider: myopenstack
image: CentOS 7
size: ds1G
ssh_key_name: mykey
ssh_key_file: /root/.ssh/id_rsa
meta:
build_config: rack_user_only
wait_for_metadata:
rax_service_level_automation: Complete
rackconnect_automation_status: DEPLOYED
Anything else from the create_server_ docs can be passed through here.
- **image**: Image dict, name or ID to boot with. image is required
unless boot_volume is given.
- **flavor**: Flavor dict, name or ID to boot onto.
- **auto_ip**: Whether to take actions to find a routable IP for
the server. (defaults to True)
- **ips**: List of IPs to attach to the server (defaults to None)
- **ip_pool**: Name of the network or floating IP pool to get an
address from. (defaults to None)
- **root_volume**: Name or ID of a volume to boot from
(defaults to None - deprecated, use boot_volume)
- **boot_volume**: Name or ID of a volume to boot from
(defaults to None)
- **terminate_volume**: If booting from a volume, whether it should
be deleted when the server is destroyed.
(defaults to False)
- **volumes**: (optional) A list of volumes to attach to the server
- **meta**: (optional) A dict of arbitrary key/value metadata to
store for this server. Both keys and values must be
<=255 characters.
- **files**: (optional, deprecated) A dict of files to overwrite
on the server upon boot. Keys are file names (i.e.
``/etc/passwd``) and values
are the file contents (either as a string or as a
file-like object). A maximum of five entries is allowed,
and each file must be 10k or less.
- **reservation_id**: a UUID for the set of servers being requested.
- **min_count**: (optional extension) The minimum number of
servers to launch.
- **max_count**: (optional extension) The maximum number of
servers to launch.
- **security_groups**: A list of security group names
- **userdata**: user data to pass to be exposed by the metadata
server this can be a file type object as well or a
string.
- **key_name**: (optional extension) name of previously created
keypair to inject into the instance.
- **availability_zone**: Name of the availability zone for instance
placement.
- **block_device_mapping**: (optional) A dict of block
device mappings for this server.
- **block_device_mapping_v2**: (optional) A dict of block
device mappings for this server.
- **nics**: (optional extension) an ordered list of nics to be
added to this server, with information about
connected networks, fixed IPs, port etc.
- **scheduler_hints**: (optional extension) arbitrary key-value pairs
specified by the client to help boot an instance
- **config_drive**: (optional extension) value for config drive
either boolean, or volume-id
- **disk_config**: (optional extension) control how the disk is
partitioned when the server is created. possible
values are 'AUTO' or 'MANUAL'.
- **admin_pass**: (optional extension) add a user supplied admin
password.
- **timeout**: (optional) Seconds to wait, defaults to 60.
See the ``wait`` parameter.
- **reuse_ips**: (optional) Whether to attempt to reuse pre-existing
floating ips should a floating IP be
needed (defaults to True)
- **network**: (optional) Network dict or name or ID to attach the
server to. Mutually exclusive with the nics parameter.
Can also be be a list of network names or IDs or
network dicts.
- **boot_from_volume**: Whether to boot from volume. 'boot_volume'
implies True, but boot_from_volume=True with
no boot_volume is valid and will create a
volume from the image and use that.
- **volume_size**: When booting an image from volume, how big should
the created volume be? Defaults to 50.
- **nat_destination**: Which network should a created floating IP
be attached to, if it's not possible to
infer from the cloud's configuration.
(Optional, defaults to None)
- **group**: ServerGroup dict, name or id to boot the server in.
If a group is provided in both scheduler_hints and in
the group param, the group param will win.
(Optional, defaults to None)
.. note::
If there is anything added, that is not in this list, it can be added to an `extras`
dictionary for the profile, and that will be to the create_server function.
.. _create_server: https://docs.openstack.org/shade/latest/user/usage.html#shade.OpenStackCloud.create_server
.. _vendor: https://docs.openstack.org/os-client-config/latest/user/vendor-support.html
.. _os-client-config: https://docs.openstack.org/os-client-config/latest/user/configuration.html#config-files
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import Python Libs
import copy
import logging
import os
import pprint
import socket
# Import Salt Libs
import salt.utils.versions
import salt.config as config
from salt.ext import six
from salt.exceptions import (
SaltCloudSystemExit,
SaltCloudExecutionTimeout,
SaltCloudExecutionFailure,
SaltCloudConfigError,
)
# Import 3rd-Party Libs
try:
import shade
import shade.openstackcloud
import shade.exc
import os_client_config
HAS_SHADE = (
salt.utils.versions._LooseVersion(shade.__version__) >= salt.utils.versions._LooseVersion('1.19.0'),
'Please install newer version of shade: >= 1.19.0'
)
except ImportError:
HAS_SHADE = (False, 'Install pypi module shade >= 1.19.0')
log = logging.getLogger(__name__)
__virtualname__ = 'openstack'
def __virtual__():
'''
Check for OpenStack dependencies
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return HAS_SHADE
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__, __active_provider_name__ or __virtualname__,
('auth', 'region_name'), log_message=False,
) or config.is_provider_configured(
__opts__, __active_provider_name__ or __virtualname__,
('cloud', 'region_name')
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
deps = {
'shade': shade[0],
'os_client_config': shade[0],
}
return config.check_driver_dependencies(
__virtualname__,
deps
)
def preferred_ip(vm_, ips):
'''
Return the preferred Internet protocol. Either 'ipv4' (default) or 'ipv6'.
'''
proto = config.get_cloud_config_value(
'protocol', vm_, __opts__, default='ipv4', search_global=False
)
family = socket.AF_INET
if proto == 'ipv6':
family = socket.AF_INET6
for ip in ips:
try:
socket.inet_pton(family, ip)
return ip
except Exception:
continue
return False
def ssh_interface(vm_):
'''
Return the ssh_interface type to connect to. Either 'public_ips' (default)
or 'private_ips'.
'''
return config.get_cloud_config_value('ssh_interface', vm_, __opts__, default='public_ips', search_global=False)
def get_conn():
'''
Return a conn object for the passed VM data
'''
if __active_provider_name__ in __context__:
return __context__[__active_provider_name__]
vm_ = get_configured_provider()
profile = vm_.pop('profile', None)
if profile is not None:
vm_ = __utils__['dictupdate.update'](os_client_config.vendors.get_profile(profile), vm_)
conn = shade.openstackcloud.OpenStackCloud(cloud_config=None, **vm_)
if __active_provider_name__ is not None:
__context__[__active_provider_name__] = conn
return conn
def list_nodes(conn=None, call=None):
'''
Return a list of VMs
CLI Example
.. code-block:: bash
salt-cloud -f list_nodes myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
ret = {}
for node, info in list_nodes_full(conn=conn).items():
for key in ('id', 'name', 'size', 'state', 'private_ips', 'public_ips', 'floating_ips', 'fixed_ips', 'image'):
ret.setdefault(node, {}).setdefault(key, info.get(key))
return ret
def list_nodes_min(conn=None, call=None):
'''
Return a list of VMs with minimal information
CLI Example
.. code-block:: bash
salt-cloud -f list_nodes_min myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_min function must be called with -f or --function.'
)
if conn is None:
conn = get_conn()
ret = {}
for node in conn.list_servers(bare=True):
ret[node.name] = {'id': node.id, 'state': node.status}
return ret
def _get_ips(node, addr_type='public'):
ret = []
for _, interface in node.addresses.items():
for addr in interface:
if addr_type in ('floating', 'fixed') and addr_type == addr.get('OS-EXT-IPS:type'):
ret.append(addr['addr'])
elif addr_type == 'public' and __utils__['cloud.is_public_ip'](addr['addr']):
ret.append(addr['addr'])
elif addr_type == 'private' and not __utils__['cloud.is_public_ip'](addr['addr']):
ret.append(addr['addr'])
return ret
def list_nodes_full(conn=None, call=None):
'''
Return a list of VMs with all the information about them
CLI Example
.. code-block:: bash
salt-cloud -f list_nodes_full myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or --function.'
)
if conn is None:
conn = get_conn()
ret = {}
for node in conn.list_servers(detailed=True):
ret[node.name] = dict(node)
ret[node.name]['id'] = node.id
ret[node.name]['name'] = node.name
ret[node.name]['size'] = node.flavor.name
ret[node.name]['state'] = node.status
ret[node.name]['private_ips'] = _get_ips(node, 'private')
ret[node.name]['public_ips'] = _get_ips(node, 'public')
ret[node.name]['floating_ips'] = _get_ips(node, 'floating')
ret[node.name]['fixed_ips'] = _get_ips(node, 'fixed')
ret[node.name]['image'] = node.image.name
return ret
def list_nodes_select(conn=None, call=None):
'''
Return a list of VMs with the fields from `query.selection`
CLI Example
.. code-block:: bash
salt-cloud -f list_nodes_full myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_select function must be called with -f or --function.'
)
return __utils__['cloud.list_nodes_select'](
list_nodes(conn, 'function'), __opts__['query.selection'], call,
)
def show_instance(name, conn=None, call=None):
'''
Get VM on this OpenStack account
name
name of the instance
CLI Example
.. code-block:: bash
salt-cloud -a show_instance myserver
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
if conn is None:
conn = get_conn()
node = conn.get_server(name, bare=True)
ret = dict(node)
ret['id'] = node.id
ret['name'] = node.name
ret['size'] = conn.get_flavor(node.flavor.id).name
ret['state'] = node.status
ret['private_ips'] = _get_ips(node, 'private')
ret['public_ips'] = _get_ips(node, 'public')
ret['floating_ips'] = _get_ips(node, 'floating')
ret['fixed_ips'] = _get_ips(node, 'fixed')
if isinstance(node.image, six.string_types):
ret['image'] = node.image
else:
ret['image'] = conn.get_image(node.image.id).name
return ret
def avail_images(conn=None, call=None):
'''
List available images for OpenStack
CLI Example
.. code-block:: bash
salt-cloud -f avail_images myopenstack
salt-cloud --list-images myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
if conn is None:
conn = get_conn()
return conn.list_images()
def avail_sizes(conn=None, call=None):
'''
List available sizes for OpenStack
CLI Example
.. code-block:: bash
salt-cloud -f avail_sizes myopenstack
salt-cloud --list-sizes myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
if conn is None:
conn = get_conn()
return conn.list_flavors()
def list_networks(conn=None, call=None):
'''
List networks for OpenStack
CLI Example
.. code-block:: bash
salt-cloud -f list_networks myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_networks function must be called with '
'-f or --function'
)
if conn is None:
conn = get_conn()
return conn.list_networks()
def list_subnets(conn=None, call=None, kwargs=None):
'''
List subnets in a virtual network
network
network to list subnets of
.. code-block:: bash
salt-cloud -f list_subnets myopenstack network=salt-net
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_subnets function must be called with '
'-f or --function.'
)
if conn is None:
conn = get_conn()
if kwargs is None or (isinstance(kwargs, dict) and 'network' not in kwargs):
raise SaltCloudSystemExit(
'A `network` must be specified'
)
return conn.list_subnets(filters={'network': kwargs['network']})
def request_instance(vm_, conn=None, call=None):
'''
Request an instance to be built
'''
if call == 'function':
# Technically this function may be called other ways too, but it
# definitely cannot be called with --function.
raise SaltCloudSystemExit(
'The request_instance action must be called with -a or --action.'
)
kwargs = copy.deepcopy(vm_)
log.info('Creating Cloud VM %s', vm_['name'])
__utils__['cloud.check_name'](vm_['name'], 'a-zA-Z0-9._-')
conn = get_conn()
userdata = config.get_cloud_config_value(
'userdata', vm_, __opts__, search_global=False, default=None
)
if userdata is not None and os.path.isfile(userdata):
try:
with __utils__['files.fopen'](userdata, 'r') as fp_:
kwargs['userdata'] = __utils__['cloud.userdata_template'](
__opts__, vm_, fp_.read()
)
except Exception as exc:
log.exception(
'Failed to read userdata from %s: %s', userdata, exc)
if 'size' in kwargs:
kwargs['flavor'] = kwargs.pop('size')
kwargs['key_name'] = config.get_cloud_config_value(
'ssh_key_name', vm_, __opts__, search_global=False, default=None
)
kwargs['wait'] = True
try:
conn.create_server(**_clean_create_kwargs(**kwargs))
except shade.exc.OpenStackCloudException as exc:
log.error('Error creating server %s: %s', vm_['name'], exc)
destroy(vm_['name'], conn=conn, call='action')
raise SaltCloudSystemExit(six.text_type(exc))
return show_instance(vm_['name'], conn=conn, call='action')
def create(vm_):
'''
Create a single VM from a data dict
'''
deploy = config.get_cloud_config_value('deploy', vm_, __opts__)
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 ssh_key_file \'{0}\' does not exist'.format(
key_filename
)
)
vm_['key_filename'] = key_filename
__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']
)
conn = get_conn()
if 'instance_id' in vm_:
# This was probably created via another process, and doesn't have
# things like salt keys created yet, so let's create them now.
if 'pub_key' not in vm_ and 'priv_key' not in vm_:
log.debug('Generating minion keys for \'%s\'', vm_['name'])
vm_['priv_key'], vm_['pub_key'] = __utils__['cloud.gen_keys'](
config.get_cloud_config_value(
'keysize',
vm_,
__opts__
)
)
else:
# Put together all of the information required to request the instance,
# and then fire off the request for it
request_instance(conn=conn, call='action', vm_=vm_)
data = show_instance(vm_.get('instance_id', vm_['name']), conn=conn, call='action')
log.debug('VM is now running')
def __query_node(vm_):
data = show_instance(vm_['name'], conn=conn, call='action')
if 'wait_for_metadata' in vm_:
for key, value in six.iteritems(vm_.get('wait_for_metadata', {})):
log.debug('Waiting for metadata: %s=%s', key, value)
if data['metadata'].get(key, None) != value:
log.debug('Metadata is not ready: %s=%s', key, data['metadata'].get(key))
return False
return preferred_ip(vm_, data[ssh_interface(vm_)])
try:
ip_address = __utils__['cloud.wait_for_fun'](
__query_node,
vm_=vm_
)
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))
log.debug('Using IP address %s', ip_address)
salt_interface = __utils__['cloud.get_salt_interface'](vm_, __opts__)
salt_ip_address = preferred_ip(vm_, data[salt_interface])
log.debug('Salt interface set to: %s', salt_ip_address)
if not ip_address:
raise SaltCloudSystemExit('A valid IP address was not found')
vm_['ssh_host'] = ip_address
vm_['salt_host'] = salt_ip_address
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)
)
event_data = {
'name': vm_['name'],
'profile': vm_['profile'],
'provider': vm_['driver'],
'instance_id': data['id'],
'floating_ips': data['floating_ips'],
'fixed_ips': data['fixed_ips'],
'private_ips': data['private_ips'],
'public_ips': data['public_ips'],
}
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args=__utils__['cloud.filter_event']('created', event_data, list(event_data)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
__utils__['cloud.cachedir_index_add'](vm_['name'], vm_['profile'], 'nova', vm_['driver'])
return ret
def destroy(name, conn=None, call=None):
'''
Delete a single VM
'''
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']
)
if not conn:
conn = get_conn()
node = show_instance(name, conn=conn, call='action')
log.info('Destroying VM: %s', name)
ret = conn.delete_server(name)
if ret:
log.info('Destroyed VM: %s', name)
# Fire destroy action
__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('delete_sshkeys', False) is True:
__utils__['cloud.remove_sshkey'](getattr(node, __opts__.get('ssh_interface', 'public_ips'))[0])
if __opts__.get('update_cachedir', False) is True:
__utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__)
__utils__['cloud.cachedir_index_del'](name)
return True
log.error('Failed to Destroy VM: %s', name)
return False
def call(conn=None, call=None, kwargs=None):
'''
Call function from shade.
func
function to call from shade.openstackcloud library
CLI Example
.. code-block:: bash
salt-cloud -f call myopenstack func=list_images
t sujksalt-cloud -f call myopenstack func=create_network name=mysubnet
'''
if call == 'action':
raise SaltCloudSystemExit(
'The call function must be called with '
'-f or --function.'
)
if 'func' not in kwargs:
raise SaltCloudSystemExit(
'No `func` argument passed'
)
if conn is None:
conn = get_conn()
func = kwargs.pop('func')
for key, value in kwargs.items():
try:
kwargs[key] = __utils__['json.loads'](value)
except ValueError:
continue
try:
return getattr(conn, func)(**kwargs)
except shade.exc.OpenStackCloudException as exc:
log.error('Error running %s: %s', func, exc)
raise SaltCloudSystemExit(six.text_type(exc))
|
saltstack/salt
|
salt/cloud/clouds/openstack.py
|
request_instance
|
python
|
def request_instance(vm_, conn=None, call=None):
'''
Request an instance to be built
'''
if call == 'function':
# Technically this function may be called other ways too, but it
# definitely cannot be called with --function.
raise SaltCloudSystemExit(
'The request_instance action must be called with -a or --action.'
)
kwargs = copy.deepcopy(vm_)
log.info('Creating Cloud VM %s', vm_['name'])
__utils__['cloud.check_name'](vm_['name'], 'a-zA-Z0-9._-')
conn = get_conn()
userdata = config.get_cloud_config_value(
'userdata', vm_, __opts__, search_global=False, default=None
)
if userdata is not None and os.path.isfile(userdata):
try:
with __utils__['files.fopen'](userdata, 'r') as fp_:
kwargs['userdata'] = __utils__['cloud.userdata_template'](
__opts__, vm_, fp_.read()
)
except Exception as exc:
log.exception(
'Failed to read userdata from %s: %s', userdata, exc)
if 'size' in kwargs:
kwargs['flavor'] = kwargs.pop('size')
kwargs['key_name'] = config.get_cloud_config_value(
'ssh_key_name', vm_, __opts__, search_global=False, default=None
)
kwargs['wait'] = True
try:
conn.create_server(**_clean_create_kwargs(**kwargs))
except shade.exc.OpenStackCloudException as exc:
log.error('Error creating server %s: %s', vm_['name'], exc)
destroy(vm_['name'], conn=conn, call='action')
raise SaltCloudSystemExit(six.text_type(exc))
return show_instance(vm_['name'], conn=conn, call='action')
|
Request an instance to be built
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/openstack.py#L619-L658
|
[
"def destroy(name, conn=None, call=None):\n '''\n Delete a single VM\n '''\n if call == 'function':\n raise SaltCloudSystemExit(\n 'The destroy action must be called with -d, --destroy, '\n '-a or --action.'\n )\n\n __utils__['cloud.fire_event'](\n 'event',\n 'destroying instance',\n 'salt/cloud/{0}/destroying'.format(name),\n args={'name': name},\n sock_dir=__opts__['sock_dir'],\n transport=__opts__['transport']\n )\n\n if not conn:\n conn = get_conn()\n node = show_instance(name, conn=conn, call='action')\n log.info('Destroying VM: %s', name)\n ret = conn.delete_server(name)\n if ret:\n log.info('Destroyed VM: %s', name)\n # Fire destroy action\n __utils__['cloud.fire_event'](\n 'event',\n 'destroyed instance',\n 'salt/cloud/{0}/destroyed'.format(name),\n args={'name': name},\n sock_dir=__opts__['sock_dir'],\n transport=__opts__['transport']\n )\n if __opts__.get('delete_sshkeys', False) is True:\n __utils__['cloud.remove_sshkey'](getattr(node, __opts__.get('ssh_interface', 'public_ips'))[0])\n if __opts__.get('update_cachedir', False) is True:\n __utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__)\n __utils__['cloud.cachedir_index_del'](name)\n return True\n\n log.error('Failed to Destroy VM: %s', name)\n return False\n",
"def get_cloud_config_value(name, vm_, opts, default=None, search_global=True):\n '''\n Search and return a setting in a known order:\n\n 1. In the virtual machine's configuration\n 2. In the virtual machine's profile configuration\n 3. In the virtual machine's provider configuration\n 4. In the salt cloud configuration if global searching is enabled\n 5. Return the provided default\n '''\n\n # As a last resort, return the default\n value = default\n\n if search_global is True and opts.get(name, None) is not None:\n # The setting name exists in the cloud(global) configuration\n value = deepcopy(opts[name])\n\n if vm_ and name:\n # Let's get the value from the profile, if present\n if 'profile' in vm_ and vm_['profile'] is not None:\n if name in opts['profiles'][vm_['profile']]:\n if isinstance(value, dict):\n value.update(opts['profiles'][vm_['profile']][name].copy())\n else:\n value = deepcopy(opts['profiles'][vm_['profile']][name])\n\n # Let's get the value from the provider, if present.\n if ':' in vm_['driver']:\n # The provider is defined as <provider-alias>:<driver-name>\n alias, driver = vm_['driver'].split(':')\n if alias in opts['providers'] and \\\n driver in opts['providers'][alias]:\n details = opts['providers'][alias][driver]\n if name in details:\n if isinstance(value, dict):\n value.update(details[name].copy())\n else:\n value = deepcopy(details[name])\n elif len(opts['providers'].get(vm_['driver'], ())) > 1:\n # The provider is NOT defined as <provider-alias>:<driver-name>\n # and there's more than one entry under the alias.\n # WARN the user!!!!\n log.error(\n \"The '%s' cloud provider definition has more than one \"\n 'entry. Your VM configuration should be specifying the '\n \"provider as 'driver: %s:<driver-engine>'. Since \"\n \"it's not, we're returning the first definition which \"\n 'might not be what you intended.',\n vm_['driver'], vm_['driver']\n )\n\n if vm_['driver'] in opts['providers']:\n # There's only one driver defined for this provider. This is safe.\n alias_defs = opts['providers'].get(vm_['driver'])\n provider_driver_defs = alias_defs[next(iter(list(alias_defs.keys())))]\n if name in provider_driver_defs:\n # The setting name exists in the VM's provider configuration.\n # Return it!\n if isinstance(value, dict):\n value.update(provider_driver_defs[name].copy())\n else:\n value = deepcopy(provider_driver_defs[name])\n\n if name and vm_ and name in vm_:\n # The setting name exists in VM configuration.\n if isinstance(vm_[name], types.GeneratorType):\n value = next(vm_[name], '')\n else:\n if isinstance(value, dict) and isinstance(vm_[name], dict):\n value.update(vm_[name].copy())\n else:\n value = deepcopy(vm_[name])\n\n return value\n",
"def show_instance(name, conn=None, call=None):\n '''\n Get VM on this OpenStack account\n\n name\n\n name of the instance\n\n CLI Example\n\n .. code-block:: bash\n\n salt-cloud -a show_instance myserver\n\n '''\n if call != 'action':\n raise SaltCloudSystemExit(\n 'The show_instance action must be called with -a or --action.'\n )\n if conn is None:\n conn = get_conn()\n\n node = conn.get_server(name, bare=True)\n ret = dict(node)\n ret['id'] = node.id\n ret['name'] = node.name\n ret['size'] = conn.get_flavor(node.flavor.id).name\n ret['state'] = node.status\n ret['private_ips'] = _get_ips(node, 'private')\n ret['public_ips'] = _get_ips(node, 'public')\n ret['floating_ips'] = _get_ips(node, 'floating')\n ret['fixed_ips'] = _get_ips(node, 'fixed')\n if isinstance(node.image, six.string_types):\n ret['image'] = node.image\n else:\n ret['image'] = conn.get_image(node.image.id).name\n return ret\n",
"def get_conn():\n '''\n Return a conn object for the passed VM data\n '''\n if __active_provider_name__ in __context__:\n return __context__[__active_provider_name__]\n vm_ = get_configured_provider()\n profile = vm_.pop('profile', None)\n if profile is not None:\n vm_ = __utils__['dictupdate.update'](os_client_config.vendors.get_profile(profile), vm_)\n conn = shade.openstackcloud.OpenStackCloud(cloud_config=None, **vm_)\n if __active_provider_name__ is not None:\n __context__[__active_provider_name__] = conn\n return conn\n",
"def _clean_create_kwargs(**kwargs):\n '''\n Sanatize kwargs to be sent to create_server\n '''\n VALID_OPTS = {\n 'name': six.string_types,\n 'image': six.string_types,\n 'flavor': six.string_types,\n 'auto_ip': bool,\n 'ips': list,\n 'ip_pool': six.string_types,\n 'root_volume': six.string_types,\n 'boot_volume': six.string_types,\n 'terminate_volume': bool,\n 'volumes': list,\n 'meta': dict,\n 'files': dict,\n 'reservation_id': six.string_types,\n 'security_groups': list,\n 'key_name': six.string_types,\n 'availability_zone': six.string_types,\n 'block_device_mapping': dict,\n 'block_device_mapping_v2': dict,\n 'nics': list,\n 'scheduler_hints': dict,\n 'config_drive': bool,\n 'disk_config': six.string_types, # AUTO or MANUAL\n 'admin_pass': six.string_types,\n 'wait': bool,\n 'timeout': int,\n 'reuse_ips': bool,\n 'network': dict,\n 'boot_from_volume': bool,\n 'volume_size': int,\n 'nat_destination': six.string_types,\n 'group': six.string_types,\n 'userdata': six.string_types,\n }\n extra = kwargs.pop('extra', {})\n for key, value in six.iteritems(kwargs.copy()):\n if key in VALID_OPTS:\n if isinstance(value, VALID_OPTS[key]):\n continue\n log.error('Error %s: %s is not of type %s', key, value, VALID_OPTS[key])\n kwargs.pop(key)\n return __utils__['dictupdate.update'](kwargs, extra)\n"
] |
# -*- coding: utf-8 -*-
'''
Openstack Cloud Driver
======================
:depends: `shade>=1.19.0 <https://pypi.python.org/pypi/shade>`_
OpenStack is an open source project that is in use by a number a cloud
providers, each of which have their own ways of using it.
This OpenStack driver uses a the shade python module which is managed by the
OpenStack Infra team. This module is written to handle all the different
versions of different OpenStack tools for salt, so most commands are just passed
over to the module to handle everything.
Provider
--------
There are two ways to configure providers for this driver. The first one is to
just let shade handle everything, and configure using os-client-config_ and
setting up `/etc/openstack/clouds.yml`.
.. code-block:: yaml
clouds:
democloud:
region_name: RegionOne
auth:
username: 'demo'
password: secret
project_name: 'demo'
auth_url: 'http://openstack/identity'
And then this can be referenced in the salt provider based on the `democloud`
name.
.. code-block:: yaml
myopenstack:
driver: openstack
cloud: democloud
region_name: RegionOne
This allows for just using one configuration for salt-cloud and for any other
openstack tools which are all using `/etc/openstack/clouds.yml`
The other method allows for specifying everything in the provider config,
instead of using the extra configuration file. This will allow for passing
salt-cloud configs only through pillars for minions without having to write a
clouds.yml file on each minion.abs
.. code-block:: yaml
myopenstack:
driver: openstack
region_name: RegionOne
auth:
username: 'demo'
password: secret
project_name: 'demo'
auth_url: 'http://openstack/identity'
Or if you need to use a profile to setup some extra stuff, it can be passed as a
`profile` to use any of the vendor_ config options.
.. code-block:: yaml
myrackspace:
driver: openstack
profile: rackspace
auth:
username: rackusername
api_key: myapikey
region_name: ORD
auth_type: rackspace_apikey
And this will pull in the profile for rackspace and setup all the correct
options for the auth_url and different api versions for services.
Profile
-------
Most of the options for building servers are just passed on to the
create_server_ function from shade.
The salt specific ones are:
- ssh_key_file: The path to the ssh key that should be used to login to the machine to bootstrap it
- ssh_key_file: The name of the keypair in openstack
- userdata_template: The renderer to use if the userdata is a file that is templated. Default: False
- ssh_interface: The interface to use to login for bootstrapping: public_ips, private_ips, floating_ips, fixed_ips
.. code-block:: yaml
centos:
provider: myopenstack
image: CentOS 7
size: ds1G
ssh_key_name: mykey
ssh_key_file: /root/.ssh/id_rsa
This is the minimum setup required.
If metadata is set to make sure that the host has finished setting up the
`wait_for_metadata` can be set.
.. code-block:: yaml
centos:
provider: myopenstack
image: CentOS 7
size: ds1G
ssh_key_name: mykey
ssh_key_file: /root/.ssh/id_rsa
meta:
build_config: rack_user_only
wait_for_metadata:
rax_service_level_automation: Complete
rackconnect_automation_status: DEPLOYED
Anything else from the create_server_ docs can be passed through here.
- **image**: Image dict, name or ID to boot with. image is required
unless boot_volume is given.
- **flavor**: Flavor dict, name or ID to boot onto.
- **auto_ip**: Whether to take actions to find a routable IP for
the server. (defaults to True)
- **ips**: List of IPs to attach to the server (defaults to None)
- **ip_pool**: Name of the network or floating IP pool to get an
address from. (defaults to None)
- **root_volume**: Name or ID of a volume to boot from
(defaults to None - deprecated, use boot_volume)
- **boot_volume**: Name or ID of a volume to boot from
(defaults to None)
- **terminate_volume**: If booting from a volume, whether it should
be deleted when the server is destroyed.
(defaults to False)
- **volumes**: (optional) A list of volumes to attach to the server
- **meta**: (optional) A dict of arbitrary key/value metadata to
store for this server. Both keys and values must be
<=255 characters.
- **files**: (optional, deprecated) A dict of files to overwrite
on the server upon boot. Keys are file names (i.e.
``/etc/passwd``) and values
are the file contents (either as a string or as a
file-like object). A maximum of five entries is allowed,
and each file must be 10k or less.
- **reservation_id**: a UUID for the set of servers being requested.
- **min_count**: (optional extension) The minimum number of
servers to launch.
- **max_count**: (optional extension) The maximum number of
servers to launch.
- **security_groups**: A list of security group names
- **userdata**: user data to pass to be exposed by the metadata
server this can be a file type object as well or a
string.
- **key_name**: (optional extension) name of previously created
keypair to inject into the instance.
- **availability_zone**: Name of the availability zone for instance
placement.
- **block_device_mapping**: (optional) A dict of block
device mappings for this server.
- **block_device_mapping_v2**: (optional) A dict of block
device mappings for this server.
- **nics**: (optional extension) an ordered list of nics to be
added to this server, with information about
connected networks, fixed IPs, port etc.
- **scheduler_hints**: (optional extension) arbitrary key-value pairs
specified by the client to help boot an instance
- **config_drive**: (optional extension) value for config drive
either boolean, or volume-id
- **disk_config**: (optional extension) control how the disk is
partitioned when the server is created. possible
values are 'AUTO' or 'MANUAL'.
- **admin_pass**: (optional extension) add a user supplied admin
password.
- **timeout**: (optional) Seconds to wait, defaults to 60.
See the ``wait`` parameter.
- **reuse_ips**: (optional) Whether to attempt to reuse pre-existing
floating ips should a floating IP be
needed (defaults to True)
- **network**: (optional) Network dict or name or ID to attach the
server to. Mutually exclusive with the nics parameter.
Can also be be a list of network names or IDs or
network dicts.
- **boot_from_volume**: Whether to boot from volume. 'boot_volume'
implies True, but boot_from_volume=True with
no boot_volume is valid and will create a
volume from the image and use that.
- **volume_size**: When booting an image from volume, how big should
the created volume be? Defaults to 50.
- **nat_destination**: Which network should a created floating IP
be attached to, if it's not possible to
infer from the cloud's configuration.
(Optional, defaults to None)
- **group**: ServerGroup dict, name or id to boot the server in.
If a group is provided in both scheduler_hints and in
the group param, the group param will win.
(Optional, defaults to None)
.. note::
If there is anything added, that is not in this list, it can be added to an `extras`
dictionary for the profile, and that will be to the create_server function.
.. _create_server: https://docs.openstack.org/shade/latest/user/usage.html#shade.OpenStackCloud.create_server
.. _vendor: https://docs.openstack.org/os-client-config/latest/user/vendor-support.html
.. _os-client-config: https://docs.openstack.org/os-client-config/latest/user/configuration.html#config-files
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import Python Libs
import copy
import logging
import os
import pprint
import socket
# Import Salt Libs
import salt.utils.versions
import salt.config as config
from salt.ext import six
from salt.exceptions import (
SaltCloudSystemExit,
SaltCloudExecutionTimeout,
SaltCloudExecutionFailure,
SaltCloudConfigError,
)
# Import 3rd-Party Libs
try:
import shade
import shade.openstackcloud
import shade.exc
import os_client_config
HAS_SHADE = (
salt.utils.versions._LooseVersion(shade.__version__) >= salt.utils.versions._LooseVersion('1.19.0'),
'Please install newer version of shade: >= 1.19.0'
)
except ImportError:
HAS_SHADE = (False, 'Install pypi module shade >= 1.19.0')
log = logging.getLogger(__name__)
__virtualname__ = 'openstack'
def __virtual__():
'''
Check for OpenStack dependencies
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return HAS_SHADE
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__, __active_provider_name__ or __virtualname__,
('auth', 'region_name'), log_message=False,
) or config.is_provider_configured(
__opts__, __active_provider_name__ or __virtualname__,
('cloud', 'region_name')
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
deps = {
'shade': shade[0],
'os_client_config': shade[0],
}
return config.check_driver_dependencies(
__virtualname__,
deps
)
def preferred_ip(vm_, ips):
'''
Return the preferred Internet protocol. Either 'ipv4' (default) or 'ipv6'.
'''
proto = config.get_cloud_config_value(
'protocol', vm_, __opts__, default='ipv4', search_global=False
)
family = socket.AF_INET
if proto == 'ipv6':
family = socket.AF_INET6
for ip in ips:
try:
socket.inet_pton(family, ip)
return ip
except Exception:
continue
return False
def ssh_interface(vm_):
'''
Return the ssh_interface type to connect to. Either 'public_ips' (default)
or 'private_ips'.
'''
return config.get_cloud_config_value('ssh_interface', vm_, __opts__, default='public_ips', search_global=False)
def get_conn():
'''
Return a conn object for the passed VM data
'''
if __active_provider_name__ in __context__:
return __context__[__active_provider_name__]
vm_ = get_configured_provider()
profile = vm_.pop('profile', None)
if profile is not None:
vm_ = __utils__['dictupdate.update'](os_client_config.vendors.get_profile(profile), vm_)
conn = shade.openstackcloud.OpenStackCloud(cloud_config=None, **vm_)
if __active_provider_name__ is not None:
__context__[__active_provider_name__] = conn
return conn
def list_nodes(conn=None, call=None):
'''
Return a list of VMs
CLI Example
.. code-block:: bash
salt-cloud -f list_nodes myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
ret = {}
for node, info in list_nodes_full(conn=conn).items():
for key in ('id', 'name', 'size', 'state', 'private_ips', 'public_ips', 'floating_ips', 'fixed_ips', 'image'):
ret.setdefault(node, {}).setdefault(key, info.get(key))
return ret
def list_nodes_min(conn=None, call=None):
'''
Return a list of VMs with minimal information
CLI Example
.. code-block:: bash
salt-cloud -f list_nodes_min myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_min function must be called with -f or --function.'
)
if conn is None:
conn = get_conn()
ret = {}
for node in conn.list_servers(bare=True):
ret[node.name] = {'id': node.id, 'state': node.status}
return ret
def _get_ips(node, addr_type='public'):
ret = []
for _, interface in node.addresses.items():
for addr in interface:
if addr_type in ('floating', 'fixed') and addr_type == addr.get('OS-EXT-IPS:type'):
ret.append(addr['addr'])
elif addr_type == 'public' and __utils__['cloud.is_public_ip'](addr['addr']):
ret.append(addr['addr'])
elif addr_type == 'private' and not __utils__['cloud.is_public_ip'](addr['addr']):
ret.append(addr['addr'])
return ret
def list_nodes_full(conn=None, call=None):
'''
Return a list of VMs with all the information about them
CLI Example
.. code-block:: bash
salt-cloud -f list_nodes_full myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or --function.'
)
if conn is None:
conn = get_conn()
ret = {}
for node in conn.list_servers(detailed=True):
ret[node.name] = dict(node)
ret[node.name]['id'] = node.id
ret[node.name]['name'] = node.name
ret[node.name]['size'] = node.flavor.name
ret[node.name]['state'] = node.status
ret[node.name]['private_ips'] = _get_ips(node, 'private')
ret[node.name]['public_ips'] = _get_ips(node, 'public')
ret[node.name]['floating_ips'] = _get_ips(node, 'floating')
ret[node.name]['fixed_ips'] = _get_ips(node, 'fixed')
ret[node.name]['image'] = node.image.name
return ret
def list_nodes_select(conn=None, call=None):
'''
Return a list of VMs with the fields from `query.selection`
CLI Example
.. code-block:: bash
salt-cloud -f list_nodes_full myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_select function must be called with -f or --function.'
)
return __utils__['cloud.list_nodes_select'](
list_nodes(conn, 'function'), __opts__['query.selection'], call,
)
def show_instance(name, conn=None, call=None):
'''
Get VM on this OpenStack account
name
name of the instance
CLI Example
.. code-block:: bash
salt-cloud -a show_instance myserver
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
if conn is None:
conn = get_conn()
node = conn.get_server(name, bare=True)
ret = dict(node)
ret['id'] = node.id
ret['name'] = node.name
ret['size'] = conn.get_flavor(node.flavor.id).name
ret['state'] = node.status
ret['private_ips'] = _get_ips(node, 'private')
ret['public_ips'] = _get_ips(node, 'public')
ret['floating_ips'] = _get_ips(node, 'floating')
ret['fixed_ips'] = _get_ips(node, 'fixed')
if isinstance(node.image, six.string_types):
ret['image'] = node.image
else:
ret['image'] = conn.get_image(node.image.id).name
return ret
def avail_images(conn=None, call=None):
'''
List available images for OpenStack
CLI Example
.. code-block:: bash
salt-cloud -f avail_images myopenstack
salt-cloud --list-images myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
if conn is None:
conn = get_conn()
return conn.list_images()
def avail_sizes(conn=None, call=None):
'''
List available sizes for OpenStack
CLI Example
.. code-block:: bash
salt-cloud -f avail_sizes myopenstack
salt-cloud --list-sizes myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
if conn is None:
conn = get_conn()
return conn.list_flavors()
def list_networks(conn=None, call=None):
'''
List networks for OpenStack
CLI Example
.. code-block:: bash
salt-cloud -f list_networks myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_networks function must be called with '
'-f or --function'
)
if conn is None:
conn = get_conn()
return conn.list_networks()
def list_subnets(conn=None, call=None, kwargs=None):
'''
List subnets in a virtual network
network
network to list subnets of
.. code-block:: bash
salt-cloud -f list_subnets myopenstack network=salt-net
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_subnets function must be called with '
'-f or --function.'
)
if conn is None:
conn = get_conn()
if kwargs is None or (isinstance(kwargs, dict) and 'network' not in kwargs):
raise SaltCloudSystemExit(
'A `network` must be specified'
)
return conn.list_subnets(filters={'network': kwargs['network']})
def _clean_create_kwargs(**kwargs):
'''
Sanatize kwargs to be sent to create_server
'''
VALID_OPTS = {
'name': six.string_types,
'image': six.string_types,
'flavor': six.string_types,
'auto_ip': bool,
'ips': list,
'ip_pool': six.string_types,
'root_volume': six.string_types,
'boot_volume': six.string_types,
'terminate_volume': bool,
'volumes': list,
'meta': dict,
'files': dict,
'reservation_id': six.string_types,
'security_groups': list,
'key_name': six.string_types,
'availability_zone': six.string_types,
'block_device_mapping': dict,
'block_device_mapping_v2': dict,
'nics': list,
'scheduler_hints': dict,
'config_drive': bool,
'disk_config': six.string_types, # AUTO or MANUAL
'admin_pass': six.string_types,
'wait': bool,
'timeout': int,
'reuse_ips': bool,
'network': dict,
'boot_from_volume': bool,
'volume_size': int,
'nat_destination': six.string_types,
'group': six.string_types,
'userdata': six.string_types,
}
extra = kwargs.pop('extra', {})
for key, value in six.iteritems(kwargs.copy()):
if key in VALID_OPTS:
if isinstance(value, VALID_OPTS[key]):
continue
log.error('Error %s: %s is not of type %s', key, value, VALID_OPTS[key])
kwargs.pop(key)
return __utils__['dictupdate.update'](kwargs, extra)
def create(vm_):
'''
Create a single VM from a data dict
'''
deploy = config.get_cloud_config_value('deploy', vm_, __opts__)
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 ssh_key_file \'{0}\' does not exist'.format(
key_filename
)
)
vm_['key_filename'] = key_filename
__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']
)
conn = get_conn()
if 'instance_id' in vm_:
# This was probably created via another process, and doesn't have
# things like salt keys created yet, so let's create them now.
if 'pub_key' not in vm_ and 'priv_key' not in vm_:
log.debug('Generating minion keys for \'%s\'', vm_['name'])
vm_['priv_key'], vm_['pub_key'] = __utils__['cloud.gen_keys'](
config.get_cloud_config_value(
'keysize',
vm_,
__opts__
)
)
else:
# Put together all of the information required to request the instance,
# and then fire off the request for it
request_instance(conn=conn, call='action', vm_=vm_)
data = show_instance(vm_.get('instance_id', vm_['name']), conn=conn, call='action')
log.debug('VM is now running')
def __query_node(vm_):
data = show_instance(vm_['name'], conn=conn, call='action')
if 'wait_for_metadata' in vm_:
for key, value in six.iteritems(vm_.get('wait_for_metadata', {})):
log.debug('Waiting for metadata: %s=%s', key, value)
if data['metadata'].get(key, None) != value:
log.debug('Metadata is not ready: %s=%s', key, data['metadata'].get(key))
return False
return preferred_ip(vm_, data[ssh_interface(vm_)])
try:
ip_address = __utils__['cloud.wait_for_fun'](
__query_node,
vm_=vm_
)
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))
log.debug('Using IP address %s', ip_address)
salt_interface = __utils__['cloud.get_salt_interface'](vm_, __opts__)
salt_ip_address = preferred_ip(vm_, data[salt_interface])
log.debug('Salt interface set to: %s', salt_ip_address)
if not ip_address:
raise SaltCloudSystemExit('A valid IP address was not found')
vm_['ssh_host'] = ip_address
vm_['salt_host'] = salt_ip_address
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)
)
event_data = {
'name': vm_['name'],
'profile': vm_['profile'],
'provider': vm_['driver'],
'instance_id': data['id'],
'floating_ips': data['floating_ips'],
'fixed_ips': data['fixed_ips'],
'private_ips': data['private_ips'],
'public_ips': data['public_ips'],
}
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args=__utils__['cloud.filter_event']('created', event_data, list(event_data)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
__utils__['cloud.cachedir_index_add'](vm_['name'], vm_['profile'], 'nova', vm_['driver'])
return ret
def destroy(name, conn=None, call=None):
'''
Delete a single VM
'''
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']
)
if not conn:
conn = get_conn()
node = show_instance(name, conn=conn, call='action')
log.info('Destroying VM: %s', name)
ret = conn.delete_server(name)
if ret:
log.info('Destroyed VM: %s', name)
# Fire destroy action
__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('delete_sshkeys', False) is True:
__utils__['cloud.remove_sshkey'](getattr(node, __opts__.get('ssh_interface', 'public_ips'))[0])
if __opts__.get('update_cachedir', False) is True:
__utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__)
__utils__['cloud.cachedir_index_del'](name)
return True
log.error('Failed to Destroy VM: %s', name)
return False
def call(conn=None, call=None, kwargs=None):
'''
Call function from shade.
func
function to call from shade.openstackcloud library
CLI Example
.. code-block:: bash
salt-cloud -f call myopenstack func=list_images
t sujksalt-cloud -f call myopenstack func=create_network name=mysubnet
'''
if call == 'action':
raise SaltCloudSystemExit(
'The call function must be called with '
'-f or --function.'
)
if 'func' not in kwargs:
raise SaltCloudSystemExit(
'No `func` argument passed'
)
if conn is None:
conn = get_conn()
func = kwargs.pop('func')
for key, value in kwargs.items():
try:
kwargs[key] = __utils__['json.loads'](value)
except ValueError:
continue
try:
return getattr(conn, func)(**kwargs)
except shade.exc.OpenStackCloudException as exc:
log.error('Error running %s: %s', func, exc)
raise SaltCloudSystemExit(six.text_type(exc))
|
saltstack/salt
|
salt/cloud/clouds/openstack.py
|
create
|
python
|
def create(vm_):
'''
Create a single VM from a data dict
'''
deploy = config.get_cloud_config_value('deploy', vm_, __opts__)
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 ssh_key_file \'{0}\' does not exist'.format(
key_filename
)
)
vm_['key_filename'] = key_filename
__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']
)
conn = get_conn()
if 'instance_id' in vm_:
# This was probably created via another process, and doesn't have
# things like salt keys created yet, so let's create them now.
if 'pub_key' not in vm_ and 'priv_key' not in vm_:
log.debug('Generating minion keys for \'%s\'', vm_['name'])
vm_['priv_key'], vm_['pub_key'] = __utils__['cloud.gen_keys'](
config.get_cloud_config_value(
'keysize',
vm_,
__opts__
)
)
else:
# Put together all of the information required to request the instance,
# and then fire off the request for it
request_instance(conn=conn, call='action', vm_=vm_)
data = show_instance(vm_.get('instance_id', vm_['name']), conn=conn, call='action')
log.debug('VM is now running')
def __query_node(vm_):
data = show_instance(vm_['name'], conn=conn, call='action')
if 'wait_for_metadata' in vm_:
for key, value in six.iteritems(vm_.get('wait_for_metadata', {})):
log.debug('Waiting for metadata: %s=%s', key, value)
if data['metadata'].get(key, None) != value:
log.debug('Metadata is not ready: %s=%s', key, data['metadata'].get(key))
return False
return preferred_ip(vm_, data[ssh_interface(vm_)])
try:
ip_address = __utils__['cloud.wait_for_fun'](
__query_node,
vm_=vm_
)
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))
log.debug('Using IP address %s', ip_address)
salt_interface = __utils__['cloud.get_salt_interface'](vm_, __opts__)
salt_ip_address = preferred_ip(vm_, data[salt_interface])
log.debug('Salt interface set to: %s', salt_ip_address)
if not ip_address:
raise SaltCloudSystemExit('A valid IP address was not found')
vm_['ssh_host'] = ip_address
vm_['salt_host'] = salt_ip_address
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)
)
event_data = {
'name': vm_['name'],
'profile': vm_['profile'],
'provider': vm_['driver'],
'instance_id': data['id'],
'floating_ips': data['floating_ips'],
'fixed_ips': data['fixed_ips'],
'private_ips': data['private_ips'],
'public_ips': data['public_ips'],
}
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args=__utils__['cloud.filter_event']('created', event_data, list(event_data)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
__utils__['cloud.cachedir_index_add'](vm_['name'], vm_['profile'], 'nova', vm_['driver'])
return ret
|
Create a single VM from a data dict
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/openstack.py#L661-L770
|
[
"def destroy(name, conn=None, call=None):\n '''\n Delete a single VM\n '''\n if call == 'function':\n raise SaltCloudSystemExit(\n 'The destroy action must be called with -d, --destroy, '\n '-a or --action.'\n )\n\n __utils__['cloud.fire_event'](\n 'event',\n 'destroying instance',\n 'salt/cloud/{0}/destroying'.format(name),\n args={'name': name},\n sock_dir=__opts__['sock_dir'],\n transport=__opts__['transport']\n )\n\n if not conn:\n conn = get_conn()\n node = show_instance(name, conn=conn, call='action')\n log.info('Destroying VM: %s', name)\n ret = conn.delete_server(name)\n if ret:\n log.info('Destroyed VM: %s', name)\n # Fire destroy action\n __utils__['cloud.fire_event'](\n 'event',\n 'destroyed instance',\n 'salt/cloud/{0}/destroyed'.format(name),\n args={'name': name},\n sock_dir=__opts__['sock_dir'],\n transport=__opts__['transport']\n )\n if __opts__.get('delete_sshkeys', False) is True:\n __utils__['cloud.remove_sshkey'](getattr(node, __opts__.get('ssh_interface', 'public_ips'))[0])\n if __opts__.get('update_cachedir', False) is True:\n __utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__)\n __utils__['cloud.cachedir_index_del'](name)\n return True\n\n log.error('Failed to Destroy VM: %s', name)\n return False\n",
"def get_cloud_config_value(name, vm_, opts, default=None, search_global=True):\n '''\n Search and return a setting in a known order:\n\n 1. In the virtual machine's configuration\n 2. In the virtual machine's profile configuration\n 3. In the virtual machine's provider configuration\n 4. In the salt cloud configuration if global searching is enabled\n 5. Return the provided default\n '''\n\n # As a last resort, return the default\n value = default\n\n if search_global is True and opts.get(name, None) is not None:\n # The setting name exists in the cloud(global) configuration\n value = deepcopy(opts[name])\n\n if vm_ and name:\n # Let's get the value from the profile, if present\n if 'profile' in vm_ and vm_['profile'] is not None:\n if name in opts['profiles'][vm_['profile']]:\n if isinstance(value, dict):\n value.update(opts['profiles'][vm_['profile']][name].copy())\n else:\n value = deepcopy(opts['profiles'][vm_['profile']][name])\n\n # Let's get the value from the provider, if present.\n if ':' in vm_['driver']:\n # The provider is defined as <provider-alias>:<driver-name>\n alias, driver = vm_['driver'].split(':')\n if alias in opts['providers'] and \\\n driver in opts['providers'][alias]:\n details = opts['providers'][alias][driver]\n if name in details:\n if isinstance(value, dict):\n value.update(details[name].copy())\n else:\n value = deepcopy(details[name])\n elif len(opts['providers'].get(vm_['driver'], ())) > 1:\n # The provider is NOT defined as <provider-alias>:<driver-name>\n # and there's more than one entry under the alias.\n # WARN the user!!!!\n log.error(\n \"The '%s' cloud provider definition has more than one \"\n 'entry. Your VM configuration should be specifying the '\n \"provider as 'driver: %s:<driver-engine>'. Since \"\n \"it's not, we're returning the first definition which \"\n 'might not be what you intended.',\n vm_['driver'], vm_['driver']\n )\n\n if vm_['driver'] in opts['providers']:\n # There's only one driver defined for this provider. This is safe.\n alias_defs = opts['providers'].get(vm_['driver'])\n provider_driver_defs = alias_defs[next(iter(list(alias_defs.keys())))]\n if name in provider_driver_defs:\n # The setting name exists in the VM's provider configuration.\n # Return it!\n if isinstance(value, dict):\n value.update(provider_driver_defs[name].copy())\n else:\n value = deepcopy(provider_driver_defs[name])\n\n if name and vm_ and name in vm_:\n # The setting name exists in VM configuration.\n if isinstance(vm_[name], types.GeneratorType):\n value = next(vm_[name], '')\n else:\n if isinstance(value, dict) and isinstance(vm_[name], dict):\n value.update(vm_[name].copy())\n else:\n value = deepcopy(vm_[name])\n\n return value\n",
"def show_instance(name, conn=None, call=None):\n '''\n Get VM on this OpenStack account\n\n name\n\n name of the instance\n\n CLI Example\n\n .. code-block:: bash\n\n salt-cloud -a show_instance myserver\n\n '''\n if call != 'action':\n raise SaltCloudSystemExit(\n 'The show_instance action must be called with -a or --action.'\n )\n if conn is None:\n conn = get_conn()\n\n node = conn.get_server(name, bare=True)\n ret = dict(node)\n ret['id'] = node.id\n ret['name'] = node.name\n ret['size'] = conn.get_flavor(node.flavor.id).name\n ret['state'] = node.status\n ret['private_ips'] = _get_ips(node, 'private')\n ret['public_ips'] = _get_ips(node, 'public')\n ret['floating_ips'] = _get_ips(node, 'floating')\n ret['fixed_ips'] = _get_ips(node, 'fixed')\n if isinstance(node.image, six.string_types):\n ret['image'] = node.image\n else:\n ret['image'] = conn.get_image(node.image.id).name\n return ret\n",
"def get_conn():\n '''\n Return a conn object for the passed VM data\n '''\n if __active_provider_name__ in __context__:\n return __context__[__active_provider_name__]\n vm_ = get_configured_provider()\n profile = vm_.pop('profile', None)\n if profile is not None:\n vm_ = __utils__['dictupdate.update'](os_client_config.vendors.get_profile(profile), vm_)\n conn = shade.openstackcloud.OpenStackCloud(cloud_config=None, **vm_)\n if __active_provider_name__ is not None:\n __context__[__active_provider_name__] = conn\n return conn\n",
"def request_instance(vm_, conn=None, call=None):\n '''\n Request an instance to be built\n '''\n if call == 'function':\n # Technically this function may be called other ways too, but it\n # definitely cannot be called with --function.\n raise SaltCloudSystemExit(\n 'The request_instance action must be called with -a or --action.'\n )\n kwargs = copy.deepcopy(vm_)\n log.info('Creating Cloud VM %s', vm_['name'])\n __utils__['cloud.check_name'](vm_['name'], 'a-zA-Z0-9._-')\n conn = get_conn()\n userdata = config.get_cloud_config_value(\n 'userdata', vm_, __opts__, search_global=False, default=None\n )\n if userdata is not None and os.path.isfile(userdata):\n try:\n with __utils__['files.fopen'](userdata, 'r') as fp_:\n kwargs['userdata'] = __utils__['cloud.userdata_template'](\n __opts__, vm_, fp_.read()\n )\n except Exception as exc:\n log.exception(\n 'Failed to read userdata from %s: %s', userdata, exc)\n if 'size' in kwargs:\n kwargs['flavor'] = kwargs.pop('size')\n kwargs['key_name'] = config.get_cloud_config_value(\n 'ssh_key_name', vm_, __opts__, search_global=False, default=None\n )\n kwargs['wait'] = True\n try:\n conn.create_server(**_clean_create_kwargs(**kwargs))\n except shade.exc.OpenStackCloudException as exc:\n log.error('Error creating server %s: %s', vm_['name'], exc)\n destroy(vm_['name'], conn=conn, call='action')\n raise SaltCloudSystemExit(six.text_type(exc))\n\n return show_instance(vm_['name'], conn=conn, call='action')\n",
"def preferred_ip(vm_, ips):\n '''\n Return the preferred Internet protocol. Either 'ipv4' (default) or 'ipv6'.\n '''\n proto = config.get_cloud_config_value(\n 'protocol', vm_, __opts__, default='ipv4', search_global=False\n )\n\n family = socket.AF_INET\n if proto == 'ipv6':\n family = socket.AF_INET6\n for ip in ips:\n try:\n socket.inet_pton(family, ip)\n return ip\n except Exception:\n continue\n return False\n"
] |
# -*- coding: utf-8 -*-
'''
Openstack Cloud Driver
======================
:depends: `shade>=1.19.0 <https://pypi.python.org/pypi/shade>`_
OpenStack is an open source project that is in use by a number a cloud
providers, each of which have their own ways of using it.
This OpenStack driver uses a the shade python module which is managed by the
OpenStack Infra team. This module is written to handle all the different
versions of different OpenStack tools for salt, so most commands are just passed
over to the module to handle everything.
Provider
--------
There are two ways to configure providers for this driver. The first one is to
just let shade handle everything, and configure using os-client-config_ and
setting up `/etc/openstack/clouds.yml`.
.. code-block:: yaml
clouds:
democloud:
region_name: RegionOne
auth:
username: 'demo'
password: secret
project_name: 'demo'
auth_url: 'http://openstack/identity'
And then this can be referenced in the salt provider based on the `democloud`
name.
.. code-block:: yaml
myopenstack:
driver: openstack
cloud: democloud
region_name: RegionOne
This allows for just using one configuration for salt-cloud and for any other
openstack tools which are all using `/etc/openstack/clouds.yml`
The other method allows for specifying everything in the provider config,
instead of using the extra configuration file. This will allow for passing
salt-cloud configs only through pillars for minions without having to write a
clouds.yml file on each minion.abs
.. code-block:: yaml
myopenstack:
driver: openstack
region_name: RegionOne
auth:
username: 'demo'
password: secret
project_name: 'demo'
auth_url: 'http://openstack/identity'
Or if you need to use a profile to setup some extra stuff, it can be passed as a
`profile` to use any of the vendor_ config options.
.. code-block:: yaml
myrackspace:
driver: openstack
profile: rackspace
auth:
username: rackusername
api_key: myapikey
region_name: ORD
auth_type: rackspace_apikey
And this will pull in the profile for rackspace and setup all the correct
options for the auth_url and different api versions for services.
Profile
-------
Most of the options for building servers are just passed on to the
create_server_ function from shade.
The salt specific ones are:
- ssh_key_file: The path to the ssh key that should be used to login to the machine to bootstrap it
- ssh_key_file: The name of the keypair in openstack
- userdata_template: The renderer to use if the userdata is a file that is templated. Default: False
- ssh_interface: The interface to use to login for bootstrapping: public_ips, private_ips, floating_ips, fixed_ips
.. code-block:: yaml
centos:
provider: myopenstack
image: CentOS 7
size: ds1G
ssh_key_name: mykey
ssh_key_file: /root/.ssh/id_rsa
This is the minimum setup required.
If metadata is set to make sure that the host has finished setting up the
`wait_for_metadata` can be set.
.. code-block:: yaml
centos:
provider: myopenstack
image: CentOS 7
size: ds1G
ssh_key_name: mykey
ssh_key_file: /root/.ssh/id_rsa
meta:
build_config: rack_user_only
wait_for_metadata:
rax_service_level_automation: Complete
rackconnect_automation_status: DEPLOYED
Anything else from the create_server_ docs can be passed through here.
- **image**: Image dict, name or ID to boot with. image is required
unless boot_volume is given.
- **flavor**: Flavor dict, name or ID to boot onto.
- **auto_ip**: Whether to take actions to find a routable IP for
the server. (defaults to True)
- **ips**: List of IPs to attach to the server (defaults to None)
- **ip_pool**: Name of the network or floating IP pool to get an
address from. (defaults to None)
- **root_volume**: Name or ID of a volume to boot from
(defaults to None - deprecated, use boot_volume)
- **boot_volume**: Name or ID of a volume to boot from
(defaults to None)
- **terminate_volume**: If booting from a volume, whether it should
be deleted when the server is destroyed.
(defaults to False)
- **volumes**: (optional) A list of volumes to attach to the server
- **meta**: (optional) A dict of arbitrary key/value metadata to
store for this server. Both keys and values must be
<=255 characters.
- **files**: (optional, deprecated) A dict of files to overwrite
on the server upon boot. Keys are file names (i.e.
``/etc/passwd``) and values
are the file contents (either as a string or as a
file-like object). A maximum of five entries is allowed,
and each file must be 10k or less.
- **reservation_id**: a UUID for the set of servers being requested.
- **min_count**: (optional extension) The minimum number of
servers to launch.
- **max_count**: (optional extension) The maximum number of
servers to launch.
- **security_groups**: A list of security group names
- **userdata**: user data to pass to be exposed by the metadata
server this can be a file type object as well or a
string.
- **key_name**: (optional extension) name of previously created
keypair to inject into the instance.
- **availability_zone**: Name of the availability zone for instance
placement.
- **block_device_mapping**: (optional) A dict of block
device mappings for this server.
- **block_device_mapping_v2**: (optional) A dict of block
device mappings for this server.
- **nics**: (optional extension) an ordered list of nics to be
added to this server, with information about
connected networks, fixed IPs, port etc.
- **scheduler_hints**: (optional extension) arbitrary key-value pairs
specified by the client to help boot an instance
- **config_drive**: (optional extension) value for config drive
either boolean, or volume-id
- **disk_config**: (optional extension) control how the disk is
partitioned when the server is created. possible
values are 'AUTO' or 'MANUAL'.
- **admin_pass**: (optional extension) add a user supplied admin
password.
- **timeout**: (optional) Seconds to wait, defaults to 60.
See the ``wait`` parameter.
- **reuse_ips**: (optional) Whether to attempt to reuse pre-existing
floating ips should a floating IP be
needed (defaults to True)
- **network**: (optional) Network dict or name or ID to attach the
server to. Mutually exclusive with the nics parameter.
Can also be be a list of network names or IDs or
network dicts.
- **boot_from_volume**: Whether to boot from volume. 'boot_volume'
implies True, but boot_from_volume=True with
no boot_volume is valid and will create a
volume from the image and use that.
- **volume_size**: When booting an image from volume, how big should
the created volume be? Defaults to 50.
- **nat_destination**: Which network should a created floating IP
be attached to, if it's not possible to
infer from the cloud's configuration.
(Optional, defaults to None)
- **group**: ServerGroup dict, name or id to boot the server in.
If a group is provided in both scheduler_hints and in
the group param, the group param will win.
(Optional, defaults to None)
.. note::
If there is anything added, that is not in this list, it can be added to an `extras`
dictionary for the profile, and that will be to the create_server function.
.. _create_server: https://docs.openstack.org/shade/latest/user/usage.html#shade.OpenStackCloud.create_server
.. _vendor: https://docs.openstack.org/os-client-config/latest/user/vendor-support.html
.. _os-client-config: https://docs.openstack.org/os-client-config/latest/user/configuration.html#config-files
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import Python Libs
import copy
import logging
import os
import pprint
import socket
# Import Salt Libs
import salt.utils.versions
import salt.config as config
from salt.ext import six
from salt.exceptions import (
SaltCloudSystemExit,
SaltCloudExecutionTimeout,
SaltCloudExecutionFailure,
SaltCloudConfigError,
)
# Import 3rd-Party Libs
try:
import shade
import shade.openstackcloud
import shade.exc
import os_client_config
HAS_SHADE = (
salt.utils.versions._LooseVersion(shade.__version__) >= salt.utils.versions._LooseVersion('1.19.0'),
'Please install newer version of shade: >= 1.19.0'
)
except ImportError:
HAS_SHADE = (False, 'Install pypi module shade >= 1.19.0')
log = logging.getLogger(__name__)
__virtualname__ = 'openstack'
def __virtual__():
'''
Check for OpenStack dependencies
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return HAS_SHADE
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__, __active_provider_name__ or __virtualname__,
('auth', 'region_name'), log_message=False,
) or config.is_provider_configured(
__opts__, __active_provider_name__ or __virtualname__,
('cloud', 'region_name')
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
deps = {
'shade': shade[0],
'os_client_config': shade[0],
}
return config.check_driver_dependencies(
__virtualname__,
deps
)
def preferred_ip(vm_, ips):
'''
Return the preferred Internet protocol. Either 'ipv4' (default) or 'ipv6'.
'''
proto = config.get_cloud_config_value(
'protocol', vm_, __opts__, default='ipv4', search_global=False
)
family = socket.AF_INET
if proto == 'ipv6':
family = socket.AF_INET6
for ip in ips:
try:
socket.inet_pton(family, ip)
return ip
except Exception:
continue
return False
def ssh_interface(vm_):
'''
Return the ssh_interface type to connect to. Either 'public_ips' (default)
or 'private_ips'.
'''
return config.get_cloud_config_value('ssh_interface', vm_, __opts__, default='public_ips', search_global=False)
def get_conn():
'''
Return a conn object for the passed VM data
'''
if __active_provider_name__ in __context__:
return __context__[__active_provider_name__]
vm_ = get_configured_provider()
profile = vm_.pop('profile', None)
if profile is not None:
vm_ = __utils__['dictupdate.update'](os_client_config.vendors.get_profile(profile), vm_)
conn = shade.openstackcloud.OpenStackCloud(cloud_config=None, **vm_)
if __active_provider_name__ is not None:
__context__[__active_provider_name__] = conn
return conn
def list_nodes(conn=None, call=None):
'''
Return a list of VMs
CLI Example
.. code-block:: bash
salt-cloud -f list_nodes myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
ret = {}
for node, info in list_nodes_full(conn=conn).items():
for key in ('id', 'name', 'size', 'state', 'private_ips', 'public_ips', 'floating_ips', 'fixed_ips', 'image'):
ret.setdefault(node, {}).setdefault(key, info.get(key))
return ret
def list_nodes_min(conn=None, call=None):
'''
Return a list of VMs with minimal information
CLI Example
.. code-block:: bash
salt-cloud -f list_nodes_min myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_min function must be called with -f or --function.'
)
if conn is None:
conn = get_conn()
ret = {}
for node in conn.list_servers(bare=True):
ret[node.name] = {'id': node.id, 'state': node.status}
return ret
def _get_ips(node, addr_type='public'):
ret = []
for _, interface in node.addresses.items():
for addr in interface:
if addr_type in ('floating', 'fixed') and addr_type == addr.get('OS-EXT-IPS:type'):
ret.append(addr['addr'])
elif addr_type == 'public' and __utils__['cloud.is_public_ip'](addr['addr']):
ret.append(addr['addr'])
elif addr_type == 'private' and not __utils__['cloud.is_public_ip'](addr['addr']):
ret.append(addr['addr'])
return ret
def list_nodes_full(conn=None, call=None):
'''
Return a list of VMs with all the information about them
CLI Example
.. code-block:: bash
salt-cloud -f list_nodes_full myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or --function.'
)
if conn is None:
conn = get_conn()
ret = {}
for node in conn.list_servers(detailed=True):
ret[node.name] = dict(node)
ret[node.name]['id'] = node.id
ret[node.name]['name'] = node.name
ret[node.name]['size'] = node.flavor.name
ret[node.name]['state'] = node.status
ret[node.name]['private_ips'] = _get_ips(node, 'private')
ret[node.name]['public_ips'] = _get_ips(node, 'public')
ret[node.name]['floating_ips'] = _get_ips(node, 'floating')
ret[node.name]['fixed_ips'] = _get_ips(node, 'fixed')
ret[node.name]['image'] = node.image.name
return ret
def list_nodes_select(conn=None, call=None):
'''
Return a list of VMs with the fields from `query.selection`
CLI Example
.. code-block:: bash
salt-cloud -f list_nodes_full myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_select function must be called with -f or --function.'
)
return __utils__['cloud.list_nodes_select'](
list_nodes(conn, 'function'), __opts__['query.selection'], call,
)
def show_instance(name, conn=None, call=None):
'''
Get VM on this OpenStack account
name
name of the instance
CLI Example
.. code-block:: bash
salt-cloud -a show_instance myserver
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
if conn is None:
conn = get_conn()
node = conn.get_server(name, bare=True)
ret = dict(node)
ret['id'] = node.id
ret['name'] = node.name
ret['size'] = conn.get_flavor(node.flavor.id).name
ret['state'] = node.status
ret['private_ips'] = _get_ips(node, 'private')
ret['public_ips'] = _get_ips(node, 'public')
ret['floating_ips'] = _get_ips(node, 'floating')
ret['fixed_ips'] = _get_ips(node, 'fixed')
if isinstance(node.image, six.string_types):
ret['image'] = node.image
else:
ret['image'] = conn.get_image(node.image.id).name
return ret
def avail_images(conn=None, call=None):
'''
List available images for OpenStack
CLI Example
.. code-block:: bash
salt-cloud -f avail_images myopenstack
salt-cloud --list-images myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
if conn is None:
conn = get_conn()
return conn.list_images()
def avail_sizes(conn=None, call=None):
'''
List available sizes for OpenStack
CLI Example
.. code-block:: bash
salt-cloud -f avail_sizes myopenstack
salt-cloud --list-sizes myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
if conn is None:
conn = get_conn()
return conn.list_flavors()
def list_networks(conn=None, call=None):
'''
List networks for OpenStack
CLI Example
.. code-block:: bash
salt-cloud -f list_networks myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_networks function must be called with '
'-f or --function'
)
if conn is None:
conn = get_conn()
return conn.list_networks()
def list_subnets(conn=None, call=None, kwargs=None):
'''
List subnets in a virtual network
network
network to list subnets of
.. code-block:: bash
salt-cloud -f list_subnets myopenstack network=salt-net
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_subnets function must be called with '
'-f or --function.'
)
if conn is None:
conn = get_conn()
if kwargs is None or (isinstance(kwargs, dict) and 'network' not in kwargs):
raise SaltCloudSystemExit(
'A `network` must be specified'
)
return conn.list_subnets(filters={'network': kwargs['network']})
def _clean_create_kwargs(**kwargs):
'''
Sanatize kwargs to be sent to create_server
'''
VALID_OPTS = {
'name': six.string_types,
'image': six.string_types,
'flavor': six.string_types,
'auto_ip': bool,
'ips': list,
'ip_pool': six.string_types,
'root_volume': six.string_types,
'boot_volume': six.string_types,
'terminate_volume': bool,
'volumes': list,
'meta': dict,
'files': dict,
'reservation_id': six.string_types,
'security_groups': list,
'key_name': six.string_types,
'availability_zone': six.string_types,
'block_device_mapping': dict,
'block_device_mapping_v2': dict,
'nics': list,
'scheduler_hints': dict,
'config_drive': bool,
'disk_config': six.string_types, # AUTO or MANUAL
'admin_pass': six.string_types,
'wait': bool,
'timeout': int,
'reuse_ips': bool,
'network': dict,
'boot_from_volume': bool,
'volume_size': int,
'nat_destination': six.string_types,
'group': six.string_types,
'userdata': six.string_types,
}
extra = kwargs.pop('extra', {})
for key, value in six.iteritems(kwargs.copy()):
if key in VALID_OPTS:
if isinstance(value, VALID_OPTS[key]):
continue
log.error('Error %s: %s is not of type %s', key, value, VALID_OPTS[key])
kwargs.pop(key)
return __utils__['dictupdate.update'](kwargs, extra)
def request_instance(vm_, conn=None, call=None):
'''
Request an instance to be built
'''
if call == 'function':
# Technically this function may be called other ways too, but it
# definitely cannot be called with --function.
raise SaltCloudSystemExit(
'The request_instance action must be called with -a or --action.'
)
kwargs = copy.deepcopy(vm_)
log.info('Creating Cloud VM %s', vm_['name'])
__utils__['cloud.check_name'](vm_['name'], 'a-zA-Z0-9._-')
conn = get_conn()
userdata = config.get_cloud_config_value(
'userdata', vm_, __opts__, search_global=False, default=None
)
if userdata is not None and os.path.isfile(userdata):
try:
with __utils__['files.fopen'](userdata, 'r') as fp_:
kwargs['userdata'] = __utils__['cloud.userdata_template'](
__opts__, vm_, fp_.read()
)
except Exception as exc:
log.exception(
'Failed to read userdata from %s: %s', userdata, exc)
if 'size' in kwargs:
kwargs['flavor'] = kwargs.pop('size')
kwargs['key_name'] = config.get_cloud_config_value(
'ssh_key_name', vm_, __opts__, search_global=False, default=None
)
kwargs['wait'] = True
try:
conn.create_server(**_clean_create_kwargs(**kwargs))
except shade.exc.OpenStackCloudException as exc:
log.error('Error creating server %s: %s', vm_['name'], exc)
destroy(vm_['name'], conn=conn, call='action')
raise SaltCloudSystemExit(six.text_type(exc))
return show_instance(vm_['name'], conn=conn, call='action')
def destroy(name, conn=None, call=None):
'''
Delete a single VM
'''
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']
)
if not conn:
conn = get_conn()
node = show_instance(name, conn=conn, call='action')
log.info('Destroying VM: %s', name)
ret = conn.delete_server(name)
if ret:
log.info('Destroyed VM: %s', name)
# Fire destroy action
__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('delete_sshkeys', False) is True:
__utils__['cloud.remove_sshkey'](getattr(node, __opts__.get('ssh_interface', 'public_ips'))[0])
if __opts__.get('update_cachedir', False) is True:
__utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__)
__utils__['cloud.cachedir_index_del'](name)
return True
log.error('Failed to Destroy VM: %s', name)
return False
def call(conn=None, call=None, kwargs=None):
'''
Call function from shade.
func
function to call from shade.openstackcloud library
CLI Example
.. code-block:: bash
salt-cloud -f call myopenstack func=list_images
t sujksalt-cloud -f call myopenstack func=create_network name=mysubnet
'''
if call == 'action':
raise SaltCloudSystemExit(
'The call function must be called with '
'-f or --function.'
)
if 'func' not in kwargs:
raise SaltCloudSystemExit(
'No `func` argument passed'
)
if conn is None:
conn = get_conn()
func = kwargs.pop('func')
for key, value in kwargs.items():
try:
kwargs[key] = __utils__['json.loads'](value)
except ValueError:
continue
try:
return getattr(conn, func)(**kwargs)
except shade.exc.OpenStackCloudException as exc:
log.error('Error running %s: %s', func, exc)
raise SaltCloudSystemExit(six.text_type(exc))
|
saltstack/salt
|
salt/cloud/clouds/openstack.py
|
destroy
|
python
|
def destroy(name, conn=None, call=None):
'''
Delete a single VM
'''
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']
)
if not conn:
conn = get_conn()
node = show_instance(name, conn=conn, call='action')
log.info('Destroying VM: %s', name)
ret = conn.delete_server(name)
if ret:
log.info('Destroyed VM: %s', name)
# Fire destroy action
__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('delete_sshkeys', False) is True:
__utils__['cloud.remove_sshkey'](getattr(node, __opts__.get('ssh_interface', 'public_ips'))[0])
if __opts__.get('update_cachedir', False) is True:
__utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__)
__utils__['cloud.cachedir_index_del'](name)
return True
log.error('Failed to Destroy VM: %s', name)
return False
|
Delete a single VM
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/openstack.py#L773-L816
|
[
"def show_instance(name, conn=None, call=None):\n '''\n Get VM on this OpenStack account\n\n name\n\n name of the instance\n\n CLI Example\n\n .. code-block:: bash\n\n salt-cloud -a show_instance myserver\n\n '''\n if call != 'action':\n raise SaltCloudSystemExit(\n 'The show_instance action must be called with -a or --action.'\n )\n if conn is None:\n conn = get_conn()\n\n node = conn.get_server(name, bare=True)\n ret = dict(node)\n ret['id'] = node.id\n ret['name'] = node.name\n ret['size'] = conn.get_flavor(node.flavor.id).name\n ret['state'] = node.status\n ret['private_ips'] = _get_ips(node, 'private')\n ret['public_ips'] = _get_ips(node, 'public')\n ret['floating_ips'] = _get_ips(node, 'floating')\n ret['fixed_ips'] = _get_ips(node, 'fixed')\n if isinstance(node.image, six.string_types):\n ret['image'] = node.image\n else:\n ret['image'] = conn.get_image(node.image.id).name\n return ret\n",
"def get_conn():\n '''\n Return a conn object for the passed VM data\n '''\n if __active_provider_name__ in __context__:\n return __context__[__active_provider_name__]\n vm_ = get_configured_provider()\n profile = vm_.pop('profile', None)\n if profile is not None:\n vm_ = __utils__['dictupdate.update'](os_client_config.vendors.get_profile(profile), vm_)\n conn = shade.openstackcloud.OpenStackCloud(cloud_config=None, **vm_)\n if __active_provider_name__ is not None:\n __context__[__active_provider_name__] = conn\n return conn\n"
] |
# -*- coding: utf-8 -*-
'''
Openstack Cloud Driver
======================
:depends: `shade>=1.19.0 <https://pypi.python.org/pypi/shade>`_
OpenStack is an open source project that is in use by a number a cloud
providers, each of which have their own ways of using it.
This OpenStack driver uses a the shade python module which is managed by the
OpenStack Infra team. This module is written to handle all the different
versions of different OpenStack tools for salt, so most commands are just passed
over to the module to handle everything.
Provider
--------
There are two ways to configure providers for this driver. The first one is to
just let shade handle everything, and configure using os-client-config_ and
setting up `/etc/openstack/clouds.yml`.
.. code-block:: yaml
clouds:
democloud:
region_name: RegionOne
auth:
username: 'demo'
password: secret
project_name: 'demo'
auth_url: 'http://openstack/identity'
And then this can be referenced in the salt provider based on the `democloud`
name.
.. code-block:: yaml
myopenstack:
driver: openstack
cloud: democloud
region_name: RegionOne
This allows for just using one configuration for salt-cloud and for any other
openstack tools which are all using `/etc/openstack/clouds.yml`
The other method allows for specifying everything in the provider config,
instead of using the extra configuration file. This will allow for passing
salt-cloud configs only through pillars for minions without having to write a
clouds.yml file on each minion.abs
.. code-block:: yaml
myopenstack:
driver: openstack
region_name: RegionOne
auth:
username: 'demo'
password: secret
project_name: 'demo'
auth_url: 'http://openstack/identity'
Or if you need to use a profile to setup some extra stuff, it can be passed as a
`profile` to use any of the vendor_ config options.
.. code-block:: yaml
myrackspace:
driver: openstack
profile: rackspace
auth:
username: rackusername
api_key: myapikey
region_name: ORD
auth_type: rackspace_apikey
And this will pull in the profile for rackspace and setup all the correct
options for the auth_url and different api versions for services.
Profile
-------
Most of the options for building servers are just passed on to the
create_server_ function from shade.
The salt specific ones are:
- ssh_key_file: The path to the ssh key that should be used to login to the machine to bootstrap it
- ssh_key_file: The name of the keypair in openstack
- userdata_template: The renderer to use if the userdata is a file that is templated. Default: False
- ssh_interface: The interface to use to login for bootstrapping: public_ips, private_ips, floating_ips, fixed_ips
.. code-block:: yaml
centos:
provider: myopenstack
image: CentOS 7
size: ds1G
ssh_key_name: mykey
ssh_key_file: /root/.ssh/id_rsa
This is the minimum setup required.
If metadata is set to make sure that the host has finished setting up the
`wait_for_metadata` can be set.
.. code-block:: yaml
centos:
provider: myopenstack
image: CentOS 7
size: ds1G
ssh_key_name: mykey
ssh_key_file: /root/.ssh/id_rsa
meta:
build_config: rack_user_only
wait_for_metadata:
rax_service_level_automation: Complete
rackconnect_automation_status: DEPLOYED
Anything else from the create_server_ docs can be passed through here.
- **image**: Image dict, name or ID to boot with. image is required
unless boot_volume is given.
- **flavor**: Flavor dict, name or ID to boot onto.
- **auto_ip**: Whether to take actions to find a routable IP for
the server. (defaults to True)
- **ips**: List of IPs to attach to the server (defaults to None)
- **ip_pool**: Name of the network or floating IP pool to get an
address from. (defaults to None)
- **root_volume**: Name or ID of a volume to boot from
(defaults to None - deprecated, use boot_volume)
- **boot_volume**: Name or ID of a volume to boot from
(defaults to None)
- **terminate_volume**: If booting from a volume, whether it should
be deleted when the server is destroyed.
(defaults to False)
- **volumes**: (optional) A list of volumes to attach to the server
- **meta**: (optional) A dict of arbitrary key/value metadata to
store for this server. Both keys and values must be
<=255 characters.
- **files**: (optional, deprecated) A dict of files to overwrite
on the server upon boot. Keys are file names (i.e.
``/etc/passwd``) and values
are the file contents (either as a string or as a
file-like object). A maximum of five entries is allowed,
and each file must be 10k or less.
- **reservation_id**: a UUID for the set of servers being requested.
- **min_count**: (optional extension) The minimum number of
servers to launch.
- **max_count**: (optional extension) The maximum number of
servers to launch.
- **security_groups**: A list of security group names
- **userdata**: user data to pass to be exposed by the metadata
server this can be a file type object as well or a
string.
- **key_name**: (optional extension) name of previously created
keypair to inject into the instance.
- **availability_zone**: Name of the availability zone for instance
placement.
- **block_device_mapping**: (optional) A dict of block
device mappings for this server.
- **block_device_mapping_v2**: (optional) A dict of block
device mappings for this server.
- **nics**: (optional extension) an ordered list of nics to be
added to this server, with information about
connected networks, fixed IPs, port etc.
- **scheduler_hints**: (optional extension) arbitrary key-value pairs
specified by the client to help boot an instance
- **config_drive**: (optional extension) value for config drive
either boolean, or volume-id
- **disk_config**: (optional extension) control how the disk is
partitioned when the server is created. possible
values are 'AUTO' or 'MANUAL'.
- **admin_pass**: (optional extension) add a user supplied admin
password.
- **timeout**: (optional) Seconds to wait, defaults to 60.
See the ``wait`` parameter.
- **reuse_ips**: (optional) Whether to attempt to reuse pre-existing
floating ips should a floating IP be
needed (defaults to True)
- **network**: (optional) Network dict or name or ID to attach the
server to. Mutually exclusive with the nics parameter.
Can also be be a list of network names or IDs or
network dicts.
- **boot_from_volume**: Whether to boot from volume. 'boot_volume'
implies True, but boot_from_volume=True with
no boot_volume is valid and will create a
volume from the image and use that.
- **volume_size**: When booting an image from volume, how big should
the created volume be? Defaults to 50.
- **nat_destination**: Which network should a created floating IP
be attached to, if it's not possible to
infer from the cloud's configuration.
(Optional, defaults to None)
- **group**: ServerGroup dict, name or id to boot the server in.
If a group is provided in both scheduler_hints and in
the group param, the group param will win.
(Optional, defaults to None)
.. note::
If there is anything added, that is not in this list, it can be added to an `extras`
dictionary for the profile, and that will be to the create_server function.
.. _create_server: https://docs.openstack.org/shade/latest/user/usage.html#shade.OpenStackCloud.create_server
.. _vendor: https://docs.openstack.org/os-client-config/latest/user/vendor-support.html
.. _os-client-config: https://docs.openstack.org/os-client-config/latest/user/configuration.html#config-files
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import Python Libs
import copy
import logging
import os
import pprint
import socket
# Import Salt Libs
import salt.utils.versions
import salt.config as config
from salt.ext import six
from salt.exceptions import (
SaltCloudSystemExit,
SaltCloudExecutionTimeout,
SaltCloudExecutionFailure,
SaltCloudConfigError,
)
# Import 3rd-Party Libs
try:
import shade
import shade.openstackcloud
import shade.exc
import os_client_config
HAS_SHADE = (
salt.utils.versions._LooseVersion(shade.__version__) >= salt.utils.versions._LooseVersion('1.19.0'),
'Please install newer version of shade: >= 1.19.0'
)
except ImportError:
HAS_SHADE = (False, 'Install pypi module shade >= 1.19.0')
log = logging.getLogger(__name__)
__virtualname__ = 'openstack'
def __virtual__():
'''
Check for OpenStack dependencies
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return HAS_SHADE
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__, __active_provider_name__ or __virtualname__,
('auth', 'region_name'), log_message=False,
) or config.is_provider_configured(
__opts__, __active_provider_name__ or __virtualname__,
('cloud', 'region_name')
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
deps = {
'shade': shade[0],
'os_client_config': shade[0],
}
return config.check_driver_dependencies(
__virtualname__,
deps
)
def preferred_ip(vm_, ips):
'''
Return the preferred Internet protocol. Either 'ipv4' (default) or 'ipv6'.
'''
proto = config.get_cloud_config_value(
'protocol', vm_, __opts__, default='ipv4', search_global=False
)
family = socket.AF_INET
if proto == 'ipv6':
family = socket.AF_INET6
for ip in ips:
try:
socket.inet_pton(family, ip)
return ip
except Exception:
continue
return False
def ssh_interface(vm_):
'''
Return the ssh_interface type to connect to. Either 'public_ips' (default)
or 'private_ips'.
'''
return config.get_cloud_config_value('ssh_interface', vm_, __opts__, default='public_ips', search_global=False)
def get_conn():
'''
Return a conn object for the passed VM data
'''
if __active_provider_name__ in __context__:
return __context__[__active_provider_name__]
vm_ = get_configured_provider()
profile = vm_.pop('profile', None)
if profile is not None:
vm_ = __utils__['dictupdate.update'](os_client_config.vendors.get_profile(profile), vm_)
conn = shade.openstackcloud.OpenStackCloud(cloud_config=None, **vm_)
if __active_provider_name__ is not None:
__context__[__active_provider_name__] = conn
return conn
def list_nodes(conn=None, call=None):
'''
Return a list of VMs
CLI Example
.. code-block:: bash
salt-cloud -f list_nodes myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
ret = {}
for node, info in list_nodes_full(conn=conn).items():
for key in ('id', 'name', 'size', 'state', 'private_ips', 'public_ips', 'floating_ips', 'fixed_ips', 'image'):
ret.setdefault(node, {}).setdefault(key, info.get(key))
return ret
def list_nodes_min(conn=None, call=None):
'''
Return a list of VMs with minimal information
CLI Example
.. code-block:: bash
salt-cloud -f list_nodes_min myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_min function must be called with -f or --function.'
)
if conn is None:
conn = get_conn()
ret = {}
for node in conn.list_servers(bare=True):
ret[node.name] = {'id': node.id, 'state': node.status}
return ret
def _get_ips(node, addr_type='public'):
ret = []
for _, interface in node.addresses.items():
for addr in interface:
if addr_type in ('floating', 'fixed') and addr_type == addr.get('OS-EXT-IPS:type'):
ret.append(addr['addr'])
elif addr_type == 'public' and __utils__['cloud.is_public_ip'](addr['addr']):
ret.append(addr['addr'])
elif addr_type == 'private' and not __utils__['cloud.is_public_ip'](addr['addr']):
ret.append(addr['addr'])
return ret
def list_nodes_full(conn=None, call=None):
'''
Return a list of VMs with all the information about them
CLI Example
.. code-block:: bash
salt-cloud -f list_nodes_full myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or --function.'
)
if conn is None:
conn = get_conn()
ret = {}
for node in conn.list_servers(detailed=True):
ret[node.name] = dict(node)
ret[node.name]['id'] = node.id
ret[node.name]['name'] = node.name
ret[node.name]['size'] = node.flavor.name
ret[node.name]['state'] = node.status
ret[node.name]['private_ips'] = _get_ips(node, 'private')
ret[node.name]['public_ips'] = _get_ips(node, 'public')
ret[node.name]['floating_ips'] = _get_ips(node, 'floating')
ret[node.name]['fixed_ips'] = _get_ips(node, 'fixed')
ret[node.name]['image'] = node.image.name
return ret
def list_nodes_select(conn=None, call=None):
'''
Return a list of VMs with the fields from `query.selection`
CLI Example
.. code-block:: bash
salt-cloud -f list_nodes_full myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_select function must be called with -f or --function.'
)
return __utils__['cloud.list_nodes_select'](
list_nodes(conn, 'function'), __opts__['query.selection'], call,
)
def show_instance(name, conn=None, call=None):
'''
Get VM on this OpenStack account
name
name of the instance
CLI Example
.. code-block:: bash
salt-cloud -a show_instance myserver
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
if conn is None:
conn = get_conn()
node = conn.get_server(name, bare=True)
ret = dict(node)
ret['id'] = node.id
ret['name'] = node.name
ret['size'] = conn.get_flavor(node.flavor.id).name
ret['state'] = node.status
ret['private_ips'] = _get_ips(node, 'private')
ret['public_ips'] = _get_ips(node, 'public')
ret['floating_ips'] = _get_ips(node, 'floating')
ret['fixed_ips'] = _get_ips(node, 'fixed')
if isinstance(node.image, six.string_types):
ret['image'] = node.image
else:
ret['image'] = conn.get_image(node.image.id).name
return ret
def avail_images(conn=None, call=None):
'''
List available images for OpenStack
CLI Example
.. code-block:: bash
salt-cloud -f avail_images myopenstack
salt-cloud --list-images myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
if conn is None:
conn = get_conn()
return conn.list_images()
def avail_sizes(conn=None, call=None):
'''
List available sizes for OpenStack
CLI Example
.. code-block:: bash
salt-cloud -f avail_sizes myopenstack
salt-cloud --list-sizes myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
if conn is None:
conn = get_conn()
return conn.list_flavors()
def list_networks(conn=None, call=None):
'''
List networks for OpenStack
CLI Example
.. code-block:: bash
salt-cloud -f list_networks myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_networks function must be called with '
'-f or --function'
)
if conn is None:
conn = get_conn()
return conn.list_networks()
def list_subnets(conn=None, call=None, kwargs=None):
'''
List subnets in a virtual network
network
network to list subnets of
.. code-block:: bash
salt-cloud -f list_subnets myopenstack network=salt-net
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_subnets function must be called with '
'-f or --function.'
)
if conn is None:
conn = get_conn()
if kwargs is None or (isinstance(kwargs, dict) and 'network' not in kwargs):
raise SaltCloudSystemExit(
'A `network` must be specified'
)
return conn.list_subnets(filters={'network': kwargs['network']})
def _clean_create_kwargs(**kwargs):
'''
Sanatize kwargs to be sent to create_server
'''
VALID_OPTS = {
'name': six.string_types,
'image': six.string_types,
'flavor': six.string_types,
'auto_ip': bool,
'ips': list,
'ip_pool': six.string_types,
'root_volume': six.string_types,
'boot_volume': six.string_types,
'terminate_volume': bool,
'volumes': list,
'meta': dict,
'files': dict,
'reservation_id': six.string_types,
'security_groups': list,
'key_name': six.string_types,
'availability_zone': six.string_types,
'block_device_mapping': dict,
'block_device_mapping_v2': dict,
'nics': list,
'scheduler_hints': dict,
'config_drive': bool,
'disk_config': six.string_types, # AUTO or MANUAL
'admin_pass': six.string_types,
'wait': bool,
'timeout': int,
'reuse_ips': bool,
'network': dict,
'boot_from_volume': bool,
'volume_size': int,
'nat_destination': six.string_types,
'group': six.string_types,
'userdata': six.string_types,
}
extra = kwargs.pop('extra', {})
for key, value in six.iteritems(kwargs.copy()):
if key in VALID_OPTS:
if isinstance(value, VALID_OPTS[key]):
continue
log.error('Error %s: %s is not of type %s', key, value, VALID_OPTS[key])
kwargs.pop(key)
return __utils__['dictupdate.update'](kwargs, extra)
def request_instance(vm_, conn=None, call=None):
'''
Request an instance to be built
'''
if call == 'function':
# Technically this function may be called other ways too, but it
# definitely cannot be called with --function.
raise SaltCloudSystemExit(
'The request_instance action must be called with -a or --action.'
)
kwargs = copy.deepcopy(vm_)
log.info('Creating Cloud VM %s', vm_['name'])
__utils__['cloud.check_name'](vm_['name'], 'a-zA-Z0-9._-')
conn = get_conn()
userdata = config.get_cloud_config_value(
'userdata', vm_, __opts__, search_global=False, default=None
)
if userdata is not None and os.path.isfile(userdata):
try:
with __utils__['files.fopen'](userdata, 'r') as fp_:
kwargs['userdata'] = __utils__['cloud.userdata_template'](
__opts__, vm_, fp_.read()
)
except Exception as exc:
log.exception(
'Failed to read userdata from %s: %s', userdata, exc)
if 'size' in kwargs:
kwargs['flavor'] = kwargs.pop('size')
kwargs['key_name'] = config.get_cloud_config_value(
'ssh_key_name', vm_, __opts__, search_global=False, default=None
)
kwargs['wait'] = True
try:
conn.create_server(**_clean_create_kwargs(**kwargs))
except shade.exc.OpenStackCloudException as exc:
log.error('Error creating server %s: %s', vm_['name'], exc)
destroy(vm_['name'], conn=conn, call='action')
raise SaltCloudSystemExit(six.text_type(exc))
return show_instance(vm_['name'], conn=conn, call='action')
def create(vm_):
'''
Create a single VM from a data dict
'''
deploy = config.get_cloud_config_value('deploy', vm_, __opts__)
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 ssh_key_file \'{0}\' does not exist'.format(
key_filename
)
)
vm_['key_filename'] = key_filename
__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']
)
conn = get_conn()
if 'instance_id' in vm_:
# This was probably created via another process, and doesn't have
# things like salt keys created yet, so let's create them now.
if 'pub_key' not in vm_ and 'priv_key' not in vm_:
log.debug('Generating minion keys for \'%s\'', vm_['name'])
vm_['priv_key'], vm_['pub_key'] = __utils__['cloud.gen_keys'](
config.get_cloud_config_value(
'keysize',
vm_,
__opts__
)
)
else:
# Put together all of the information required to request the instance,
# and then fire off the request for it
request_instance(conn=conn, call='action', vm_=vm_)
data = show_instance(vm_.get('instance_id', vm_['name']), conn=conn, call='action')
log.debug('VM is now running')
def __query_node(vm_):
data = show_instance(vm_['name'], conn=conn, call='action')
if 'wait_for_metadata' in vm_:
for key, value in six.iteritems(vm_.get('wait_for_metadata', {})):
log.debug('Waiting for metadata: %s=%s', key, value)
if data['metadata'].get(key, None) != value:
log.debug('Metadata is not ready: %s=%s', key, data['metadata'].get(key))
return False
return preferred_ip(vm_, data[ssh_interface(vm_)])
try:
ip_address = __utils__['cloud.wait_for_fun'](
__query_node,
vm_=vm_
)
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))
log.debug('Using IP address %s', ip_address)
salt_interface = __utils__['cloud.get_salt_interface'](vm_, __opts__)
salt_ip_address = preferred_ip(vm_, data[salt_interface])
log.debug('Salt interface set to: %s', salt_ip_address)
if not ip_address:
raise SaltCloudSystemExit('A valid IP address was not found')
vm_['ssh_host'] = ip_address
vm_['salt_host'] = salt_ip_address
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)
)
event_data = {
'name': vm_['name'],
'profile': vm_['profile'],
'provider': vm_['driver'],
'instance_id': data['id'],
'floating_ips': data['floating_ips'],
'fixed_ips': data['fixed_ips'],
'private_ips': data['private_ips'],
'public_ips': data['public_ips'],
}
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args=__utils__['cloud.filter_event']('created', event_data, list(event_data)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
__utils__['cloud.cachedir_index_add'](vm_['name'], vm_['profile'], 'nova', vm_['driver'])
return ret
def call(conn=None, call=None, kwargs=None):
'''
Call function from shade.
func
function to call from shade.openstackcloud library
CLI Example
.. code-block:: bash
salt-cloud -f call myopenstack func=list_images
t sujksalt-cloud -f call myopenstack func=create_network name=mysubnet
'''
if call == 'action':
raise SaltCloudSystemExit(
'The call function must be called with '
'-f or --function.'
)
if 'func' not in kwargs:
raise SaltCloudSystemExit(
'No `func` argument passed'
)
if conn is None:
conn = get_conn()
func = kwargs.pop('func')
for key, value in kwargs.items():
try:
kwargs[key] = __utils__['json.loads'](value)
except ValueError:
continue
try:
return getattr(conn, func)(**kwargs)
except shade.exc.OpenStackCloudException as exc:
log.error('Error running %s: %s', func, exc)
raise SaltCloudSystemExit(six.text_type(exc))
|
saltstack/salt
|
salt/cloud/clouds/openstack.py
|
call
|
python
|
def call(conn=None, call=None, kwargs=None):
'''
Call function from shade.
func
function to call from shade.openstackcloud library
CLI Example
.. code-block:: bash
salt-cloud -f call myopenstack func=list_images
t sujksalt-cloud -f call myopenstack func=create_network name=mysubnet
'''
if call == 'action':
raise SaltCloudSystemExit(
'The call function must be called with '
'-f or --function.'
)
if 'func' not in kwargs:
raise SaltCloudSystemExit(
'No `func` argument passed'
)
if conn is None:
conn = get_conn()
func = kwargs.pop('func')
for key, value in kwargs.items():
try:
kwargs[key] = __utils__['json.loads'](value)
except ValueError:
continue
try:
return getattr(conn, func)(**kwargs)
except shade.exc.OpenStackCloudException as exc:
log.error('Error running %s: %s', func, exc)
raise SaltCloudSystemExit(six.text_type(exc))
|
Call function from shade.
func
function to call from shade.openstackcloud library
CLI Example
.. code-block:: bash
salt-cloud -f call myopenstack func=list_images
t sujksalt-cloud -f call myopenstack func=create_network name=mysubnet
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/openstack.py#L819-L858
|
[
"def get_conn():\n '''\n Return a conn object for the passed VM data\n '''\n if __active_provider_name__ in __context__:\n return __context__[__active_provider_name__]\n vm_ = get_configured_provider()\n profile = vm_.pop('profile', None)\n if profile is not None:\n vm_ = __utils__['dictupdate.update'](os_client_config.vendors.get_profile(profile), vm_)\n conn = shade.openstackcloud.OpenStackCloud(cloud_config=None, **vm_)\n if __active_provider_name__ is not None:\n __context__[__active_provider_name__] = conn\n return conn\n"
] |
# -*- coding: utf-8 -*-
'''
Openstack Cloud Driver
======================
:depends: `shade>=1.19.0 <https://pypi.python.org/pypi/shade>`_
OpenStack is an open source project that is in use by a number a cloud
providers, each of which have their own ways of using it.
This OpenStack driver uses a the shade python module which is managed by the
OpenStack Infra team. This module is written to handle all the different
versions of different OpenStack tools for salt, so most commands are just passed
over to the module to handle everything.
Provider
--------
There are two ways to configure providers for this driver. The first one is to
just let shade handle everything, and configure using os-client-config_ and
setting up `/etc/openstack/clouds.yml`.
.. code-block:: yaml
clouds:
democloud:
region_name: RegionOne
auth:
username: 'demo'
password: secret
project_name: 'demo'
auth_url: 'http://openstack/identity'
And then this can be referenced in the salt provider based on the `democloud`
name.
.. code-block:: yaml
myopenstack:
driver: openstack
cloud: democloud
region_name: RegionOne
This allows for just using one configuration for salt-cloud and for any other
openstack tools which are all using `/etc/openstack/clouds.yml`
The other method allows for specifying everything in the provider config,
instead of using the extra configuration file. This will allow for passing
salt-cloud configs only through pillars for minions without having to write a
clouds.yml file on each minion.abs
.. code-block:: yaml
myopenstack:
driver: openstack
region_name: RegionOne
auth:
username: 'demo'
password: secret
project_name: 'demo'
auth_url: 'http://openstack/identity'
Or if you need to use a profile to setup some extra stuff, it can be passed as a
`profile` to use any of the vendor_ config options.
.. code-block:: yaml
myrackspace:
driver: openstack
profile: rackspace
auth:
username: rackusername
api_key: myapikey
region_name: ORD
auth_type: rackspace_apikey
And this will pull in the profile for rackspace and setup all the correct
options for the auth_url and different api versions for services.
Profile
-------
Most of the options for building servers are just passed on to the
create_server_ function from shade.
The salt specific ones are:
- ssh_key_file: The path to the ssh key that should be used to login to the machine to bootstrap it
- ssh_key_file: The name of the keypair in openstack
- userdata_template: The renderer to use if the userdata is a file that is templated. Default: False
- ssh_interface: The interface to use to login for bootstrapping: public_ips, private_ips, floating_ips, fixed_ips
.. code-block:: yaml
centos:
provider: myopenstack
image: CentOS 7
size: ds1G
ssh_key_name: mykey
ssh_key_file: /root/.ssh/id_rsa
This is the minimum setup required.
If metadata is set to make sure that the host has finished setting up the
`wait_for_metadata` can be set.
.. code-block:: yaml
centos:
provider: myopenstack
image: CentOS 7
size: ds1G
ssh_key_name: mykey
ssh_key_file: /root/.ssh/id_rsa
meta:
build_config: rack_user_only
wait_for_metadata:
rax_service_level_automation: Complete
rackconnect_automation_status: DEPLOYED
Anything else from the create_server_ docs can be passed through here.
- **image**: Image dict, name or ID to boot with. image is required
unless boot_volume is given.
- **flavor**: Flavor dict, name or ID to boot onto.
- **auto_ip**: Whether to take actions to find a routable IP for
the server. (defaults to True)
- **ips**: List of IPs to attach to the server (defaults to None)
- **ip_pool**: Name of the network or floating IP pool to get an
address from. (defaults to None)
- **root_volume**: Name or ID of a volume to boot from
(defaults to None - deprecated, use boot_volume)
- **boot_volume**: Name or ID of a volume to boot from
(defaults to None)
- **terminate_volume**: If booting from a volume, whether it should
be deleted when the server is destroyed.
(defaults to False)
- **volumes**: (optional) A list of volumes to attach to the server
- **meta**: (optional) A dict of arbitrary key/value metadata to
store for this server. Both keys and values must be
<=255 characters.
- **files**: (optional, deprecated) A dict of files to overwrite
on the server upon boot. Keys are file names (i.e.
``/etc/passwd``) and values
are the file contents (either as a string or as a
file-like object). A maximum of five entries is allowed,
and each file must be 10k or less.
- **reservation_id**: a UUID for the set of servers being requested.
- **min_count**: (optional extension) The minimum number of
servers to launch.
- **max_count**: (optional extension) The maximum number of
servers to launch.
- **security_groups**: A list of security group names
- **userdata**: user data to pass to be exposed by the metadata
server this can be a file type object as well or a
string.
- **key_name**: (optional extension) name of previously created
keypair to inject into the instance.
- **availability_zone**: Name of the availability zone for instance
placement.
- **block_device_mapping**: (optional) A dict of block
device mappings for this server.
- **block_device_mapping_v2**: (optional) A dict of block
device mappings for this server.
- **nics**: (optional extension) an ordered list of nics to be
added to this server, with information about
connected networks, fixed IPs, port etc.
- **scheduler_hints**: (optional extension) arbitrary key-value pairs
specified by the client to help boot an instance
- **config_drive**: (optional extension) value for config drive
either boolean, or volume-id
- **disk_config**: (optional extension) control how the disk is
partitioned when the server is created. possible
values are 'AUTO' or 'MANUAL'.
- **admin_pass**: (optional extension) add a user supplied admin
password.
- **timeout**: (optional) Seconds to wait, defaults to 60.
See the ``wait`` parameter.
- **reuse_ips**: (optional) Whether to attempt to reuse pre-existing
floating ips should a floating IP be
needed (defaults to True)
- **network**: (optional) Network dict or name or ID to attach the
server to. Mutually exclusive with the nics parameter.
Can also be be a list of network names or IDs or
network dicts.
- **boot_from_volume**: Whether to boot from volume. 'boot_volume'
implies True, but boot_from_volume=True with
no boot_volume is valid and will create a
volume from the image and use that.
- **volume_size**: When booting an image from volume, how big should
the created volume be? Defaults to 50.
- **nat_destination**: Which network should a created floating IP
be attached to, if it's not possible to
infer from the cloud's configuration.
(Optional, defaults to None)
- **group**: ServerGroup dict, name or id to boot the server in.
If a group is provided in both scheduler_hints and in
the group param, the group param will win.
(Optional, defaults to None)
.. note::
If there is anything added, that is not in this list, it can be added to an `extras`
dictionary for the profile, and that will be to the create_server function.
.. _create_server: https://docs.openstack.org/shade/latest/user/usage.html#shade.OpenStackCloud.create_server
.. _vendor: https://docs.openstack.org/os-client-config/latest/user/vendor-support.html
.. _os-client-config: https://docs.openstack.org/os-client-config/latest/user/configuration.html#config-files
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import Python Libs
import copy
import logging
import os
import pprint
import socket
# Import Salt Libs
import salt.utils.versions
import salt.config as config
from salt.ext import six
from salt.exceptions import (
SaltCloudSystemExit,
SaltCloudExecutionTimeout,
SaltCloudExecutionFailure,
SaltCloudConfigError,
)
# Import 3rd-Party Libs
try:
import shade
import shade.openstackcloud
import shade.exc
import os_client_config
HAS_SHADE = (
salt.utils.versions._LooseVersion(shade.__version__) >= salt.utils.versions._LooseVersion('1.19.0'),
'Please install newer version of shade: >= 1.19.0'
)
except ImportError:
HAS_SHADE = (False, 'Install pypi module shade >= 1.19.0')
log = logging.getLogger(__name__)
__virtualname__ = 'openstack'
def __virtual__():
'''
Check for OpenStack dependencies
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return HAS_SHADE
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__, __active_provider_name__ or __virtualname__,
('auth', 'region_name'), log_message=False,
) or config.is_provider_configured(
__opts__, __active_provider_name__ or __virtualname__,
('cloud', 'region_name')
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
deps = {
'shade': shade[0],
'os_client_config': shade[0],
}
return config.check_driver_dependencies(
__virtualname__,
deps
)
def preferred_ip(vm_, ips):
'''
Return the preferred Internet protocol. Either 'ipv4' (default) or 'ipv6'.
'''
proto = config.get_cloud_config_value(
'protocol', vm_, __opts__, default='ipv4', search_global=False
)
family = socket.AF_INET
if proto == 'ipv6':
family = socket.AF_INET6
for ip in ips:
try:
socket.inet_pton(family, ip)
return ip
except Exception:
continue
return False
def ssh_interface(vm_):
'''
Return the ssh_interface type to connect to. Either 'public_ips' (default)
or 'private_ips'.
'''
return config.get_cloud_config_value('ssh_interface', vm_, __opts__, default='public_ips', search_global=False)
def get_conn():
'''
Return a conn object for the passed VM data
'''
if __active_provider_name__ in __context__:
return __context__[__active_provider_name__]
vm_ = get_configured_provider()
profile = vm_.pop('profile', None)
if profile is not None:
vm_ = __utils__['dictupdate.update'](os_client_config.vendors.get_profile(profile), vm_)
conn = shade.openstackcloud.OpenStackCloud(cloud_config=None, **vm_)
if __active_provider_name__ is not None:
__context__[__active_provider_name__] = conn
return conn
def list_nodes(conn=None, call=None):
'''
Return a list of VMs
CLI Example
.. code-block:: bash
salt-cloud -f list_nodes myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
ret = {}
for node, info in list_nodes_full(conn=conn).items():
for key in ('id', 'name', 'size', 'state', 'private_ips', 'public_ips', 'floating_ips', 'fixed_ips', 'image'):
ret.setdefault(node, {}).setdefault(key, info.get(key))
return ret
def list_nodes_min(conn=None, call=None):
'''
Return a list of VMs with minimal information
CLI Example
.. code-block:: bash
salt-cloud -f list_nodes_min myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_min function must be called with -f or --function.'
)
if conn is None:
conn = get_conn()
ret = {}
for node in conn.list_servers(bare=True):
ret[node.name] = {'id': node.id, 'state': node.status}
return ret
def _get_ips(node, addr_type='public'):
ret = []
for _, interface in node.addresses.items():
for addr in interface:
if addr_type in ('floating', 'fixed') and addr_type == addr.get('OS-EXT-IPS:type'):
ret.append(addr['addr'])
elif addr_type == 'public' and __utils__['cloud.is_public_ip'](addr['addr']):
ret.append(addr['addr'])
elif addr_type == 'private' and not __utils__['cloud.is_public_ip'](addr['addr']):
ret.append(addr['addr'])
return ret
def list_nodes_full(conn=None, call=None):
'''
Return a list of VMs with all the information about them
CLI Example
.. code-block:: bash
salt-cloud -f list_nodes_full myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or --function.'
)
if conn is None:
conn = get_conn()
ret = {}
for node in conn.list_servers(detailed=True):
ret[node.name] = dict(node)
ret[node.name]['id'] = node.id
ret[node.name]['name'] = node.name
ret[node.name]['size'] = node.flavor.name
ret[node.name]['state'] = node.status
ret[node.name]['private_ips'] = _get_ips(node, 'private')
ret[node.name]['public_ips'] = _get_ips(node, 'public')
ret[node.name]['floating_ips'] = _get_ips(node, 'floating')
ret[node.name]['fixed_ips'] = _get_ips(node, 'fixed')
ret[node.name]['image'] = node.image.name
return ret
def list_nodes_select(conn=None, call=None):
'''
Return a list of VMs with the fields from `query.selection`
CLI Example
.. code-block:: bash
salt-cloud -f list_nodes_full myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_select function must be called with -f or --function.'
)
return __utils__['cloud.list_nodes_select'](
list_nodes(conn, 'function'), __opts__['query.selection'], call,
)
def show_instance(name, conn=None, call=None):
'''
Get VM on this OpenStack account
name
name of the instance
CLI Example
.. code-block:: bash
salt-cloud -a show_instance myserver
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
if conn is None:
conn = get_conn()
node = conn.get_server(name, bare=True)
ret = dict(node)
ret['id'] = node.id
ret['name'] = node.name
ret['size'] = conn.get_flavor(node.flavor.id).name
ret['state'] = node.status
ret['private_ips'] = _get_ips(node, 'private')
ret['public_ips'] = _get_ips(node, 'public')
ret['floating_ips'] = _get_ips(node, 'floating')
ret['fixed_ips'] = _get_ips(node, 'fixed')
if isinstance(node.image, six.string_types):
ret['image'] = node.image
else:
ret['image'] = conn.get_image(node.image.id).name
return ret
def avail_images(conn=None, call=None):
'''
List available images for OpenStack
CLI Example
.. code-block:: bash
salt-cloud -f avail_images myopenstack
salt-cloud --list-images myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
if conn is None:
conn = get_conn()
return conn.list_images()
def avail_sizes(conn=None, call=None):
'''
List available sizes for OpenStack
CLI Example
.. code-block:: bash
salt-cloud -f avail_sizes myopenstack
salt-cloud --list-sizes myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
if conn is None:
conn = get_conn()
return conn.list_flavors()
def list_networks(conn=None, call=None):
'''
List networks for OpenStack
CLI Example
.. code-block:: bash
salt-cloud -f list_networks myopenstack
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_networks function must be called with '
'-f or --function'
)
if conn is None:
conn = get_conn()
return conn.list_networks()
def list_subnets(conn=None, call=None, kwargs=None):
'''
List subnets in a virtual network
network
network to list subnets of
.. code-block:: bash
salt-cloud -f list_subnets myopenstack network=salt-net
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_subnets function must be called with '
'-f or --function.'
)
if conn is None:
conn = get_conn()
if kwargs is None or (isinstance(kwargs, dict) and 'network' not in kwargs):
raise SaltCloudSystemExit(
'A `network` must be specified'
)
return conn.list_subnets(filters={'network': kwargs['network']})
def _clean_create_kwargs(**kwargs):
'''
Sanatize kwargs to be sent to create_server
'''
VALID_OPTS = {
'name': six.string_types,
'image': six.string_types,
'flavor': six.string_types,
'auto_ip': bool,
'ips': list,
'ip_pool': six.string_types,
'root_volume': six.string_types,
'boot_volume': six.string_types,
'terminate_volume': bool,
'volumes': list,
'meta': dict,
'files': dict,
'reservation_id': six.string_types,
'security_groups': list,
'key_name': six.string_types,
'availability_zone': six.string_types,
'block_device_mapping': dict,
'block_device_mapping_v2': dict,
'nics': list,
'scheduler_hints': dict,
'config_drive': bool,
'disk_config': six.string_types, # AUTO or MANUAL
'admin_pass': six.string_types,
'wait': bool,
'timeout': int,
'reuse_ips': bool,
'network': dict,
'boot_from_volume': bool,
'volume_size': int,
'nat_destination': six.string_types,
'group': six.string_types,
'userdata': six.string_types,
}
extra = kwargs.pop('extra', {})
for key, value in six.iteritems(kwargs.copy()):
if key in VALID_OPTS:
if isinstance(value, VALID_OPTS[key]):
continue
log.error('Error %s: %s is not of type %s', key, value, VALID_OPTS[key])
kwargs.pop(key)
return __utils__['dictupdate.update'](kwargs, extra)
def request_instance(vm_, conn=None, call=None):
'''
Request an instance to be built
'''
if call == 'function':
# Technically this function may be called other ways too, but it
# definitely cannot be called with --function.
raise SaltCloudSystemExit(
'The request_instance action must be called with -a or --action.'
)
kwargs = copy.deepcopy(vm_)
log.info('Creating Cloud VM %s', vm_['name'])
__utils__['cloud.check_name'](vm_['name'], 'a-zA-Z0-9._-')
conn = get_conn()
userdata = config.get_cloud_config_value(
'userdata', vm_, __opts__, search_global=False, default=None
)
if userdata is not None and os.path.isfile(userdata):
try:
with __utils__['files.fopen'](userdata, 'r') as fp_:
kwargs['userdata'] = __utils__['cloud.userdata_template'](
__opts__, vm_, fp_.read()
)
except Exception as exc:
log.exception(
'Failed to read userdata from %s: %s', userdata, exc)
if 'size' in kwargs:
kwargs['flavor'] = kwargs.pop('size')
kwargs['key_name'] = config.get_cloud_config_value(
'ssh_key_name', vm_, __opts__, search_global=False, default=None
)
kwargs['wait'] = True
try:
conn.create_server(**_clean_create_kwargs(**kwargs))
except shade.exc.OpenStackCloudException as exc:
log.error('Error creating server %s: %s', vm_['name'], exc)
destroy(vm_['name'], conn=conn, call='action')
raise SaltCloudSystemExit(six.text_type(exc))
return show_instance(vm_['name'], conn=conn, call='action')
def create(vm_):
'''
Create a single VM from a data dict
'''
deploy = config.get_cloud_config_value('deploy', vm_, __opts__)
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 ssh_key_file \'{0}\' does not exist'.format(
key_filename
)
)
vm_['key_filename'] = key_filename
__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']
)
conn = get_conn()
if 'instance_id' in vm_:
# This was probably created via another process, and doesn't have
# things like salt keys created yet, so let's create them now.
if 'pub_key' not in vm_ and 'priv_key' not in vm_:
log.debug('Generating minion keys for \'%s\'', vm_['name'])
vm_['priv_key'], vm_['pub_key'] = __utils__['cloud.gen_keys'](
config.get_cloud_config_value(
'keysize',
vm_,
__opts__
)
)
else:
# Put together all of the information required to request the instance,
# and then fire off the request for it
request_instance(conn=conn, call='action', vm_=vm_)
data = show_instance(vm_.get('instance_id', vm_['name']), conn=conn, call='action')
log.debug('VM is now running')
def __query_node(vm_):
data = show_instance(vm_['name'], conn=conn, call='action')
if 'wait_for_metadata' in vm_:
for key, value in six.iteritems(vm_.get('wait_for_metadata', {})):
log.debug('Waiting for metadata: %s=%s', key, value)
if data['metadata'].get(key, None) != value:
log.debug('Metadata is not ready: %s=%s', key, data['metadata'].get(key))
return False
return preferred_ip(vm_, data[ssh_interface(vm_)])
try:
ip_address = __utils__['cloud.wait_for_fun'](
__query_node,
vm_=vm_
)
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))
log.debug('Using IP address %s', ip_address)
salt_interface = __utils__['cloud.get_salt_interface'](vm_, __opts__)
salt_ip_address = preferred_ip(vm_, data[salt_interface])
log.debug('Salt interface set to: %s', salt_ip_address)
if not ip_address:
raise SaltCloudSystemExit('A valid IP address was not found')
vm_['ssh_host'] = ip_address
vm_['salt_host'] = salt_ip_address
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)
)
event_data = {
'name': vm_['name'],
'profile': vm_['profile'],
'provider': vm_['driver'],
'instance_id': data['id'],
'floating_ips': data['floating_ips'],
'fixed_ips': data['fixed_ips'],
'private_ips': data['private_ips'],
'public_ips': data['public_ips'],
}
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args=__utils__['cloud.filter_event']('created', event_data, list(event_data)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
__utils__['cloud.cachedir_index_add'](vm_['name'], vm_['profile'], 'nova', vm_['driver'])
return ret
def destroy(name, conn=None, call=None):
'''
Delete a single VM
'''
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']
)
if not conn:
conn = get_conn()
node = show_instance(name, conn=conn, call='action')
log.info('Destroying VM: %s', name)
ret = conn.delete_server(name)
if ret:
log.info('Destroyed VM: %s', name)
# Fire destroy action
__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('delete_sshkeys', False) is True:
__utils__['cloud.remove_sshkey'](getattr(node, __opts__.get('ssh_interface', 'public_ips'))[0])
if __opts__.get('update_cachedir', False) is True:
__utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__)
__utils__['cloud.cachedir_index_del'](name)
return True
log.error('Failed to Destroy VM: %s', name)
return False
|
saltstack/salt
|
salt/modules/slsutil.py
|
merge
|
python
|
def merge(obj_a, obj_b, strategy='smart', renderer='yaml', merge_lists=False):
'''
Merge a data structure into another by choosing a merge strategy
Strategies:
* aggregate
* list
* overwrite
* recurse
* smart
CLI Example:
.. code-block:: shell
salt '*' slsutil.merge '{foo: Foo}' '{bar: Bar}'
'''
return salt.utils.dictupdate.merge(obj_a, obj_b, strategy, renderer,
merge_lists)
|
Merge a data structure into another by choosing a merge strategy
Strategies:
* aggregate
* list
* overwrite
* recurse
* smart
CLI Example:
.. code-block:: shell
salt '*' slsutil.merge '{foo: Foo}' '{bar: Bar}'
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/slsutil.py#L37-L56
|
[
"def merge(obj_a, obj_b, strategy='smart', renderer='yaml', merge_lists=False):\n if strategy == 'smart':\n if renderer.split('|')[-1] == 'yamlex' or renderer.startswith('yamlex_'):\n strategy = 'aggregate'\n else:\n strategy = 'recurse'\n\n if strategy == 'list':\n merged = merge_list(obj_a, obj_b)\n elif strategy == 'recurse':\n merged = merge_recurse(obj_a, obj_b, merge_lists)\n elif strategy == 'aggregate':\n #: level = 1 merge at least root data\n merged = merge_aggregate(obj_a, obj_b)\n elif strategy == 'overwrite':\n merged = merge_overwrite(obj_a, obj_b, merge_lists)\n elif strategy == 'none':\n # If we do not want to merge, there is only one pillar passed, so we can safely use the default recurse,\n # we just do not want to log an error\n merged = merge_recurse(obj_a, obj_b)\n else:\n log.warning(\n 'Unknown merging strategy \\'%s\\', fallback to recurse',\n strategy\n )\n merged = merge_recurse(obj_a, obj_b)\n\n return merged\n"
] |
# -*- coding: utf-8 -*-
'''
Utility functions for use with or in SLS files
'''
# Import Python libs
from __future__ import absolute_import, unicode_literals, print_function
import textwrap
import os
# Import Salt libs
import salt.exceptions
import salt.loader
import salt.template
import salt.utils.args
import salt.utils.dictupdate
def update(dest, upd, recursive_update=True, merge_lists=False):
'''
Merge ``upd`` recursively into ``dest``
If ``merge_lists=True``, will aggregate list object types instead of
replacing. This behavior is only activated when ``recursive_update=True``.
CLI Example:
.. code-block:: shell
salt '*' slsutil.update '{foo: Foo}' '{bar: Bar}'
'''
return salt.utils.dictupdate.update(dest, upd, recursive_update,
merge_lists)
def merge_all(lst, strategy='smart', renderer='yaml', merge_lists=False):
'''
.. versionadded:: 2019.2.0
Merge a list of objects into each other in order
:type lst: Iterable
:param lst: List of objects to be merged.
:type strategy: String
:param strategy: Merge strategy. See utils.dictupdate.
:type renderer: String
:param renderer:
Renderer type. Used to determine strategy when strategy is 'smart'.
:type merge_lists: Bool
:param merge_lists: Defines whether to merge embedded object lists.
CLI Example:
.. code-block:: shell
$ salt-call --output=txt slsutil.merge_all '[{foo: Foo}, {foo: Bar}]'
local: {u'foo': u'Bar'}
'''
ret = {}
for obj in lst:
ret = salt.utils.dictupdate.merge(
ret, obj, strategy, renderer, merge_lists
)
return ret
def renderer(path=None, string=None, default_renderer='jinja|yaml', **kwargs):
'''
Parse a string or file through Salt's renderer system
.. versionchanged:: 2018.3.0
Add support for Salt fileserver URIs.
This is an open-ended function and can be used for a variety of tasks. It
makes use of Salt's "renderer pipes" system to run a string or file through
a pipe of any of the loaded renderer modules.
:param path: The path to a file on Salt's fileserver (any URIs supported by
:py:func:`cp.get_url <salt.modules.cp.get_url>`) or on the local file
system.
:param string: An inline string to be used as the file to send through the
renderer system. Note, not all renderer modules can work with strings;
the 'py' renderer requires a file, for example.
:param default_renderer: The renderer pipe to send the file through; this
is overridden by a "she-bang" at the top of the file.
:param kwargs: Keyword args to pass to Salt's compile_template() function.
Keep in mind the goal of each renderer when choosing a render-pipe; for
example, the Jinja renderer processes a text file and produces a string,
however the YAML renderer processes a text file and produces a data
structure.
One possible use is to allow writing "map files", as are commonly seen in
Salt formulas, but without tying the renderer of the map file to the
renderer used in the other sls files. In other words, a map file could use
the Python renderer and still be included and used by an sls file that uses
the default 'jinja|yaml' renderer.
For example, the two following map files produce identical results but one
is written using the normal 'jinja|yaml' and the other is using 'py':
.. code-block:: jinja
#!jinja|yaml
{% set apache = salt.grains.filter_by({
...normal jinja map file here...
}, merge=salt.pillar.get('apache:lookup')) %}
{{ apache | yaml() }}
.. code-block:: python
#!py
def run():
apache = __salt__.grains.filter_by({
...normal map here but as a python dict...
}, merge=__salt__.pillar.get('apache:lookup'))
return apache
Regardless of which of the above map files is used, it can be accessed from
any other sls file by calling this function. The following is a usage
example in Jinja:
.. code-block:: jinja
{% set apache = salt.slsutil.renderer('map.sls') %}
CLI Example:
.. code-block:: bash
salt '*' slsutil.renderer salt://path/to/file
salt '*' slsutil.renderer /path/to/file
salt '*' slsutil.renderer /path/to/file.jinja 'jinja'
salt '*' slsutil.renderer /path/to/file.sls 'jinja|yaml'
salt '*' slsutil.renderer string='Inline template! {{ saltenv }}'
salt '*' slsutil.renderer string='Hello, {{ name }}.' name='world'
'''
if not path and not string:
raise salt.exceptions.SaltInvocationError(
'Must pass either path or string')
renderers = salt.loader.render(__opts__, __salt__)
if path:
path_or_string = __salt__['cp.get_url'](path, saltenv=kwargs.get('saltenv', 'base'))
elif string:
path_or_string = ':string:'
kwargs['input_data'] = string
ret = salt.template.compile_template(
path_or_string,
renderers,
default_renderer,
__opts__['renderer_blacklist'],
__opts__['renderer_whitelist'],
**kwargs
)
return ret.read() if __utils__['stringio.is_readable'](ret) else ret
def _get_serialize_fn(serializer, fn_name):
serializers = salt.loader.serializers(__opts__)
fns = getattr(serializers, serializer, None)
fn = getattr(fns, fn_name, None)
if not fns:
raise salt.exceptions.CommandExecutionError(
"Serializer '{0}' not found.".format(serializer))
if not fn:
raise salt.exceptions.CommandExecutionError(
"Serializer '{0}' does not implement {1}.".format(serializer,
fn_name))
return fn
def serialize(serializer, obj, **mod_kwargs):
'''
Serialize a Python object using a :py:mod:`serializer module
<salt.serializers>`
CLI Example:
.. code-block:: bash
salt '*' --no-parse=obj slsutil.serialize 'json' obj="{'foo': 'Foo!'}
Jinja Example:
.. code-block:: jinja
{% set json_string = salt.slsutil.serialize('json',
{'foo': 'Foo!'}) %}
'''
kwargs = salt.utils.args.clean_kwargs(**mod_kwargs)
return _get_serialize_fn(serializer, 'serialize')(obj, **kwargs)
def deserialize(serializer, stream_or_string, **mod_kwargs):
'''
Deserialize a Python object using a :py:mod:`serializer module
<salt.serializers>`
CLI Example:
.. code-block:: bash
salt '*' slsutil.deserialize 'json' '{"foo": "Foo!"}'
salt '*' --no-parse=stream_or_string slsutil.deserialize 'json' \\
stream_or_string='{"foo": "Foo!"}'
Jinja Example:
.. code-block:: jinja
{% set python_object = salt.slsutil.deserialize('json',
'{"foo": "Foo!"}') %}
'''
kwargs = salt.utils.args.clean_kwargs(**mod_kwargs)
return _get_serialize_fn(serializer, 'deserialize')(stream_or_string,
**kwargs)
def banner(width=72, commentchar='#', borderchar='#', blockstart=None, blockend=None,
title=None, text=None, newline=False):
'''
Create a standardized comment block to include in a templated file.
A common technique in configuration management is to include a comment
block in managed files, warning users not to modify the file. This
function simplifies and standardizes those comment blocks.
:param width: The width, in characters, of the banner. Default is 72.
:param commentchar: The character to be used in the starting position of
each line. This value should be set to a valid line comment character
for the syntax of the file in which the banner is being inserted.
Multiple character sequences, like '//' are supported.
If the file's syntax does not support line comments (such as XML),
use the ``blockstart`` and ``blockend`` options.
:param borderchar: The character to use in the top and bottom border of
the comment box. Must be a single character.
:param blockstart: The character sequence to use at the beginning of a
block comment. Should be used in conjunction with ``blockend``
:param blockend: The character sequence to use at the end of a
block comment. Should be used in conjunction with ``blockstart``
:param title: The first field of the comment block. This field appears
centered at the top of the box.
:param text: The second filed of the comment block. This field appears
left-justifed at the bottom of the box.
:param newline: Boolean value to indicate whether the comment block should
end with a newline. Default is ``False``.
This banner can be injected into any templated file, for example:
.. code-block:: jinja
{{ salt['slsutil.banner'](width=120, commentchar='//') }}
The default banner:
.. code-block:: none
########################################################################
# #
# THIS FILE IS MANAGED BY SALT - DO NOT EDIT #
# #
# The contents of this file are managed by Salt. Any changes to this #
# file may be overwritten automatically and without warning. #
########################################################################
'''
if title is None:
title = 'THIS FILE IS MANAGED BY SALT - DO NOT EDIT'
if text is None:
text = ('The contents of this file are managed by Salt. '
'Any changes to this file may be overwritten '
'automatically and without warning')
# Set up some typesetting variables
lgutter = commentchar.strip() + ' '
rgutter = ' ' + commentchar.strip()
textwidth = width - len(lgutter) - len(rgutter)
border_line = commentchar + borderchar[:1] * (width - len(commentchar) * 2) + commentchar
spacer_line = commentchar + ' ' * (width - len(commentchar) * 2) + commentchar
wrapper = textwrap.TextWrapper(width=(width - len(lgutter) - len(rgutter)))
block = list()
# Create the banner
if blockstart is not None:
block.append(blockstart)
block.append(border_line)
block.append(spacer_line)
for line in wrapper.wrap(title):
block.append(lgutter + line.center(textwidth) + rgutter)
block.append(spacer_line)
for line in wrapper.wrap(text):
block.append(lgutter + line + ' ' * (textwidth - len(line)) + rgutter)
block.append(border_line)
if blockend is not None:
block.append(blockend)
# Convert list to multi-line string
result = os.linesep.join(block)
# Add a newline character to the end of the banner
if newline:
return result + os.linesep
return result
def boolstr(value, true='true', false='false'):
'''
Convert a boolean value into a string. This function is
intended to be used from within file templates to provide
an easy way to take boolean values stored in Pillars or
Grains, and write them out in the apprpriate syntax for
a particular file template.
:param value: The boolean value to be converted
:param true: The value to return if ``value`` is ``True``
:param false: The value to return if ``value`` is ``False``
In this example, a pillar named ``smtp:encrypted`` stores a boolean
value, but the template that uses that value needs ``yes`` or ``no``
to be written, based on the boolean value.
*Note: this is written on two lines for clarity. The same result
could be achieved in one line.*
.. code-block:: jinja
{% set encrypted = salt[pillar.get]('smtp:encrypted', false) %}
use_tls: {{ salt['slsutil.boolstr'](encrypted, 'yes', 'no') }}
Result (assuming the value is ``True``):
.. code-block:: none
use_tls: yes
'''
if value:
return true
return false
|
saltstack/salt
|
salt/modules/slsutil.py
|
merge_all
|
python
|
def merge_all(lst, strategy='smart', renderer='yaml', merge_lists=False):
'''
.. versionadded:: 2019.2.0
Merge a list of objects into each other in order
:type lst: Iterable
:param lst: List of objects to be merged.
:type strategy: String
:param strategy: Merge strategy. See utils.dictupdate.
:type renderer: String
:param renderer:
Renderer type. Used to determine strategy when strategy is 'smart'.
:type merge_lists: Bool
:param merge_lists: Defines whether to merge embedded object lists.
CLI Example:
.. code-block:: shell
$ salt-call --output=txt slsutil.merge_all '[{foo: Foo}, {foo: Bar}]'
local: {u'foo': u'Bar'}
'''
ret = {}
for obj in lst:
ret = salt.utils.dictupdate.merge(
ret, obj, strategy, renderer, merge_lists
)
return ret
|
.. versionadded:: 2019.2.0
Merge a list of objects into each other in order
:type lst: Iterable
:param lst: List of objects to be merged.
:type strategy: String
:param strategy: Merge strategy. See utils.dictupdate.
:type renderer: String
:param renderer:
Renderer type. Used to determine strategy when strategy is 'smart'.
:type merge_lists: Bool
:param merge_lists: Defines whether to merge embedded object lists.
CLI Example:
.. code-block:: shell
$ salt-call --output=txt slsutil.merge_all '[{foo: Foo}, {foo: Bar}]'
local: {u'foo': u'Bar'}
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/slsutil.py#L59-L92
|
[
"def merge(obj_a, obj_b, strategy='smart', renderer='yaml', merge_lists=False):\n if strategy == 'smart':\n if renderer.split('|')[-1] == 'yamlex' or renderer.startswith('yamlex_'):\n strategy = 'aggregate'\n else:\n strategy = 'recurse'\n\n if strategy == 'list':\n merged = merge_list(obj_a, obj_b)\n elif strategy == 'recurse':\n merged = merge_recurse(obj_a, obj_b, merge_lists)\n elif strategy == 'aggregate':\n #: level = 1 merge at least root data\n merged = merge_aggregate(obj_a, obj_b)\n elif strategy == 'overwrite':\n merged = merge_overwrite(obj_a, obj_b, merge_lists)\n elif strategy == 'none':\n # If we do not want to merge, there is only one pillar passed, so we can safely use the default recurse,\n # we just do not want to log an error\n merged = merge_recurse(obj_a, obj_b)\n else:\n log.warning(\n 'Unknown merging strategy \\'%s\\', fallback to recurse',\n strategy\n )\n merged = merge_recurse(obj_a, obj_b)\n\n return merged\n"
] |
# -*- coding: utf-8 -*-
'''
Utility functions for use with or in SLS files
'''
# Import Python libs
from __future__ import absolute_import, unicode_literals, print_function
import textwrap
import os
# Import Salt libs
import salt.exceptions
import salt.loader
import salt.template
import salt.utils.args
import salt.utils.dictupdate
def update(dest, upd, recursive_update=True, merge_lists=False):
'''
Merge ``upd`` recursively into ``dest``
If ``merge_lists=True``, will aggregate list object types instead of
replacing. This behavior is only activated when ``recursive_update=True``.
CLI Example:
.. code-block:: shell
salt '*' slsutil.update '{foo: Foo}' '{bar: Bar}'
'''
return salt.utils.dictupdate.update(dest, upd, recursive_update,
merge_lists)
def merge(obj_a, obj_b, strategy='smart', renderer='yaml', merge_lists=False):
'''
Merge a data structure into another by choosing a merge strategy
Strategies:
* aggregate
* list
* overwrite
* recurse
* smart
CLI Example:
.. code-block:: shell
salt '*' slsutil.merge '{foo: Foo}' '{bar: Bar}'
'''
return salt.utils.dictupdate.merge(obj_a, obj_b, strategy, renderer,
merge_lists)
def renderer(path=None, string=None, default_renderer='jinja|yaml', **kwargs):
'''
Parse a string or file through Salt's renderer system
.. versionchanged:: 2018.3.0
Add support for Salt fileserver URIs.
This is an open-ended function and can be used for a variety of tasks. It
makes use of Salt's "renderer pipes" system to run a string or file through
a pipe of any of the loaded renderer modules.
:param path: The path to a file on Salt's fileserver (any URIs supported by
:py:func:`cp.get_url <salt.modules.cp.get_url>`) or on the local file
system.
:param string: An inline string to be used as the file to send through the
renderer system. Note, not all renderer modules can work with strings;
the 'py' renderer requires a file, for example.
:param default_renderer: The renderer pipe to send the file through; this
is overridden by a "she-bang" at the top of the file.
:param kwargs: Keyword args to pass to Salt's compile_template() function.
Keep in mind the goal of each renderer when choosing a render-pipe; for
example, the Jinja renderer processes a text file and produces a string,
however the YAML renderer processes a text file and produces a data
structure.
One possible use is to allow writing "map files", as are commonly seen in
Salt formulas, but without tying the renderer of the map file to the
renderer used in the other sls files. In other words, a map file could use
the Python renderer and still be included and used by an sls file that uses
the default 'jinja|yaml' renderer.
For example, the two following map files produce identical results but one
is written using the normal 'jinja|yaml' and the other is using 'py':
.. code-block:: jinja
#!jinja|yaml
{% set apache = salt.grains.filter_by({
...normal jinja map file here...
}, merge=salt.pillar.get('apache:lookup')) %}
{{ apache | yaml() }}
.. code-block:: python
#!py
def run():
apache = __salt__.grains.filter_by({
...normal map here but as a python dict...
}, merge=__salt__.pillar.get('apache:lookup'))
return apache
Regardless of which of the above map files is used, it can be accessed from
any other sls file by calling this function. The following is a usage
example in Jinja:
.. code-block:: jinja
{% set apache = salt.slsutil.renderer('map.sls') %}
CLI Example:
.. code-block:: bash
salt '*' slsutil.renderer salt://path/to/file
salt '*' slsutil.renderer /path/to/file
salt '*' slsutil.renderer /path/to/file.jinja 'jinja'
salt '*' slsutil.renderer /path/to/file.sls 'jinja|yaml'
salt '*' slsutil.renderer string='Inline template! {{ saltenv }}'
salt '*' slsutil.renderer string='Hello, {{ name }}.' name='world'
'''
if not path and not string:
raise salt.exceptions.SaltInvocationError(
'Must pass either path or string')
renderers = salt.loader.render(__opts__, __salt__)
if path:
path_or_string = __salt__['cp.get_url'](path, saltenv=kwargs.get('saltenv', 'base'))
elif string:
path_or_string = ':string:'
kwargs['input_data'] = string
ret = salt.template.compile_template(
path_or_string,
renderers,
default_renderer,
__opts__['renderer_blacklist'],
__opts__['renderer_whitelist'],
**kwargs
)
return ret.read() if __utils__['stringio.is_readable'](ret) else ret
def _get_serialize_fn(serializer, fn_name):
serializers = salt.loader.serializers(__opts__)
fns = getattr(serializers, serializer, None)
fn = getattr(fns, fn_name, None)
if not fns:
raise salt.exceptions.CommandExecutionError(
"Serializer '{0}' not found.".format(serializer))
if not fn:
raise salt.exceptions.CommandExecutionError(
"Serializer '{0}' does not implement {1}.".format(serializer,
fn_name))
return fn
def serialize(serializer, obj, **mod_kwargs):
'''
Serialize a Python object using a :py:mod:`serializer module
<salt.serializers>`
CLI Example:
.. code-block:: bash
salt '*' --no-parse=obj slsutil.serialize 'json' obj="{'foo': 'Foo!'}
Jinja Example:
.. code-block:: jinja
{% set json_string = salt.slsutil.serialize('json',
{'foo': 'Foo!'}) %}
'''
kwargs = salt.utils.args.clean_kwargs(**mod_kwargs)
return _get_serialize_fn(serializer, 'serialize')(obj, **kwargs)
def deserialize(serializer, stream_or_string, **mod_kwargs):
'''
Deserialize a Python object using a :py:mod:`serializer module
<salt.serializers>`
CLI Example:
.. code-block:: bash
salt '*' slsutil.deserialize 'json' '{"foo": "Foo!"}'
salt '*' --no-parse=stream_or_string slsutil.deserialize 'json' \\
stream_or_string='{"foo": "Foo!"}'
Jinja Example:
.. code-block:: jinja
{% set python_object = salt.slsutil.deserialize('json',
'{"foo": "Foo!"}') %}
'''
kwargs = salt.utils.args.clean_kwargs(**mod_kwargs)
return _get_serialize_fn(serializer, 'deserialize')(stream_or_string,
**kwargs)
def banner(width=72, commentchar='#', borderchar='#', blockstart=None, blockend=None,
title=None, text=None, newline=False):
'''
Create a standardized comment block to include in a templated file.
A common technique in configuration management is to include a comment
block in managed files, warning users not to modify the file. This
function simplifies and standardizes those comment blocks.
:param width: The width, in characters, of the banner. Default is 72.
:param commentchar: The character to be used in the starting position of
each line. This value should be set to a valid line comment character
for the syntax of the file in which the banner is being inserted.
Multiple character sequences, like '//' are supported.
If the file's syntax does not support line comments (such as XML),
use the ``blockstart`` and ``blockend`` options.
:param borderchar: The character to use in the top and bottom border of
the comment box. Must be a single character.
:param blockstart: The character sequence to use at the beginning of a
block comment. Should be used in conjunction with ``blockend``
:param blockend: The character sequence to use at the end of a
block comment. Should be used in conjunction with ``blockstart``
:param title: The first field of the comment block. This field appears
centered at the top of the box.
:param text: The second filed of the comment block. This field appears
left-justifed at the bottom of the box.
:param newline: Boolean value to indicate whether the comment block should
end with a newline. Default is ``False``.
This banner can be injected into any templated file, for example:
.. code-block:: jinja
{{ salt['slsutil.banner'](width=120, commentchar='//') }}
The default banner:
.. code-block:: none
########################################################################
# #
# THIS FILE IS MANAGED BY SALT - DO NOT EDIT #
# #
# The contents of this file are managed by Salt. Any changes to this #
# file may be overwritten automatically and without warning. #
########################################################################
'''
if title is None:
title = 'THIS FILE IS MANAGED BY SALT - DO NOT EDIT'
if text is None:
text = ('The contents of this file are managed by Salt. '
'Any changes to this file may be overwritten '
'automatically and without warning')
# Set up some typesetting variables
lgutter = commentchar.strip() + ' '
rgutter = ' ' + commentchar.strip()
textwidth = width - len(lgutter) - len(rgutter)
border_line = commentchar + borderchar[:1] * (width - len(commentchar) * 2) + commentchar
spacer_line = commentchar + ' ' * (width - len(commentchar) * 2) + commentchar
wrapper = textwrap.TextWrapper(width=(width - len(lgutter) - len(rgutter)))
block = list()
# Create the banner
if blockstart is not None:
block.append(blockstart)
block.append(border_line)
block.append(spacer_line)
for line in wrapper.wrap(title):
block.append(lgutter + line.center(textwidth) + rgutter)
block.append(spacer_line)
for line in wrapper.wrap(text):
block.append(lgutter + line + ' ' * (textwidth - len(line)) + rgutter)
block.append(border_line)
if blockend is not None:
block.append(blockend)
# Convert list to multi-line string
result = os.linesep.join(block)
# Add a newline character to the end of the banner
if newline:
return result + os.linesep
return result
def boolstr(value, true='true', false='false'):
'''
Convert a boolean value into a string. This function is
intended to be used from within file templates to provide
an easy way to take boolean values stored in Pillars or
Grains, and write them out in the apprpriate syntax for
a particular file template.
:param value: The boolean value to be converted
:param true: The value to return if ``value`` is ``True``
:param false: The value to return if ``value`` is ``False``
In this example, a pillar named ``smtp:encrypted`` stores a boolean
value, but the template that uses that value needs ``yes`` or ``no``
to be written, based on the boolean value.
*Note: this is written on two lines for clarity. The same result
could be achieved in one line.*
.. code-block:: jinja
{% set encrypted = salt[pillar.get]('smtp:encrypted', false) %}
use_tls: {{ salt['slsutil.boolstr'](encrypted, 'yes', 'no') }}
Result (assuming the value is ``True``):
.. code-block:: none
use_tls: yes
'''
if value:
return true
return false
|
saltstack/salt
|
salt/modules/slsutil.py
|
renderer
|
python
|
def renderer(path=None, string=None, default_renderer='jinja|yaml', **kwargs):
'''
Parse a string or file through Salt's renderer system
.. versionchanged:: 2018.3.0
Add support for Salt fileserver URIs.
This is an open-ended function and can be used for a variety of tasks. It
makes use of Salt's "renderer pipes" system to run a string or file through
a pipe of any of the loaded renderer modules.
:param path: The path to a file on Salt's fileserver (any URIs supported by
:py:func:`cp.get_url <salt.modules.cp.get_url>`) or on the local file
system.
:param string: An inline string to be used as the file to send through the
renderer system. Note, not all renderer modules can work with strings;
the 'py' renderer requires a file, for example.
:param default_renderer: The renderer pipe to send the file through; this
is overridden by a "she-bang" at the top of the file.
:param kwargs: Keyword args to pass to Salt's compile_template() function.
Keep in mind the goal of each renderer when choosing a render-pipe; for
example, the Jinja renderer processes a text file and produces a string,
however the YAML renderer processes a text file and produces a data
structure.
One possible use is to allow writing "map files", as are commonly seen in
Salt formulas, but without tying the renderer of the map file to the
renderer used in the other sls files. In other words, a map file could use
the Python renderer and still be included and used by an sls file that uses
the default 'jinja|yaml' renderer.
For example, the two following map files produce identical results but one
is written using the normal 'jinja|yaml' and the other is using 'py':
.. code-block:: jinja
#!jinja|yaml
{% set apache = salt.grains.filter_by({
...normal jinja map file here...
}, merge=salt.pillar.get('apache:lookup')) %}
{{ apache | yaml() }}
.. code-block:: python
#!py
def run():
apache = __salt__.grains.filter_by({
...normal map here but as a python dict...
}, merge=__salt__.pillar.get('apache:lookup'))
return apache
Regardless of which of the above map files is used, it can be accessed from
any other sls file by calling this function. The following is a usage
example in Jinja:
.. code-block:: jinja
{% set apache = salt.slsutil.renderer('map.sls') %}
CLI Example:
.. code-block:: bash
salt '*' slsutil.renderer salt://path/to/file
salt '*' slsutil.renderer /path/to/file
salt '*' slsutil.renderer /path/to/file.jinja 'jinja'
salt '*' slsutil.renderer /path/to/file.sls 'jinja|yaml'
salt '*' slsutil.renderer string='Inline template! {{ saltenv }}'
salt '*' slsutil.renderer string='Hello, {{ name }}.' name='world'
'''
if not path and not string:
raise salt.exceptions.SaltInvocationError(
'Must pass either path or string')
renderers = salt.loader.render(__opts__, __salt__)
if path:
path_or_string = __salt__['cp.get_url'](path, saltenv=kwargs.get('saltenv', 'base'))
elif string:
path_or_string = ':string:'
kwargs['input_data'] = string
ret = salt.template.compile_template(
path_or_string,
renderers,
default_renderer,
__opts__['renderer_blacklist'],
__opts__['renderer_whitelist'],
**kwargs
)
return ret.read() if __utils__['stringio.is_readable'](ret) else ret
|
Parse a string or file through Salt's renderer system
.. versionchanged:: 2018.3.0
Add support for Salt fileserver URIs.
This is an open-ended function and can be used for a variety of tasks. It
makes use of Salt's "renderer pipes" system to run a string or file through
a pipe of any of the loaded renderer modules.
:param path: The path to a file on Salt's fileserver (any URIs supported by
:py:func:`cp.get_url <salt.modules.cp.get_url>`) or on the local file
system.
:param string: An inline string to be used as the file to send through the
renderer system. Note, not all renderer modules can work with strings;
the 'py' renderer requires a file, for example.
:param default_renderer: The renderer pipe to send the file through; this
is overridden by a "she-bang" at the top of the file.
:param kwargs: Keyword args to pass to Salt's compile_template() function.
Keep in mind the goal of each renderer when choosing a render-pipe; for
example, the Jinja renderer processes a text file and produces a string,
however the YAML renderer processes a text file and produces a data
structure.
One possible use is to allow writing "map files", as are commonly seen in
Salt formulas, but without tying the renderer of the map file to the
renderer used in the other sls files. In other words, a map file could use
the Python renderer and still be included and used by an sls file that uses
the default 'jinja|yaml' renderer.
For example, the two following map files produce identical results but one
is written using the normal 'jinja|yaml' and the other is using 'py':
.. code-block:: jinja
#!jinja|yaml
{% set apache = salt.grains.filter_by({
...normal jinja map file here...
}, merge=salt.pillar.get('apache:lookup')) %}
{{ apache | yaml() }}
.. code-block:: python
#!py
def run():
apache = __salt__.grains.filter_by({
...normal map here but as a python dict...
}, merge=__salt__.pillar.get('apache:lookup'))
return apache
Regardless of which of the above map files is used, it can be accessed from
any other sls file by calling this function. The following is a usage
example in Jinja:
.. code-block:: jinja
{% set apache = salt.slsutil.renderer('map.sls') %}
CLI Example:
.. code-block:: bash
salt '*' slsutil.renderer salt://path/to/file
salt '*' slsutil.renderer /path/to/file
salt '*' slsutil.renderer /path/to/file.jinja 'jinja'
salt '*' slsutil.renderer /path/to/file.sls 'jinja|yaml'
salt '*' slsutil.renderer string='Inline template! {{ saltenv }}'
salt '*' slsutil.renderer string='Hello, {{ name }}.' name='world'
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/slsutil.py#L95-L186
|
[
"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"
] |
# -*- coding: utf-8 -*-
'''
Utility functions for use with or in SLS files
'''
# Import Python libs
from __future__ import absolute_import, unicode_literals, print_function
import textwrap
import os
# Import Salt libs
import salt.exceptions
import salt.loader
import salt.template
import salt.utils.args
import salt.utils.dictupdate
def update(dest, upd, recursive_update=True, merge_lists=False):
'''
Merge ``upd`` recursively into ``dest``
If ``merge_lists=True``, will aggregate list object types instead of
replacing. This behavior is only activated when ``recursive_update=True``.
CLI Example:
.. code-block:: shell
salt '*' slsutil.update '{foo: Foo}' '{bar: Bar}'
'''
return salt.utils.dictupdate.update(dest, upd, recursive_update,
merge_lists)
def merge(obj_a, obj_b, strategy='smart', renderer='yaml', merge_lists=False):
'''
Merge a data structure into another by choosing a merge strategy
Strategies:
* aggregate
* list
* overwrite
* recurse
* smart
CLI Example:
.. code-block:: shell
salt '*' slsutil.merge '{foo: Foo}' '{bar: Bar}'
'''
return salt.utils.dictupdate.merge(obj_a, obj_b, strategy, renderer,
merge_lists)
def merge_all(lst, strategy='smart', renderer='yaml', merge_lists=False):
'''
.. versionadded:: 2019.2.0
Merge a list of objects into each other in order
:type lst: Iterable
:param lst: List of objects to be merged.
:type strategy: String
:param strategy: Merge strategy. See utils.dictupdate.
:type renderer: String
:param renderer:
Renderer type. Used to determine strategy when strategy is 'smart'.
:type merge_lists: Bool
:param merge_lists: Defines whether to merge embedded object lists.
CLI Example:
.. code-block:: shell
$ salt-call --output=txt slsutil.merge_all '[{foo: Foo}, {foo: Bar}]'
local: {u'foo': u'Bar'}
'''
ret = {}
for obj in lst:
ret = salt.utils.dictupdate.merge(
ret, obj, strategy, renderer, merge_lists
)
return ret
def _get_serialize_fn(serializer, fn_name):
serializers = salt.loader.serializers(__opts__)
fns = getattr(serializers, serializer, None)
fn = getattr(fns, fn_name, None)
if not fns:
raise salt.exceptions.CommandExecutionError(
"Serializer '{0}' not found.".format(serializer))
if not fn:
raise salt.exceptions.CommandExecutionError(
"Serializer '{0}' does not implement {1}.".format(serializer,
fn_name))
return fn
def serialize(serializer, obj, **mod_kwargs):
'''
Serialize a Python object using a :py:mod:`serializer module
<salt.serializers>`
CLI Example:
.. code-block:: bash
salt '*' --no-parse=obj slsutil.serialize 'json' obj="{'foo': 'Foo!'}
Jinja Example:
.. code-block:: jinja
{% set json_string = salt.slsutil.serialize('json',
{'foo': 'Foo!'}) %}
'''
kwargs = salt.utils.args.clean_kwargs(**mod_kwargs)
return _get_serialize_fn(serializer, 'serialize')(obj, **kwargs)
def deserialize(serializer, stream_or_string, **mod_kwargs):
'''
Deserialize a Python object using a :py:mod:`serializer module
<salt.serializers>`
CLI Example:
.. code-block:: bash
salt '*' slsutil.deserialize 'json' '{"foo": "Foo!"}'
salt '*' --no-parse=stream_or_string slsutil.deserialize 'json' \\
stream_or_string='{"foo": "Foo!"}'
Jinja Example:
.. code-block:: jinja
{% set python_object = salt.slsutil.deserialize('json',
'{"foo": "Foo!"}') %}
'''
kwargs = salt.utils.args.clean_kwargs(**mod_kwargs)
return _get_serialize_fn(serializer, 'deserialize')(stream_or_string,
**kwargs)
def banner(width=72, commentchar='#', borderchar='#', blockstart=None, blockend=None,
title=None, text=None, newline=False):
'''
Create a standardized comment block to include in a templated file.
A common technique in configuration management is to include a comment
block in managed files, warning users not to modify the file. This
function simplifies and standardizes those comment blocks.
:param width: The width, in characters, of the banner. Default is 72.
:param commentchar: The character to be used in the starting position of
each line. This value should be set to a valid line comment character
for the syntax of the file in which the banner is being inserted.
Multiple character sequences, like '//' are supported.
If the file's syntax does not support line comments (such as XML),
use the ``blockstart`` and ``blockend`` options.
:param borderchar: The character to use in the top and bottom border of
the comment box. Must be a single character.
:param blockstart: The character sequence to use at the beginning of a
block comment. Should be used in conjunction with ``blockend``
:param blockend: The character sequence to use at the end of a
block comment. Should be used in conjunction with ``blockstart``
:param title: The first field of the comment block. This field appears
centered at the top of the box.
:param text: The second filed of the comment block. This field appears
left-justifed at the bottom of the box.
:param newline: Boolean value to indicate whether the comment block should
end with a newline. Default is ``False``.
This banner can be injected into any templated file, for example:
.. code-block:: jinja
{{ salt['slsutil.banner'](width=120, commentchar='//') }}
The default banner:
.. code-block:: none
########################################################################
# #
# THIS FILE IS MANAGED BY SALT - DO NOT EDIT #
# #
# The contents of this file are managed by Salt. Any changes to this #
# file may be overwritten automatically and without warning. #
########################################################################
'''
if title is None:
title = 'THIS FILE IS MANAGED BY SALT - DO NOT EDIT'
if text is None:
text = ('The contents of this file are managed by Salt. '
'Any changes to this file may be overwritten '
'automatically and without warning')
# Set up some typesetting variables
lgutter = commentchar.strip() + ' '
rgutter = ' ' + commentchar.strip()
textwidth = width - len(lgutter) - len(rgutter)
border_line = commentchar + borderchar[:1] * (width - len(commentchar) * 2) + commentchar
spacer_line = commentchar + ' ' * (width - len(commentchar) * 2) + commentchar
wrapper = textwrap.TextWrapper(width=(width - len(lgutter) - len(rgutter)))
block = list()
# Create the banner
if blockstart is not None:
block.append(blockstart)
block.append(border_line)
block.append(spacer_line)
for line in wrapper.wrap(title):
block.append(lgutter + line.center(textwidth) + rgutter)
block.append(spacer_line)
for line in wrapper.wrap(text):
block.append(lgutter + line + ' ' * (textwidth - len(line)) + rgutter)
block.append(border_line)
if blockend is not None:
block.append(blockend)
# Convert list to multi-line string
result = os.linesep.join(block)
# Add a newline character to the end of the banner
if newline:
return result + os.linesep
return result
def boolstr(value, true='true', false='false'):
'''
Convert a boolean value into a string. This function is
intended to be used from within file templates to provide
an easy way to take boolean values stored in Pillars or
Grains, and write them out in the apprpriate syntax for
a particular file template.
:param value: The boolean value to be converted
:param true: The value to return if ``value`` is ``True``
:param false: The value to return if ``value`` is ``False``
In this example, a pillar named ``smtp:encrypted`` stores a boolean
value, but the template that uses that value needs ``yes`` or ``no``
to be written, based on the boolean value.
*Note: this is written on two lines for clarity. The same result
could be achieved in one line.*
.. code-block:: jinja
{% set encrypted = salt[pillar.get]('smtp:encrypted', false) %}
use_tls: {{ salt['slsutil.boolstr'](encrypted, 'yes', 'no') }}
Result (assuming the value is ``True``):
.. code-block:: none
use_tls: yes
'''
if value:
return true
return false
|
saltstack/salt
|
salt/modules/slsutil.py
|
serialize
|
python
|
def serialize(serializer, obj, **mod_kwargs):
'''
Serialize a Python object using a :py:mod:`serializer module
<salt.serializers>`
CLI Example:
.. code-block:: bash
salt '*' --no-parse=obj slsutil.serialize 'json' obj="{'foo': 'Foo!'}
Jinja Example:
.. code-block:: jinja
{% set json_string = salt.slsutil.serialize('json',
{'foo': 'Foo!'}) %}
'''
kwargs = salt.utils.args.clean_kwargs(**mod_kwargs)
return _get_serialize_fn(serializer, 'serialize')(obj, **kwargs)
|
Serialize a Python object using a :py:mod:`serializer module
<salt.serializers>`
CLI Example:
.. code-block:: bash
salt '*' --no-parse=obj slsutil.serialize 'json' obj="{'foo': 'Foo!'}
Jinja Example:
.. code-block:: jinja
{% set json_string = salt.slsutil.serialize('json',
{'foo': 'Foo!'}) %}
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/slsutil.py#L206-L225
|
[
"def clean_kwargs(**kwargs):\n '''\n Return a dict without any of the __pub* keys (or any other keys starting\n with a dunder) from the kwargs dict passed into the execution module\n functions. These keys are useful for tracking what was used to invoke\n the function call, but they may not be desirable to have if passing the\n kwargs forward wholesale.\n\n Usage example:\n\n .. code-block:: python\n\n kwargs = __utils__['args.clean_kwargs'](**kwargs)\n '''\n ret = {}\n for key, val in six.iteritems(kwargs):\n if not key.startswith('__'):\n ret[key] = val\n return ret\n",
"def _get_serialize_fn(serializer, fn_name):\n serializers = salt.loader.serializers(__opts__)\n fns = getattr(serializers, serializer, None)\n fn = getattr(fns, fn_name, None)\n\n if not fns:\n raise salt.exceptions.CommandExecutionError(\n \"Serializer '{0}' not found.\".format(serializer))\n\n if not fn:\n raise salt.exceptions.CommandExecutionError(\n \"Serializer '{0}' does not implement {1}.\".format(serializer,\n fn_name))\n\n return fn\n"
] |
# -*- coding: utf-8 -*-
'''
Utility functions for use with or in SLS files
'''
# Import Python libs
from __future__ import absolute_import, unicode_literals, print_function
import textwrap
import os
# Import Salt libs
import salt.exceptions
import salt.loader
import salt.template
import salt.utils.args
import salt.utils.dictupdate
def update(dest, upd, recursive_update=True, merge_lists=False):
'''
Merge ``upd`` recursively into ``dest``
If ``merge_lists=True``, will aggregate list object types instead of
replacing. This behavior is only activated when ``recursive_update=True``.
CLI Example:
.. code-block:: shell
salt '*' slsutil.update '{foo: Foo}' '{bar: Bar}'
'''
return salt.utils.dictupdate.update(dest, upd, recursive_update,
merge_lists)
def merge(obj_a, obj_b, strategy='smart', renderer='yaml', merge_lists=False):
'''
Merge a data structure into another by choosing a merge strategy
Strategies:
* aggregate
* list
* overwrite
* recurse
* smart
CLI Example:
.. code-block:: shell
salt '*' slsutil.merge '{foo: Foo}' '{bar: Bar}'
'''
return salt.utils.dictupdate.merge(obj_a, obj_b, strategy, renderer,
merge_lists)
def merge_all(lst, strategy='smart', renderer='yaml', merge_lists=False):
'''
.. versionadded:: 2019.2.0
Merge a list of objects into each other in order
:type lst: Iterable
:param lst: List of objects to be merged.
:type strategy: String
:param strategy: Merge strategy. See utils.dictupdate.
:type renderer: String
:param renderer:
Renderer type. Used to determine strategy when strategy is 'smart'.
:type merge_lists: Bool
:param merge_lists: Defines whether to merge embedded object lists.
CLI Example:
.. code-block:: shell
$ salt-call --output=txt slsutil.merge_all '[{foo: Foo}, {foo: Bar}]'
local: {u'foo': u'Bar'}
'''
ret = {}
for obj in lst:
ret = salt.utils.dictupdate.merge(
ret, obj, strategy, renderer, merge_lists
)
return ret
def renderer(path=None, string=None, default_renderer='jinja|yaml', **kwargs):
'''
Parse a string or file through Salt's renderer system
.. versionchanged:: 2018.3.0
Add support for Salt fileserver URIs.
This is an open-ended function and can be used for a variety of tasks. It
makes use of Salt's "renderer pipes" system to run a string or file through
a pipe of any of the loaded renderer modules.
:param path: The path to a file on Salt's fileserver (any URIs supported by
:py:func:`cp.get_url <salt.modules.cp.get_url>`) or on the local file
system.
:param string: An inline string to be used as the file to send through the
renderer system. Note, not all renderer modules can work with strings;
the 'py' renderer requires a file, for example.
:param default_renderer: The renderer pipe to send the file through; this
is overridden by a "she-bang" at the top of the file.
:param kwargs: Keyword args to pass to Salt's compile_template() function.
Keep in mind the goal of each renderer when choosing a render-pipe; for
example, the Jinja renderer processes a text file and produces a string,
however the YAML renderer processes a text file and produces a data
structure.
One possible use is to allow writing "map files", as are commonly seen in
Salt formulas, but without tying the renderer of the map file to the
renderer used in the other sls files. In other words, a map file could use
the Python renderer and still be included and used by an sls file that uses
the default 'jinja|yaml' renderer.
For example, the two following map files produce identical results but one
is written using the normal 'jinja|yaml' and the other is using 'py':
.. code-block:: jinja
#!jinja|yaml
{% set apache = salt.grains.filter_by({
...normal jinja map file here...
}, merge=salt.pillar.get('apache:lookup')) %}
{{ apache | yaml() }}
.. code-block:: python
#!py
def run():
apache = __salt__.grains.filter_by({
...normal map here but as a python dict...
}, merge=__salt__.pillar.get('apache:lookup'))
return apache
Regardless of which of the above map files is used, it can be accessed from
any other sls file by calling this function. The following is a usage
example in Jinja:
.. code-block:: jinja
{% set apache = salt.slsutil.renderer('map.sls') %}
CLI Example:
.. code-block:: bash
salt '*' slsutil.renderer salt://path/to/file
salt '*' slsutil.renderer /path/to/file
salt '*' slsutil.renderer /path/to/file.jinja 'jinja'
salt '*' slsutil.renderer /path/to/file.sls 'jinja|yaml'
salt '*' slsutil.renderer string='Inline template! {{ saltenv }}'
salt '*' slsutil.renderer string='Hello, {{ name }}.' name='world'
'''
if not path and not string:
raise salt.exceptions.SaltInvocationError(
'Must pass either path or string')
renderers = salt.loader.render(__opts__, __salt__)
if path:
path_or_string = __salt__['cp.get_url'](path, saltenv=kwargs.get('saltenv', 'base'))
elif string:
path_or_string = ':string:'
kwargs['input_data'] = string
ret = salt.template.compile_template(
path_or_string,
renderers,
default_renderer,
__opts__['renderer_blacklist'],
__opts__['renderer_whitelist'],
**kwargs
)
return ret.read() if __utils__['stringio.is_readable'](ret) else ret
def _get_serialize_fn(serializer, fn_name):
serializers = salt.loader.serializers(__opts__)
fns = getattr(serializers, serializer, None)
fn = getattr(fns, fn_name, None)
if not fns:
raise salt.exceptions.CommandExecutionError(
"Serializer '{0}' not found.".format(serializer))
if not fn:
raise salt.exceptions.CommandExecutionError(
"Serializer '{0}' does not implement {1}.".format(serializer,
fn_name))
return fn
def deserialize(serializer, stream_or_string, **mod_kwargs):
'''
Deserialize a Python object using a :py:mod:`serializer module
<salt.serializers>`
CLI Example:
.. code-block:: bash
salt '*' slsutil.deserialize 'json' '{"foo": "Foo!"}'
salt '*' --no-parse=stream_or_string slsutil.deserialize 'json' \\
stream_or_string='{"foo": "Foo!"}'
Jinja Example:
.. code-block:: jinja
{% set python_object = salt.slsutil.deserialize('json',
'{"foo": "Foo!"}') %}
'''
kwargs = salt.utils.args.clean_kwargs(**mod_kwargs)
return _get_serialize_fn(serializer, 'deserialize')(stream_or_string,
**kwargs)
def banner(width=72, commentchar='#', borderchar='#', blockstart=None, blockend=None,
title=None, text=None, newline=False):
'''
Create a standardized comment block to include in a templated file.
A common technique in configuration management is to include a comment
block in managed files, warning users not to modify the file. This
function simplifies and standardizes those comment blocks.
:param width: The width, in characters, of the banner. Default is 72.
:param commentchar: The character to be used in the starting position of
each line. This value should be set to a valid line comment character
for the syntax of the file in which the banner is being inserted.
Multiple character sequences, like '//' are supported.
If the file's syntax does not support line comments (such as XML),
use the ``blockstart`` and ``blockend`` options.
:param borderchar: The character to use in the top and bottom border of
the comment box. Must be a single character.
:param blockstart: The character sequence to use at the beginning of a
block comment. Should be used in conjunction with ``blockend``
:param blockend: The character sequence to use at the end of a
block comment. Should be used in conjunction with ``blockstart``
:param title: The first field of the comment block. This field appears
centered at the top of the box.
:param text: The second filed of the comment block. This field appears
left-justifed at the bottom of the box.
:param newline: Boolean value to indicate whether the comment block should
end with a newline. Default is ``False``.
This banner can be injected into any templated file, for example:
.. code-block:: jinja
{{ salt['slsutil.banner'](width=120, commentchar='//') }}
The default banner:
.. code-block:: none
########################################################################
# #
# THIS FILE IS MANAGED BY SALT - DO NOT EDIT #
# #
# The contents of this file are managed by Salt. Any changes to this #
# file may be overwritten automatically and without warning. #
########################################################################
'''
if title is None:
title = 'THIS FILE IS MANAGED BY SALT - DO NOT EDIT'
if text is None:
text = ('The contents of this file are managed by Salt. '
'Any changes to this file may be overwritten '
'automatically and without warning')
# Set up some typesetting variables
lgutter = commentchar.strip() + ' '
rgutter = ' ' + commentchar.strip()
textwidth = width - len(lgutter) - len(rgutter)
border_line = commentchar + borderchar[:1] * (width - len(commentchar) * 2) + commentchar
spacer_line = commentchar + ' ' * (width - len(commentchar) * 2) + commentchar
wrapper = textwrap.TextWrapper(width=(width - len(lgutter) - len(rgutter)))
block = list()
# Create the banner
if blockstart is not None:
block.append(blockstart)
block.append(border_line)
block.append(spacer_line)
for line in wrapper.wrap(title):
block.append(lgutter + line.center(textwidth) + rgutter)
block.append(spacer_line)
for line in wrapper.wrap(text):
block.append(lgutter + line + ' ' * (textwidth - len(line)) + rgutter)
block.append(border_line)
if blockend is not None:
block.append(blockend)
# Convert list to multi-line string
result = os.linesep.join(block)
# Add a newline character to the end of the banner
if newline:
return result + os.linesep
return result
def boolstr(value, true='true', false='false'):
'''
Convert a boolean value into a string. This function is
intended to be used from within file templates to provide
an easy way to take boolean values stored in Pillars or
Grains, and write them out in the apprpriate syntax for
a particular file template.
:param value: The boolean value to be converted
:param true: The value to return if ``value`` is ``True``
:param false: The value to return if ``value`` is ``False``
In this example, a pillar named ``smtp:encrypted`` stores a boolean
value, but the template that uses that value needs ``yes`` or ``no``
to be written, based on the boolean value.
*Note: this is written on two lines for clarity. The same result
could be achieved in one line.*
.. code-block:: jinja
{% set encrypted = salt[pillar.get]('smtp:encrypted', false) %}
use_tls: {{ salt['slsutil.boolstr'](encrypted, 'yes', 'no') }}
Result (assuming the value is ``True``):
.. code-block:: none
use_tls: yes
'''
if value:
return true
return false
|
saltstack/salt
|
salt/modules/slsutil.py
|
deserialize
|
python
|
def deserialize(serializer, stream_or_string, **mod_kwargs):
'''
Deserialize a Python object using a :py:mod:`serializer module
<salt.serializers>`
CLI Example:
.. code-block:: bash
salt '*' slsutil.deserialize 'json' '{"foo": "Foo!"}'
salt '*' --no-parse=stream_or_string slsutil.deserialize 'json' \\
stream_or_string='{"foo": "Foo!"}'
Jinja Example:
.. code-block:: jinja
{% set python_object = salt.slsutil.deserialize('json',
'{"foo": "Foo!"}') %}
'''
kwargs = salt.utils.args.clean_kwargs(**mod_kwargs)
return _get_serialize_fn(serializer, 'deserialize')(stream_or_string,
**kwargs)
|
Deserialize a Python object using a :py:mod:`serializer module
<salt.serializers>`
CLI Example:
.. code-block:: bash
salt '*' slsutil.deserialize 'json' '{"foo": "Foo!"}'
salt '*' --no-parse=stream_or_string slsutil.deserialize 'json' \\
stream_or_string='{"foo": "Foo!"}'
Jinja Example:
.. code-block:: jinja
{% set python_object = salt.slsutil.deserialize('json',
'{"foo": "Foo!"}') %}
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/slsutil.py#L228-L250
|
[
"def clean_kwargs(**kwargs):\n '''\n Return a dict without any of the __pub* keys (or any other keys starting\n with a dunder) from the kwargs dict passed into the execution module\n functions. These keys are useful for tracking what was used to invoke\n the function call, but they may not be desirable to have if passing the\n kwargs forward wholesale.\n\n Usage example:\n\n .. code-block:: python\n\n kwargs = __utils__['args.clean_kwargs'](**kwargs)\n '''\n ret = {}\n for key, val in six.iteritems(kwargs):\n if not key.startswith('__'):\n ret[key] = val\n return ret\n",
"def _get_serialize_fn(serializer, fn_name):\n serializers = salt.loader.serializers(__opts__)\n fns = getattr(serializers, serializer, None)\n fn = getattr(fns, fn_name, None)\n\n if not fns:\n raise salt.exceptions.CommandExecutionError(\n \"Serializer '{0}' not found.\".format(serializer))\n\n if not fn:\n raise salt.exceptions.CommandExecutionError(\n \"Serializer '{0}' does not implement {1}.\".format(serializer,\n fn_name))\n\n return fn\n"
] |
# -*- coding: utf-8 -*-
'''
Utility functions for use with or in SLS files
'''
# Import Python libs
from __future__ import absolute_import, unicode_literals, print_function
import textwrap
import os
# Import Salt libs
import salt.exceptions
import salt.loader
import salt.template
import salt.utils.args
import salt.utils.dictupdate
def update(dest, upd, recursive_update=True, merge_lists=False):
'''
Merge ``upd`` recursively into ``dest``
If ``merge_lists=True``, will aggregate list object types instead of
replacing. This behavior is only activated when ``recursive_update=True``.
CLI Example:
.. code-block:: shell
salt '*' slsutil.update '{foo: Foo}' '{bar: Bar}'
'''
return salt.utils.dictupdate.update(dest, upd, recursive_update,
merge_lists)
def merge(obj_a, obj_b, strategy='smart', renderer='yaml', merge_lists=False):
'''
Merge a data structure into another by choosing a merge strategy
Strategies:
* aggregate
* list
* overwrite
* recurse
* smart
CLI Example:
.. code-block:: shell
salt '*' slsutil.merge '{foo: Foo}' '{bar: Bar}'
'''
return salt.utils.dictupdate.merge(obj_a, obj_b, strategy, renderer,
merge_lists)
def merge_all(lst, strategy='smart', renderer='yaml', merge_lists=False):
'''
.. versionadded:: 2019.2.0
Merge a list of objects into each other in order
:type lst: Iterable
:param lst: List of objects to be merged.
:type strategy: String
:param strategy: Merge strategy. See utils.dictupdate.
:type renderer: String
:param renderer:
Renderer type. Used to determine strategy when strategy is 'smart'.
:type merge_lists: Bool
:param merge_lists: Defines whether to merge embedded object lists.
CLI Example:
.. code-block:: shell
$ salt-call --output=txt slsutil.merge_all '[{foo: Foo}, {foo: Bar}]'
local: {u'foo': u'Bar'}
'''
ret = {}
for obj in lst:
ret = salt.utils.dictupdate.merge(
ret, obj, strategy, renderer, merge_lists
)
return ret
def renderer(path=None, string=None, default_renderer='jinja|yaml', **kwargs):
'''
Parse a string or file through Salt's renderer system
.. versionchanged:: 2018.3.0
Add support for Salt fileserver URIs.
This is an open-ended function and can be used for a variety of tasks. It
makes use of Salt's "renderer pipes" system to run a string or file through
a pipe of any of the loaded renderer modules.
:param path: The path to a file on Salt's fileserver (any URIs supported by
:py:func:`cp.get_url <salt.modules.cp.get_url>`) or on the local file
system.
:param string: An inline string to be used as the file to send through the
renderer system. Note, not all renderer modules can work with strings;
the 'py' renderer requires a file, for example.
:param default_renderer: The renderer pipe to send the file through; this
is overridden by a "she-bang" at the top of the file.
:param kwargs: Keyword args to pass to Salt's compile_template() function.
Keep in mind the goal of each renderer when choosing a render-pipe; for
example, the Jinja renderer processes a text file and produces a string,
however the YAML renderer processes a text file and produces a data
structure.
One possible use is to allow writing "map files", as are commonly seen in
Salt formulas, but without tying the renderer of the map file to the
renderer used in the other sls files. In other words, a map file could use
the Python renderer and still be included and used by an sls file that uses
the default 'jinja|yaml' renderer.
For example, the two following map files produce identical results but one
is written using the normal 'jinja|yaml' and the other is using 'py':
.. code-block:: jinja
#!jinja|yaml
{% set apache = salt.grains.filter_by({
...normal jinja map file here...
}, merge=salt.pillar.get('apache:lookup')) %}
{{ apache | yaml() }}
.. code-block:: python
#!py
def run():
apache = __salt__.grains.filter_by({
...normal map here but as a python dict...
}, merge=__salt__.pillar.get('apache:lookup'))
return apache
Regardless of which of the above map files is used, it can be accessed from
any other sls file by calling this function. The following is a usage
example in Jinja:
.. code-block:: jinja
{% set apache = salt.slsutil.renderer('map.sls') %}
CLI Example:
.. code-block:: bash
salt '*' slsutil.renderer salt://path/to/file
salt '*' slsutil.renderer /path/to/file
salt '*' slsutil.renderer /path/to/file.jinja 'jinja'
salt '*' slsutil.renderer /path/to/file.sls 'jinja|yaml'
salt '*' slsutil.renderer string='Inline template! {{ saltenv }}'
salt '*' slsutil.renderer string='Hello, {{ name }}.' name='world'
'''
if not path and not string:
raise salt.exceptions.SaltInvocationError(
'Must pass either path or string')
renderers = salt.loader.render(__opts__, __salt__)
if path:
path_or_string = __salt__['cp.get_url'](path, saltenv=kwargs.get('saltenv', 'base'))
elif string:
path_or_string = ':string:'
kwargs['input_data'] = string
ret = salt.template.compile_template(
path_or_string,
renderers,
default_renderer,
__opts__['renderer_blacklist'],
__opts__['renderer_whitelist'],
**kwargs
)
return ret.read() if __utils__['stringio.is_readable'](ret) else ret
def _get_serialize_fn(serializer, fn_name):
serializers = salt.loader.serializers(__opts__)
fns = getattr(serializers, serializer, None)
fn = getattr(fns, fn_name, None)
if not fns:
raise salt.exceptions.CommandExecutionError(
"Serializer '{0}' not found.".format(serializer))
if not fn:
raise salt.exceptions.CommandExecutionError(
"Serializer '{0}' does not implement {1}.".format(serializer,
fn_name))
return fn
def serialize(serializer, obj, **mod_kwargs):
'''
Serialize a Python object using a :py:mod:`serializer module
<salt.serializers>`
CLI Example:
.. code-block:: bash
salt '*' --no-parse=obj slsutil.serialize 'json' obj="{'foo': 'Foo!'}
Jinja Example:
.. code-block:: jinja
{% set json_string = salt.slsutil.serialize('json',
{'foo': 'Foo!'}) %}
'''
kwargs = salt.utils.args.clean_kwargs(**mod_kwargs)
return _get_serialize_fn(serializer, 'serialize')(obj, **kwargs)
def banner(width=72, commentchar='#', borderchar='#', blockstart=None, blockend=None,
title=None, text=None, newline=False):
'''
Create a standardized comment block to include in a templated file.
A common technique in configuration management is to include a comment
block in managed files, warning users not to modify the file. This
function simplifies and standardizes those comment blocks.
:param width: The width, in characters, of the banner. Default is 72.
:param commentchar: The character to be used in the starting position of
each line. This value should be set to a valid line comment character
for the syntax of the file in which the banner is being inserted.
Multiple character sequences, like '//' are supported.
If the file's syntax does not support line comments (such as XML),
use the ``blockstart`` and ``blockend`` options.
:param borderchar: The character to use in the top and bottom border of
the comment box. Must be a single character.
:param blockstart: The character sequence to use at the beginning of a
block comment. Should be used in conjunction with ``blockend``
:param blockend: The character sequence to use at the end of a
block comment. Should be used in conjunction with ``blockstart``
:param title: The first field of the comment block. This field appears
centered at the top of the box.
:param text: The second filed of the comment block. This field appears
left-justifed at the bottom of the box.
:param newline: Boolean value to indicate whether the comment block should
end with a newline. Default is ``False``.
This banner can be injected into any templated file, for example:
.. code-block:: jinja
{{ salt['slsutil.banner'](width=120, commentchar='//') }}
The default banner:
.. code-block:: none
########################################################################
# #
# THIS FILE IS MANAGED BY SALT - DO NOT EDIT #
# #
# The contents of this file are managed by Salt. Any changes to this #
# file may be overwritten automatically and without warning. #
########################################################################
'''
if title is None:
title = 'THIS FILE IS MANAGED BY SALT - DO NOT EDIT'
if text is None:
text = ('The contents of this file are managed by Salt. '
'Any changes to this file may be overwritten '
'automatically and without warning')
# Set up some typesetting variables
lgutter = commentchar.strip() + ' '
rgutter = ' ' + commentchar.strip()
textwidth = width - len(lgutter) - len(rgutter)
border_line = commentchar + borderchar[:1] * (width - len(commentchar) * 2) + commentchar
spacer_line = commentchar + ' ' * (width - len(commentchar) * 2) + commentchar
wrapper = textwrap.TextWrapper(width=(width - len(lgutter) - len(rgutter)))
block = list()
# Create the banner
if blockstart is not None:
block.append(blockstart)
block.append(border_line)
block.append(spacer_line)
for line in wrapper.wrap(title):
block.append(lgutter + line.center(textwidth) + rgutter)
block.append(spacer_line)
for line in wrapper.wrap(text):
block.append(lgutter + line + ' ' * (textwidth - len(line)) + rgutter)
block.append(border_line)
if blockend is not None:
block.append(blockend)
# Convert list to multi-line string
result = os.linesep.join(block)
# Add a newline character to the end of the banner
if newline:
return result + os.linesep
return result
def boolstr(value, true='true', false='false'):
'''
Convert a boolean value into a string. This function is
intended to be used from within file templates to provide
an easy way to take boolean values stored in Pillars or
Grains, and write them out in the apprpriate syntax for
a particular file template.
:param value: The boolean value to be converted
:param true: The value to return if ``value`` is ``True``
:param false: The value to return if ``value`` is ``False``
In this example, a pillar named ``smtp:encrypted`` stores a boolean
value, but the template that uses that value needs ``yes`` or ``no``
to be written, based on the boolean value.
*Note: this is written on two lines for clarity. The same result
could be achieved in one line.*
.. code-block:: jinja
{% set encrypted = salt[pillar.get]('smtp:encrypted', false) %}
use_tls: {{ salt['slsutil.boolstr'](encrypted, 'yes', 'no') }}
Result (assuming the value is ``True``):
.. code-block:: none
use_tls: yes
'''
if value:
return true
return false
|
saltstack/salt
|
salt/modules/slsutil.py
|
banner
|
python
|
def banner(width=72, commentchar='#', borderchar='#', blockstart=None, blockend=None,
title=None, text=None, newline=False):
'''
Create a standardized comment block to include in a templated file.
A common technique in configuration management is to include a comment
block in managed files, warning users not to modify the file. This
function simplifies and standardizes those comment blocks.
:param width: The width, in characters, of the banner. Default is 72.
:param commentchar: The character to be used in the starting position of
each line. This value should be set to a valid line comment character
for the syntax of the file in which the banner is being inserted.
Multiple character sequences, like '//' are supported.
If the file's syntax does not support line comments (such as XML),
use the ``blockstart`` and ``blockend`` options.
:param borderchar: The character to use in the top and bottom border of
the comment box. Must be a single character.
:param blockstart: The character sequence to use at the beginning of a
block comment. Should be used in conjunction with ``blockend``
:param blockend: The character sequence to use at the end of a
block comment. Should be used in conjunction with ``blockstart``
:param title: The first field of the comment block. This field appears
centered at the top of the box.
:param text: The second filed of the comment block. This field appears
left-justifed at the bottom of the box.
:param newline: Boolean value to indicate whether the comment block should
end with a newline. Default is ``False``.
This banner can be injected into any templated file, for example:
.. code-block:: jinja
{{ salt['slsutil.banner'](width=120, commentchar='//') }}
The default banner:
.. code-block:: none
########################################################################
# #
# THIS FILE IS MANAGED BY SALT - DO NOT EDIT #
# #
# The contents of this file are managed by Salt. Any changes to this #
# file may be overwritten automatically and without warning. #
########################################################################
'''
if title is None:
title = 'THIS FILE IS MANAGED BY SALT - DO NOT EDIT'
if text is None:
text = ('The contents of this file are managed by Salt. '
'Any changes to this file may be overwritten '
'automatically and without warning')
# Set up some typesetting variables
lgutter = commentchar.strip() + ' '
rgutter = ' ' + commentchar.strip()
textwidth = width - len(lgutter) - len(rgutter)
border_line = commentchar + borderchar[:1] * (width - len(commentchar) * 2) + commentchar
spacer_line = commentchar + ' ' * (width - len(commentchar) * 2) + commentchar
wrapper = textwrap.TextWrapper(width=(width - len(lgutter) - len(rgutter)))
block = list()
# Create the banner
if blockstart is not None:
block.append(blockstart)
block.append(border_line)
block.append(spacer_line)
for line in wrapper.wrap(title):
block.append(lgutter + line.center(textwidth) + rgutter)
block.append(spacer_line)
for line in wrapper.wrap(text):
block.append(lgutter + line + ' ' * (textwidth - len(line)) + rgutter)
block.append(border_line)
if blockend is not None:
block.append(blockend)
# Convert list to multi-line string
result = os.linesep.join(block)
# Add a newline character to the end of the banner
if newline:
return result + os.linesep
return result
|
Create a standardized comment block to include in a templated file.
A common technique in configuration management is to include a comment
block in managed files, warning users not to modify the file. This
function simplifies and standardizes those comment blocks.
:param width: The width, in characters, of the banner. Default is 72.
:param commentchar: The character to be used in the starting position of
each line. This value should be set to a valid line comment character
for the syntax of the file in which the banner is being inserted.
Multiple character sequences, like '//' are supported.
If the file's syntax does not support line comments (such as XML),
use the ``blockstart`` and ``blockend`` options.
:param borderchar: The character to use in the top and bottom border of
the comment box. Must be a single character.
:param blockstart: The character sequence to use at the beginning of a
block comment. Should be used in conjunction with ``blockend``
:param blockend: The character sequence to use at the end of a
block comment. Should be used in conjunction with ``blockstart``
:param title: The first field of the comment block. This field appears
centered at the top of the box.
:param text: The second filed of the comment block. This field appears
left-justifed at the bottom of the box.
:param newline: Boolean value to indicate whether the comment block should
end with a newline. Default is ``False``.
This banner can be injected into any templated file, for example:
.. code-block:: jinja
{{ salt['slsutil.banner'](width=120, commentchar='//') }}
The default banner:
.. code-block:: none
########################################################################
# #
# THIS FILE IS MANAGED BY SALT - DO NOT EDIT #
# #
# The contents of this file are managed by Salt. Any changes to this #
# file may be overwritten automatically and without warning. #
########################################################################
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/slsutil.py#L253-L339
| null |
# -*- coding: utf-8 -*-
'''
Utility functions for use with or in SLS files
'''
# Import Python libs
from __future__ import absolute_import, unicode_literals, print_function
import textwrap
import os
# Import Salt libs
import salt.exceptions
import salt.loader
import salt.template
import salt.utils.args
import salt.utils.dictupdate
def update(dest, upd, recursive_update=True, merge_lists=False):
'''
Merge ``upd`` recursively into ``dest``
If ``merge_lists=True``, will aggregate list object types instead of
replacing. This behavior is only activated when ``recursive_update=True``.
CLI Example:
.. code-block:: shell
salt '*' slsutil.update '{foo: Foo}' '{bar: Bar}'
'''
return salt.utils.dictupdate.update(dest, upd, recursive_update,
merge_lists)
def merge(obj_a, obj_b, strategy='smart', renderer='yaml', merge_lists=False):
'''
Merge a data structure into another by choosing a merge strategy
Strategies:
* aggregate
* list
* overwrite
* recurse
* smart
CLI Example:
.. code-block:: shell
salt '*' slsutil.merge '{foo: Foo}' '{bar: Bar}'
'''
return salt.utils.dictupdate.merge(obj_a, obj_b, strategy, renderer,
merge_lists)
def merge_all(lst, strategy='smart', renderer='yaml', merge_lists=False):
'''
.. versionadded:: 2019.2.0
Merge a list of objects into each other in order
:type lst: Iterable
:param lst: List of objects to be merged.
:type strategy: String
:param strategy: Merge strategy. See utils.dictupdate.
:type renderer: String
:param renderer:
Renderer type. Used to determine strategy when strategy is 'smart'.
:type merge_lists: Bool
:param merge_lists: Defines whether to merge embedded object lists.
CLI Example:
.. code-block:: shell
$ salt-call --output=txt slsutil.merge_all '[{foo: Foo}, {foo: Bar}]'
local: {u'foo': u'Bar'}
'''
ret = {}
for obj in lst:
ret = salt.utils.dictupdate.merge(
ret, obj, strategy, renderer, merge_lists
)
return ret
def renderer(path=None, string=None, default_renderer='jinja|yaml', **kwargs):
'''
Parse a string or file through Salt's renderer system
.. versionchanged:: 2018.3.0
Add support for Salt fileserver URIs.
This is an open-ended function and can be used for a variety of tasks. It
makes use of Salt's "renderer pipes" system to run a string or file through
a pipe of any of the loaded renderer modules.
:param path: The path to a file on Salt's fileserver (any URIs supported by
:py:func:`cp.get_url <salt.modules.cp.get_url>`) or on the local file
system.
:param string: An inline string to be used as the file to send through the
renderer system. Note, not all renderer modules can work with strings;
the 'py' renderer requires a file, for example.
:param default_renderer: The renderer pipe to send the file through; this
is overridden by a "she-bang" at the top of the file.
:param kwargs: Keyword args to pass to Salt's compile_template() function.
Keep in mind the goal of each renderer when choosing a render-pipe; for
example, the Jinja renderer processes a text file and produces a string,
however the YAML renderer processes a text file and produces a data
structure.
One possible use is to allow writing "map files", as are commonly seen in
Salt formulas, but without tying the renderer of the map file to the
renderer used in the other sls files. In other words, a map file could use
the Python renderer and still be included and used by an sls file that uses
the default 'jinja|yaml' renderer.
For example, the two following map files produce identical results but one
is written using the normal 'jinja|yaml' and the other is using 'py':
.. code-block:: jinja
#!jinja|yaml
{% set apache = salt.grains.filter_by({
...normal jinja map file here...
}, merge=salt.pillar.get('apache:lookup')) %}
{{ apache | yaml() }}
.. code-block:: python
#!py
def run():
apache = __salt__.grains.filter_by({
...normal map here but as a python dict...
}, merge=__salt__.pillar.get('apache:lookup'))
return apache
Regardless of which of the above map files is used, it can be accessed from
any other sls file by calling this function. The following is a usage
example in Jinja:
.. code-block:: jinja
{% set apache = salt.slsutil.renderer('map.sls') %}
CLI Example:
.. code-block:: bash
salt '*' slsutil.renderer salt://path/to/file
salt '*' slsutil.renderer /path/to/file
salt '*' slsutil.renderer /path/to/file.jinja 'jinja'
salt '*' slsutil.renderer /path/to/file.sls 'jinja|yaml'
salt '*' slsutil.renderer string='Inline template! {{ saltenv }}'
salt '*' slsutil.renderer string='Hello, {{ name }}.' name='world'
'''
if not path and not string:
raise salt.exceptions.SaltInvocationError(
'Must pass either path or string')
renderers = salt.loader.render(__opts__, __salt__)
if path:
path_or_string = __salt__['cp.get_url'](path, saltenv=kwargs.get('saltenv', 'base'))
elif string:
path_or_string = ':string:'
kwargs['input_data'] = string
ret = salt.template.compile_template(
path_or_string,
renderers,
default_renderer,
__opts__['renderer_blacklist'],
__opts__['renderer_whitelist'],
**kwargs
)
return ret.read() if __utils__['stringio.is_readable'](ret) else ret
def _get_serialize_fn(serializer, fn_name):
serializers = salt.loader.serializers(__opts__)
fns = getattr(serializers, serializer, None)
fn = getattr(fns, fn_name, None)
if not fns:
raise salt.exceptions.CommandExecutionError(
"Serializer '{0}' not found.".format(serializer))
if not fn:
raise salt.exceptions.CommandExecutionError(
"Serializer '{0}' does not implement {1}.".format(serializer,
fn_name))
return fn
def serialize(serializer, obj, **mod_kwargs):
'''
Serialize a Python object using a :py:mod:`serializer module
<salt.serializers>`
CLI Example:
.. code-block:: bash
salt '*' --no-parse=obj slsutil.serialize 'json' obj="{'foo': 'Foo!'}
Jinja Example:
.. code-block:: jinja
{% set json_string = salt.slsutil.serialize('json',
{'foo': 'Foo!'}) %}
'''
kwargs = salt.utils.args.clean_kwargs(**mod_kwargs)
return _get_serialize_fn(serializer, 'serialize')(obj, **kwargs)
def deserialize(serializer, stream_or_string, **mod_kwargs):
'''
Deserialize a Python object using a :py:mod:`serializer module
<salt.serializers>`
CLI Example:
.. code-block:: bash
salt '*' slsutil.deserialize 'json' '{"foo": "Foo!"}'
salt '*' --no-parse=stream_or_string slsutil.deserialize 'json' \\
stream_or_string='{"foo": "Foo!"}'
Jinja Example:
.. code-block:: jinja
{% set python_object = salt.slsutil.deserialize('json',
'{"foo": "Foo!"}') %}
'''
kwargs = salt.utils.args.clean_kwargs(**mod_kwargs)
return _get_serialize_fn(serializer, 'deserialize')(stream_or_string,
**kwargs)
def boolstr(value, true='true', false='false'):
'''
Convert a boolean value into a string. This function is
intended to be used from within file templates to provide
an easy way to take boolean values stored in Pillars or
Grains, and write them out in the apprpriate syntax for
a particular file template.
:param value: The boolean value to be converted
:param true: The value to return if ``value`` is ``True``
:param false: The value to return if ``value`` is ``False``
In this example, a pillar named ``smtp:encrypted`` stores a boolean
value, but the template that uses that value needs ``yes`` or ``no``
to be written, based on the boolean value.
*Note: this is written on two lines for clarity. The same result
could be achieved in one line.*
.. code-block:: jinja
{% set encrypted = salt[pillar.get]('smtp:encrypted', false) %}
use_tls: {{ salt['slsutil.boolstr'](encrypted, 'yes', 'no') }}
Result (assuming the value is ``True``):
.. code-block:: none
use_tls: yes
'''
if value:
return true
return false
|
saltstack/salt
|
salt/utils/msazure.py
|
get_storage_conn
|
python
|
def get_storage_conn(storage_account=None, storage_key=None, opts=None):
'''
.. versionadded:: 2015.8.0
Return a storage_conn object for the storage account
'''
if opts is None:
opts = {}
if not storage_account:
storage_account = opts.get('storage_account', None)
if not storage_key:
storage_key = opts.get('storage_key', None)
return azure.storage.BlobService(storage_account, storage_key)
|
.. versionadded:: 2015.8.0
Return a storage_conn object for the storage account
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/msazure.py#L26-L40
| null |
# -*- coding: utf-8 -*-
'''
.. versionadded:: 2015.8.0
Utilities for accessing storage container blobs on Azure
'''
# Import python libs
from __future__ import absolute_import, unicode_literals
import logging
# Import azure libs
HAS_LIBS = False
try:
import azure
HAS_LIBS = True
except ImportError:
pass
# Import salt libs
from salt.exceptions import SaltSystemExit
log = logging.getLogger(__name__)
def list_blobs(storage_conn=None, **kwargs):
'''
.. versionadded:: 2015.8.0
List blobs associated with the container
'''
if not storage_conn:
storage_conn = get_storage_conn(opts=kwargs)
if 'container' not in kwargs:
raise SaltSystemExit(
code=42,
msg='An storage container name must be specified as "container"'
)
data = storage_conn.list_blobs(
container_name=kwargs['container'],
prefix=kwargs.get('prefix', None),
marker=kwargs.get('marker', None),
maxresults=kwargs.get('maxresults', None),
include=kwargs.get('include', None),
delimiter=kwargs.get('delimiter', None),
)
ret = {}
for item in data.blobs:
ret[item.name] = object_to_dict(item)
return ret
def put_blob(storage_conn=None, **kwargs):
'''
.. versionadded:: 2015.8.0
Upload a blob
'''
if not storage_conn:
storage_conn = get_storage_conn(opts=kwargs)
if 'container' not in kwargs:
raise SaltSystemExit(code=42, msg='The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltSystemExit(code=42, msg='The blob name must be specified as "name"')
if 'blob_path' not in kwargs and 'blob_content' not in kwargs:
raise SaltSystemExit(
code=42,
msg='Either a path to a file needs to be passed in as "blob_path" '
'or the contents of a blob as "blob_content."'
)
blob_kwargs = {
'container_name': kwargs['container'],
'blob_name': kwargs['name'],
'cache_control': kwargs.get('cache_control', None),
'content_language': kwargs.get('content_language', None),
'content_md5': kwargs.get('content_md5', None),
'x_ms_blob_content_type': kwargs.get('blob_content_type', None),
'x_ms_blob_content_encoding': kwargs.get('blob_content_encoding', None),
'x_ms_blob_content_language': kwargs.get('blob_content_language', None),
'x_ms_blob_content_md5': kwargs.get('blob_content_md5', None),
'x_ms_blob_cache_control': kwargs.get('blob_cache_control', None),
'x_ms_meta_name_values': kwargs.get('meta_name_values', None),
'x_ms_lease_id': kwargs.get('lease_id', None),
}
if 'blob_path' in kwargs:
data = storage_conn.put_block_blob_from_path(
file_path=kwargs['blob_path'],
**blob_kwargs
)
elif 'blob_content' in kwargs:
data = storage_conn.put_block_blob_from_bytes(
blob=kwargs['blob_content'],
**blob_kwargs
)
return data
def get_blob(storage_conn=None, **kwargs):
'''
.. versionadded:: 2015.8.0
Download a blob
'''
if not storage_conn:
storage_conn = get_storage_conn(opts=kwargs)
if 'container' not in kwargs:
raise SaltSystemExit(code=42, msg='The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltSystemExit(code=42, msg='The blob name must be specified as "name"')
if 'local_path' not in kwargs and 'return_content' not in kwargs:
raise SaltSystemExit(
code=42,
msg='Either a local path needs to be passed in as "local_path", '
'or "return_content" to return the blob contents directly'
)
blob_kwargs = {
'container_name': kwargs['container'],
'blob_name': kwargs['name'],
'snapshot': kwargs.get('snapshot', None),
'x_ms_lease_id': kwargs.get('lease_id', None),
'progress_callback': kwargs.get('progress_callback', None),
'max_connections': kwargs.get('max_connections', 1),
'max_retries': kwargs.get('max_retries', 5),
'retry_wait': kwargs.get('retry_wait', 1),
}
if 'local_path' in kwargs:
data = storage_conn.get_blob_to_path(
file_path=kwargs['local_path'],
open_mode=kwargs.get('open_mode', 'wb'),
**blob_kwargs
)
elif 'return_content' in kwargs:
data = storage_conn.get_blob_to_bytes(
**blob_kwargs
)
return data
def object_to_dict(obj):
'''
.. versionadded:: 2015.8.0
Convert an object to a dictionary
'''
if isinstance(obj, list) or isinstance(obj, tuple):
ret = []
for item in obj:
ret.append(object_to_dict(item))
elif hasattr(obj, '__dict__'):
ret = {}
for item in obj.__dict__:
if item.startswith('_'):
continue
ret[item] = object_to_dict(obj.__dict__[item])
else:
ret = obj
return ret
|
saltstack/salt
|
salt/utils/msazure.py
|
list_blobs
|
python
|
def list_blobs(storage_conn=None, **kwargs):
'''
.. versionadded:: 2015.8.0
List blobs associated with the container
'''
if not storage_conn:
storage_conn = get_storage_conn(opts=kwargs)
if 'container' not in kwargs:
raise SaltSystemExit(
code=42,
msg='An storage container name must be specified as "container"'
)
data = storage_conn.list_blobs(
container_name=kwargs['container'],
prefix=kwargs.get('prefix', None),
marker=kwargs.get('marker', None),
maxresults=kwargs.get('maxresults', None),
include=kwargs.get('include', None),
delimiter=kwargs.get('delimiter', None),
)
ret = {}
for item in data.blobs:
ret[item.name] = object_to_dict(item)
return ret
|
.. versionadded:: 2015.8.0
List blobs associated with the container
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/msazure.py#L43-L70
|
[
"def get_storage_conn(storage_account=None, storage_key=None, opts=None):\n '''\n .. versionadded:: 2015.8.0\n\n Return a storage_conn object for the storage account\n '''\n if opts is None:\n opts = {}\n\n if not storage_account:\n storage_account = opts.get('storage_account', None)\n if not storage_key:\n storage_key = opts.get('storage_key', None)\n\n return azure.storage.BlobService(storage_account, storage_key)\n",
"def object_to_dict(obj):\n '''\n .. versionadded:: 2015.8.0\n\n Convert an object to a dictionary\n '''\n if isinstance(obj, list) or isinstance(obj, tuple):\n ret = []\n for item in obj:\n ret.append(object_to_dict(item))\n elif hasattr(obj, '__dict__'):\n ret = {}\n for item in obj.__dict__:\n if item.startswith('_'):\n continue\n ret[item] = object_to_dict(obj.__dict__[item])\n else:\n ret = obj\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
.. versionadded:: 2015.8.0
Utilities for accessing storage container blobs on Azure
'''
# Import python libs
from __future__ import absolute_import, unicode_literals
import logging
# Import azure libs
HAS_LIBS = False
try:
import azure
HAS_LIBS = True
except ImportError:
pass
# Import salt libs
from salt.exceptions import SaltSystemExit
log = logging.getLogger(__name__)
def get_storage_conn(storage_account=None, storage_key=None, opts=None):
'''
.. versionadded:: 2015.8.0
Return a storage_conn object for the storage account
'''
if opts is None:
opts = {}
if not storage_account:
storage_account = opts.get('storage_account', None)
if not storage_key:
storage_key = opts.get('storage_key', None)
return azure.storage.BlobService(storage_account, storage_key)
def put_blob(storage_conn=None, **kwargs):
'''
.. versionadded:: 2015.8.0
Upload a blob
'''
if not storage_conn:
storage_conn = get_storage_conn(opts=kwargs)
if 'container' not in kwargs:
raise SaltSystemExit(code=42, msg='The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltSystemExit(code=42, msg='The blob name must be specified as "name"')
if 'blob_path' not in kwargs and 'blob_content' not in kwargs:
raise SaltSystemExit(
code=42,
msg='Either a path to a file needs to be passed in as "blob_path" '
'or the contents of a blob as "blob_content."'
)
blob_kwargs = {
'container_name': kwargs['container'],
'blob_name': kwargs['name'],
'cache_control': kwargs.get('cache_control', None),
'content_language': kwargs.get('content_language', None),
'content_md5': kwargs.get('content_md5', None),
'x_ms_blob_content_type': kwargs.get('blob_content_type', None),
'x_ms_blob_content_encoding': kwargs.get('blob_content_encoding', None),
'x_ms_blob_content_language': kwargs.get('blob_content_language', None),
'x_ms_blob_content_md5': kwargs.get('blob_content_md5', None),
'x_ms_blob_cache_control': kwargs.get('blob_cache_control', None),
'x_ms_meta_name_values': kwargs.get('meta_name_values', None),
'x_ms_lease_id': kwargs.get('lease_id', None),
}
if 'blob_path' in kwargs:
data = storage_conn.put_block_blob_from_path(
file_path=kwargs['blob_path'],
**blob_kwargs
)
elif 'blob_content' in kwargs:
data = storage_conn.put_block_blob_from_bytes(
blob=kwargs['blob_content'],
**blob_kwargs
)
return data
def get_blob(storage_conn=None, **kwargs):
'''
.. versionadded:: 2015.8.0
Download a blob
'''
if not storage_conn:
storage_conn = get_storage_conn(opts=kwargs)
if 'container' not in kwargs:
raise SaltSystemExit(code=42, msg='The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltSystemExit(code=42, msg='The blob name must be specified as "name"')
if 'local_path' not in kwargs and 'return_content' not in kwargs:
raise SaltSystemExit(
code=42,
msg='Either a local path needs to be passed in as "local_path", '
'or "return_content" to return the blob contents directly'
)
blob_kwargs = {
'container_name': kwargs['container'],
'blob_name': kwargs['name'],
'snapshot': kwargs.get('snapshot', None),
'x_ms_lease_id': kwargs.get('lease_id', None),
'progress_callback': kwargs.get('progress_callback', None),
'max_connections': kwargs.get('max_connections', 1),
'max_retries': kwargs.get('max_retries', 5),
'retry_wait': kwargs.get('retry_wait', 1),
}
if 'local_path' in kwargs:
data = storage_conn.get_blob_to_path(
file_path=kwargs['local_path'],
open_mode=kwargs.get('open_mode', 'wb'),
**blob_kwargs
)
elif 'return_content' in kwargs:
data = storage_conn.get_blob_to_bytes(
**blob_kwargs
)
return data
def object_to_dict(obj):
'''
.. versionadded:: 2015.8.0
Convert an object to a dictionary
'''
if isinstance(obj, list) or isinstance(obj, tuple):
ret = []
for item in obj:
ret.append(object_to_dict(item))
elif hasattr(obj, '__dict__'):
ret = {}
for item in obj.__dict__:
if item.startswith('_'):
continue
ret[item] = object_to_dict(obj.__dict__[item])
else:
ret = obj
return ret
|
saltstack/salt
|
salt/utils/msazure.py
|
put_blob
|
python
|
def put_blob(storage_conn=None, **kwargs):
'''
.. versionadded:: 2015.8.0
Upload a blob
'''
if not storage_conn:
storage_conn = get_storage_conn(opts=kwargs)
if 'container' not in kwargs:
raise SaltSystemExit(code=42, msg='The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltSystemExit(code=42, msg='The blob name must be specified as "name"')
if 'blob_path' not in kwargs and 'blob_content' not in kwargs:
raise SaltSystemExit(
code=42,
msg='Either a path to a file needs to be passed in as "blob_path" '
'or the contents of a blob as "blob_content."'
)
blob_kwargs = {
'container_name': kwargs['container'],
'blob_name': kwargs['name'],
'cache_control': kwargs.get('cache_control', None),
'content_language': kwargs.get('content_language', None),
'content_md5': kwargs.get('content_md5', None),
'x_ms_blob_content_type': kwargs.get('blob_content_type', None),
'x_ms_blob_content_encoding': kwargs.get('blob_content_encoding', None),
'x_ms_blob_content_language': kwargs.get('blob_content_language', None),
'x_ms_blob_content_md5': kwargs.get('blob_content_md5', None),
'x_ms_blob_cache_control': kwargs.get('blob_cache_control', None),
'x_ms_meta_name_values': kwargs.get('meta_name_values', None),
'x_ms_lease_id': kwargs.get('lease_id', None),
}
if 'blob_path' in kwargs:
data = storage_conn.put_block_blob_from_path(
file_path=kwargs['blob_path'],
**blob_kwargs
)
elif 'blob_content' in kwargs:
data = storage_conn.put_block_blob_from_bytes(
blob=kwargs['blob_content'],
**blob_kwargs
)
return data
|
.. versionadded:: 2015.8.0
Upload a blob
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/msazure.py#L73-L120
|
[
"def get_storage_conn(storage_account=None, storage_key=None, opts=None):\n '''\n .. versionadded:: 2015.8.0\n\n Return a storage_conn object for the storage account\n '''\n if opts is None:\n opts = {}\n\n if not storage_account:\n storage_account = opts.get('storage_account', None)\n if not storage_key:\n storage_key = opts.get('storage_key', None)\n\n return azure.storage.BlobService(storage_account, storage_key)\n"
] |
# -*- coding: utf-8 -*-
'''
.. versionadded:: 2015.8.0
Utilities for accessing storage container blobs on Azure
'''
# Import python libs
from __future__ import absolute_import, unicode_literals
import logging
# Import azure libs
HAS_LIBS = False
try:
import azure
HAS_LIBS = True
except ImportError:
pass
# Import salt libs
from salt.exceptions import SaltSystemExit
log = logging.getLogger(__name__)
def get_storage_conn(storage_account=None, storage_key=None, opts=None):
'''
.. versionadded:: 2015.8.0
Return a storage_conn object for the storage account
'''
if opts is None:
opts = {}
if not storage_account:
storage_account = opts.get('storage_account', None)
if not storage_key:
storage_key = opts.get('storage_key', None)
return azure.storage.BlobService(storage_account, storage_key)
def list_blobs(storage_conn=None, **kwargs):
'''
.. versionadded:: 2015.8.0
List blobs associated with the container
'''
if not storage_conn:
storage_conn = get_storage_conn(opts=kwargs)
if 'container' not in kwargs:
raise SaltSystemExit(
code=42,
msg='An storage container name must be specified as "container"'
)
data = storage_conn.list_blobs(
container_name=kwargs['container'],
prefix=kwargs.get('prefix', None),
marker=kwargs.get('marker', None),
maxresults=kwargs.get('maxresults', None),
include=kwargs.get('include', None),
delimiter=kwargs.get('delimiter', None),
)
ret = {}
for item in data.blobs:
ret[item.name] = object_to_dict(item)
return ret
def get_blob(storage_conn=None, **kwargs):
'''
.. versionadded:: 2015.8.0
Download a blob
'''
if not storage_conn:
storage_conn = get_storage_conn(opts=kwargs)
if 'container' not in kwargs:
raise SaltSystemExit(code=42, msg='The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltSystemExit(code=42, msg='The blob name must be specified as "name"')
if 'local_path' not in kwargs and 'return_content' not in kwargs:
raise SaltSystemExit(
code=42,
msg='Either a local path needs to be passed in as "local_path", '
'or "return_content" to return the blob contents directly'
)
blob_kwargs = {
'container_name': kwargs['container'],
'blob_name': kwargs['name'],
'snapshot': kwargs.get('snapshot', None),
'x_ms_lease_id': kwargs.get('lease_id', None),
'progress_callback': kwargs.get('progress_callback', None),
'max_connections': kwargs.get('max_connections', 1),
'max_retries': kwargs.get('max_retries', 5),
'retry_wait': kwargs.get('retry_wait', 1),
}
if 'local_path' in kwargs:
data = storage_conn.get_blob_to_path(
file_path=kwargs['local_path'],
open_mode=kwargs.get('open_mode', 'wb'),
**blob_kwargs
)
elif 'return_content' in kwargs:
data = storage_conn.get_blob_to_bytes(
**blob_kwargs
)
return data
def object_to_dict(obj):
'''
.. versionadded:: 2015.8.0
Convert an object to a dictionary
'''
if isinstance(obj, list) or isinstance(obj, tuple):
ret = []
for item in obj:
ret.append(object_to_dict(item))
elif hasattr(obj, '__dict__'):
ret = {}
for item in obj.__dict__:
if item.startswith('_'):
continue
ret[item] = object_to_dict(obj.__dict__[item])
else:
ret = obj
return ret
|
saltstack/salt
|
salt/utils/msazure.py
|
get_blob
|
python
|
def get_blob(storage_conn=None, **kwargs):
'''
.. versionadded:: 2015.8.0
Download a blob
'''
if not storage_conn:
storage_conn = get_storage_conn(opts=kwargs)
if 'container' not in kwargs:
raise SaltSystemExit(code=42, msg='The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltSystemExit(code=42, msg='The blob name must be specified as "name"')
if 'local_path' not in kwargs and 'return_content' not in kwargs:
raise SaltSystemExit(
code=42,
msg='Either a local path needs to be passed in as "local_path", '
'or "return_content" to return the blob contents directly'
)
blob_kwargs = {
'container_name': kwargs['container'],
'blob_name': kwargs['name'],
'snapshot': kwargs.get('snapshot', None),
'x_ms_lease_id': kwargs.get('lease_id', None),
'progress_callback': kwargs.get('progress_callback', None),
'max_connections': kwargs.get('max_connections', 1),
'max_retries': kwargs.get('max_retries', 5),
'retry_wait': kwargs.get('retry_wait', 1),
}
if 'local_path' in kwargs:
data = storage_conn.get_blob_to_path(
file_path=kwargs['local_path'],
open_mode=kwargs.get('open_mode', 'wb'),
**blob_kwargs
)
elif 'return_content' in kwargs:
data = storage_conn.get_blob_to_bytes(
**blob_kwargs
)
return data
|
.. versionadded:: 2015.8.0
Download a blob
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/msazure.py#L123-L167
|
[
"def get_storage_conn(storage_account=None, storage_key=None, opts=None):\n '''\n .. versionadded:: 2015.8.0\n\n Return a storage_conn object for the storage account\n '''\n if opts is None:\n opts = {}\n\n if not storage_account:\n storage_account = opts.get('storage_account', None)\n if not storage_key:\n storage_key = opts.get('storage_key', None)\n\n return azure.storage.BlobService(storage_account, storage_key)\n"
] |
# -*- coding: utf-8 -*-
'''
.. versionadded:: 2015.8.0
Utilities for accessing storage container blobs on Azure
'''
# Import python libs
from __future__ import absolute_import, unicode_literals
import logging
# Import azure libs
HAS_LIBS = False
try:
import azure
HAS_LIBS = True
except ImportError:
pass
# Import salt libs
from salt.exceptions import SaltSystemExit
log = logging.getLogger(__name__)
def get_storage_conn(storage_account=None, storage_key=None, opts=None):
'''
.. versionadded:: 2015.8.0
Return a storage_conn object for the storage account
'''
if opts is None:
opts = {}
if not storage_account:
storage_account = opts.get('storage_account', None)
if not storage_key:
storage_key = opts.get('storage_key', None)
return azure.storage.BlobService(storage_account, storage_key)
def list_blobs(storage_conn=None, **kwargs):
'''
.. versionadded:: 2015.8.0
List blobs associated with the container
'''
if not storage_conn:
storage_conn = get_storage_conn(opts=kwargs)
if 'container' not in kwargs:
raise SaltSystemExit(
code=42,
msg='An storage container name must be specified as "container"'
)
data = storage_conn.list_blobs(
container_name=kwargs['container'],
prefix=kwargs.get('prefix', None),
marker=kwargs.get('marker', None),
maxresults=kwargs.get('maxresults', None),
include=kwargs.get('include', None),
delimiter=kwargs.get('delimiter', None),
)
ret = {}
for item in data.blobs:
ret[item.name] = object_to_dict(item)
return ret
def put_blob(storage_conn=None, **kwargs):
'''
.. versionadded:: 2015.8.0
Upload a blob
'''
if not storage_conn:
storage_conn = get_storage_conn(opts=kwargs)
if 'container' not in kwargs:
raise SaltSystemExit(code=42, msg='The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltSystemExit(code=42, msg='The blob name must be specified as "name"')
if 'blob_path' not in kwargs and 'blob_content' not in kwargs:
raise SaltSystemExit(
code=42,
msg='Either a path to a file needs to be passed in as "blob_path" '
'or the contents of a blob as "blob_content."'
)
blob_kwargs = {
'container_name': kwargs['container'],
'blob_name': kwargs['name'],
'cache_control': kwargs.get('cache_control', None),
'content_language': kwargs.get('content_language', None),
'content_md5': kwargs.get('content_md5', None),
'x_ms_blob_content_type': kwargs.get('blob_content_type', None),
'x_ms_blob_content_encoding': kwargs.get('blob_content_encoding', None),
'x_ms_blob_content_language': kwargs.get('blob_content_language', None),
'x_ms_blob_content_md5': kwargs.get('blob_content_md5', None),
'x_ms_blob_cache_control': kwargs.get('blob_cache_control', None),
'x_ms_meta_name_values': kwargs.get('meta_name_values', None),
'x_ms_lease_id': kwargs.get('lease_id', None),
}
if 'blob_path' in kwargs:
data = storage_conn.put_block_blob_from_path(
file_path=kwargs['blob_path'],
**blob_kwargs
)
elif 'blob_content' in kwargs:
data = storage_conn.put_block_blob_from_bytes(
blob=kwargs['blob_content'],
**blob_kwargs
)
return data
def object_to_dict(obj):
'''
.. versionadded:: 2015.8.0
Convert an object to a dictionary
'''
if isinstance(obj, list) or isinstance(obj, tuple):
ret = []
for item in obj:
ret.append(object_to_dict(item))
elif hasattr(obj, '__dict__'):
ret = {}
for item in obj.__dict__:
if item.startswith('_'):
continue
ret[item] = object_to_dict(obj.__dict__[item])
else:
ret = obj
return ret
|
saltstack/salt
|
salt/utils/msazure.py
|
object_to_dict
|
python
|
def object_to_dict(obj):
'''
.. versionadded:: 2015.8.0
Convert an object to a dictionary
'''
if isinstance(obj, list) or isinstance(obj, tuple):
ret = []
for item in obj:
ret.append(object_to_dict(item))
elif hasattr(obj, '__dict__'):
ret = {}
for item in obj.__dict__:
if item.startswith('_'):
continue
ret[item] = object_to_dict(obj.__dict__[item])
else:
ret = obj
return ret
|
.. versionadded:: 2015.8.0
Convert an object to a dictionary
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/msazure.py#L170-L188
|
[
"def object_to_dict(obj):\n '''\n .. versionadded:: 2015.8.0\n\n Convert an object to a dictionary\n '''\n if isinstance(obj, list) or isinstance(obj, tuple):\n ret = []\n for item in obj:\n ret.append(object_to_dict(item))\n elif hasattr(obj, '__dict__'):\n ret = {}\n for item in obj.__dict__:\n if item.startswith('_'):\n continue\n ret[item] = object_to_dict(obj.__dict__[item])\n else:\n ret = obj\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
.. versionadded:: 2015.8.0
Utilities for accessing storage container blobs on Azure
'''
# Import python libs
from __future__ import absolute_import, unicode_literals
import logging
# Import azure libs
HAS_LIBS = False
try:
import azure
HAS_LIBS = True
except ImportError:
pass
# Import salt libs
from salt.exceptions import SaltSystemExit
log = logging.getLogger(__name__)
def get_storage_conn(storage_account=None, storage_key=None, opts=None):
'''
.. versionadded:: 2015.8.0
Return a storage_conn object for the storage account
'''
if opts is None:
opts = {}
if not storage_account:
storage_account = opts.get('storage_account', None)
if not storage_key:
storage_key = opts.get('storage_key', None)
return azure.storage.BlobService(storage_account, storage_key)
def list_blobs(storage_conn=None, **kwargs):
'''
.. versionadded:: 2015.8.0
List blobs associated with the container
'''
if not storage_conn:
storage_conn = get_storage_conn(opts=kwargs)
if 'container' not in kwargs:
raise SaltSystemExit(
code=42,
msg='An storage container name must be specified as "container"'
)
data = storage_conn.list_blobs(
container_name=kwargs['container'],
prefix=kwargs.get('prefix', None),
marker=kwargs.get('marker', None),
maxresults=kwargs.get('maxresults', None),
include=kwargs.get('include', None),
delimiter=kwargs.get('delimiter', None),
)
ret = {}
for item in data.blobs:
ret[item.name] = object_to_dict(item)
return ret
def put_blob(storage_conn=None, **kwargs):
'''
.. versionadded:: 2015.8.0
Upload a blob
'''
if not storage_conn:
storage_conn = get_storage_conn(opts=kwargs)
if 'container' not in kwargs:
raise SaltSystemExit(code=42, msg='The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltSystemExit(code=42, msg='The blob name must be specified as "name"')
if 'blob_path' not in kwargs and 'blob_content' not in kwargs:
raise SaltSystemExit(
code=42,
msg='Either a path to a file needs to be passed in as "blob_path" '
'or the contents of a blob as "blob_content."'
)
blob_kwargs = {
'container_name': kwargs['container'],
'blob_name': kwargs['name'],
'cache_control': kwargs.get('cache_control', None),
'content_language': kwargs.get('content_language', None),
'content_md5': kwargs.get('content_md5', None),
'x_ms_blob_content_type': kwargs.get('blob_content_type', None),
'x_ms_blob_content_encoding': kwargs.get('blob_content_encoding', None),
'x_ms_blob_content_language': kwargs.get('blob_content_language', None),
'x_ms_blob_content_md5': kwargs.get('blob_content_md5', None),
'x_ms_blob_cache_control': kwargs.get('blob_cache_control', None),
'x_ms_meta_name_values': kwargs.get('meta_name_values', None),
'x_ms_lease_id': kwargs.get('lease_id', None),
}
if 'blob_path' in kwargs:
data = storage_conn.put_block_blob_from_path(
file_path=kwargs['blob_path'],
**blob_kwargs
)
elif 'blob_content' in kwargs:
data = storage_conn.put_block_blob_from_bytes(
blob=kwargs['blob_content'],
**blob_kwargs
)
return data
def get_blob(storage_conn=None, **kwargs):
'''
.. versionadded:: 2015.8.0
Download a blob
'''
if not storage_conn:
storage_conn = get_storage_conn(opts=kwargs)
if 'container' not in kwargs:
raise SaltSystemExit(code=42, msg='The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltSystemExit(code=42, msg='The blob name must be specified as "name"')
if 'local_path' not in kwargs and 'return_content' not in kwargs:
raise SaltSystemExit(
code=42,
msg='Either a local path needs to be passed in as "local_path", '
'or "return_content" to return the blob contents directly'
)
blob_kwargs = {
'container_name': kwargs['container'],
'blob_name': kwargs['name'],
'snapshot': kwargs.get('snapshot', None),
'x_ms_lease_id': kwargs.get('lease_id', None),
'progress_callback': kwargs.get('progress_callback', None),
'max_connections': kwargs.get('max_connections', 1),
'max_retries': kwargs.get('max_retries', 5),
'retry_wait': kwargs.get('retry_wait', 1),
}
if 'local_path' in kwargs:
data = storage_conn.get_blob_to_path(
file_path=kwargs['local_path'],
open_mode=kwargs.get('open_mode', 'wb'),
**blob_kwargs
)
elif 'return_content' in kwargs:
data = storage_conn.get_blob_to_bytes(
**blob_kwargs
)
return data
|
saltstack/salt
|
salt/cloud/cli.py
|
SaltCloud.run
|
python
|
def run(self):
'''
Execute the salt-cloud command line
'''
# Parse shell arguments
self.parse_args()
salt_master_user = self.config.get('user')
if salt_master_user is None:
salt_master_user = salt.utils.user.get_user()
if not check_user(salt_master_user):
self.error(
'If salt-cloud is running on a master machine, salt-cloud '
'needs to run as the same user as the salt-master, \'{0}\'. '
'If salt-cloud is not running on a salt-master, the '
'appropriate write permissions must be granted to \'{1}\'. '
'Please run salt-cloud as root, \'{0}\', or change '
'permissions for \'{1}\'.'.format(
salt_master_user,
syspaths.CONFIG_DIR
)
)
try:
if self.config['verify_env']:
verify_env(
[os.path.dirname(self.config['conf_file'])],
salt_master_user,
root_dir=self.config['root_dir'],
)
logfile = self.config['log_file']
if logfile is not None and not logfile.startswith('tcp://') \
and not logfile.startswith('udp://') \
and not logfile.startswith('file://'):
# Logfile is not using Syslog, verify
verify_files([logfile], salt_master_user)
except (IOError, OSError) as err:
log.error('Error while verifying the environment: %s', err)
sys.exit(err.errno)
# Setup log file logging
self.setup_logfile_logger()
verify_log(self.config)
if self.options.update_bootstrap:
ret = salt.utils.cloud.update_bootstrap(self.config)
salt.output.display_output(ret,
self.options.output,
opts=self.config)
self.exit(salt.defaults.exitcodes.EX_OK)
log.info('salt-cloud starting')
try:
mapper = salt.cloud.Map(self.config)
except SaltCloudSystemExit as exc:
self.handle_exception(exc.args, exc)
except SaltCloudException as exc:
msg = 'There was an error generating the mapper.'
self.handle_exception(msg, exc)
names = self.config.get('names', None)
if names is not None:
filtered_rendered_map = {}
for map_profile in mapper.rendered_map:
filtered_map_profile = {}
for name in mapper.rendered_map[map_profile]:
if name in names:
filtered_map_profile[name] = mapper.rendered_map[map_profile][name]
if filtered_map_profile:
filtered_rendered_map[map_profile] = filtered_map_profile
mapper.rendered_map = filtered_rendered_map
ret = {}
if self.selected_query_option is not None:
if self.selected_query_option == 'list_providers':
try:
ret = mapper.provider_list()
except (SaltCloudException, Exception) as exc:
msg = 'There was an error listing providers: {0}'
self.handle_exception(msg, exc)
elif self.selected_query_option == 'list_profiles':
provider = self.options.list_profiles
try:
ret = mapper.profile_list(provider)
except(SaltCloudException, Exception) as exc:
msg = 'There was an error listing profiles: {0}'
self.handle_exception(msg, exc)
elif self.config.get('map', None):
log.info('Applying map from \'%s\'.', self.config['map'])
try:
ret = mapper.interpolated_map(
query=self.selected_query_option
)
except (SaltCloudException, Exception) as exc:
msg = 'There was an error with a custom map: {0}'
self.handle_exception(msg, exc)
else:
try:
ret = mapper.map_providers_parallel(
query=self.selected_query_option
)
except (SaltCloudException, Exception) as exc:
msg = 'There was an error with a map: {0}'
self.handle_exception(msg, exc)
elif self.options.list_locations is not None:
try:
ret = mapper.location_list(
self.options.list_locations
)
except (SaltCloudException, Exception) as exc:
msg = 'There was an error listing locations: {0}'
self.handle_exception(msg, exc)
elif self.options.list_images is not None:
try:
ret = mapper.image_list(
self.options.list_images
)
except (SaltCloudException, Exception) as exc:
msg = 'There was an error listing images: {0}'
self.handle_exception(msg, exc)
elif self.options.list_sizes is not None:
try:
ret = mapper.size_list(
self.options.list_sizes
)
except (SaltCloudException, Exception) as exc:
msg = 'There was an error listing sizes: {0}'
self.handle_exception(msg, exc)
elif self.options.destroy and (self.config.get('names', None) or
self.config.get('map', None)):
map_file = self.config.get('map', None)
names = self.config.get('names', ())
if map_file is not None:
if names != ():
msg = 'Supplying a mapfile, \'{0}\', in addition to instance names {1} ' \
'with the \'--destroy\' or \'-d\' function is not supported. ' \
'Please choose to delete either the entire map file or individual ' \
'instances.'.format(map_file, names)
self.handle_exception(msg, SaltCloudSystemExit)
log.info('Applying map from \'%s\'.', map_file)
matching = mapper.delete_map(query='list_nodes')
else:
matching = mapper.get_running_by_names(
names,
profile=self.options.profile
)
if not matching:
print('No machines were found to be destroyed')
self.exit(salt.defaults.exitcodes.EX_OK)
msg = 'The following virtual machines are set to be destroyed:\n'
names = set()
for alias, drivers in six.iteritems(matching):
msg += ' {0}:\n'.format(alias)
for driver, vms in six.iteritems(drivers):
msg += ' {0}:\n'.format(driver)
for name in vms:
msg += ' {0}\n'.format(name)
names.add(name)
try:
if self.print_confirm(msg):
ret = mapper.destroy(names, cached=True)
except (SaltCloudException, Exception) as exc:
msg = 'There was an error destroying machines: {0}'
self.handle_exception(msg, exc)
elif self.options.action and (self.config.get('names', None) or
self.config.get('map', None)):
if self.config.get('map', None):
log.info('Applying map from \'%s\'.', self.config['map'])
try:
names = mapper.get_vmnames_by_action(self.options.action)
except SaltCloudException as exc:
msg = 'There was an error actioning virtual machines.'
self.handle_exception(msg, exc)
else:
names = self.config.get('names', None)
kwargs = {}
machines = []
msg = (
'The following virtual machines are set to be actioned with '
'"{0}":\n'.format(
self.options.action
)
)
for name in names:
if '=' in name:
# This is obviously not a machine name, treat it as a kwarg
key, value = name.split('=', 1)
kwargs[key] = value
else:
msg += ' {0}\n'.format(name)
machines.append(name)
names = machines
try:
if self.print_confirm(msg):
ret = mapper.do_action(names, kwargs)
except (SaltCloudException, Exception) as exc:
msg = 'There was an error actioning machines: {0}'
self.handle_exception(msg, exc)
elif self.options.function:
kwargs = {}
args = self.args[:]
for arg in args[:]:
if '=' in arg:
key, value = arg.split('=', 1)
kwargs[key] = value
args.remove(arg)
if args:
self.error(
'Any arguments passed to --function need to be passed '
'as kwargs. Ex: image=ami-54cf5c3d. Remaining '
'arguments: {0}'.format(args)
)
try:
ret = mapper.do_function(
self.function_provider, self.function_name, kwargs
)
except (SaltCloudException, Exception) as exc:
msg = 'There was an error running the function: {0}'
self.handle_exception(msg, exc)
elif self.options.profile and self.config.get('names', False):
try:
ret = mapper.run_profile(
self.options.profile,
self.config.get('names')
)
except (SaltCloudException, Exception) as exc:
msg = 'There was a profile error: {0}'
self.handle_exception(msg, exc)
elif self.options.set_password:
username = self.credential_username
provider_name = "salt.cloud.provider.{0}".format(self.credential_provider)
# TODO: check if provider is configured
# set the password
salt.utils.cloud.store_password_in_keyring(provider_name, username)
elif self.config.get('map', None) and \
self.selected_query_option is None:
if not mapper.rendered_map:
sys.stderr.write('No nodes defined in this map')
self.exit(salt.defaults.exitcodes.EX_GENERIC)
try:
ret = {}
run_map = True
log.info('Applying map from \'%s\'.', self.config['map'])
dmap = mapper.map_data()
msg = ''
if 'errors' in dmap:
# display profile errors
msg += 'Found the following errors:\n'
for profile_name, error in six.iteritems(dmap['errors']):
msg += ' {0}: {1}\n'.format(profile_name, error)
sys.stderr.write(msg)
sys.stderr.flush()
msg = ''
if 'existing' in dmap:
msg += ('The following virtual machines already exist:\n')
for name in dmap['existing']:
msg += ' {0}\n'.format(name)
if dmap['create']:
msg += ('The following virtual machines are set to be '
'created:\n')
for name in dmap['create']:
msg += ' {0}\n'.format(name)
if 'destroy' in dmap:
msg += ('The following virtual machines are set to be '
'destroyed:\n')
for name in dmap['destroy']:
msg += ' {0}\n'.format(name)
if not dmap['create'] and not dmap.get('destroy', None):
if not dmap.get('existing', None):
# nothing to create or destroy & nothing exists
print(msg)
self.exit(1)
else:
# nothing to create or destroy, print existing
run_map = False
if run_map:
if self.print_confirm(msg):
ret = mapper.run_map(dmap)
if self.config.get('parallel', False) is False:
log.info('Complete')
if dmap.get('existing', None):
for name in dmap['existing']:
if 'ec2' in dmap['existing'][name]['provider']:
msg = 'Instance already exists, or is terminated and has the same name.'
else:
msg = 'Already running.'
ret[name] = {'Message': msg}
except (SaltCloudException, Exception) as exc:
msg = 'There was a query error: {0}'
self.handle_exception(msg, exc)
elif self.options.bootstrap:
host = self.options.bootstrap
if self.args and '=' not in self.args[0]:
minion_id = self.args.pop(0)
else:
minion_id = host
vm_ = {
'driver': '',
'ssh_host': host,
'name': minion_id,
}
args = self.args[:]
for arg in args[:]:
if '=' in arg:
key, value = arg.split('=', 1)
vm_[key] = value
args.remove(arg)
if args:
self.error(
'Any arguments passed to --bootstrap need to be passed as '
'kwargs. Ex: ssh_username=larry. Remaining arguments: {0}'.format(args)
)
try:
ret = salt.utils.cloud.bootstrap(vm_, self.config)
except (SaltCloudException, Exception) as exc:
msg = 'There was an error bootstrapping the minion: {0}'
self.handle_exception(msg, exc)
else:
self.error('Nothing was done. Using the proper arguments?')
salt.output.display_output(ret,
self.options.output,
opts=self.config)
self.exit(salt.defaults.exitcodes.EX_OK)
|
Execute the salt-cloud command line
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/cli.py#L41-L397
|
[
"def iteritems(d, **kw):\n return d.iteritems(**kw)\n",
"def verify_env(\n dirs,\n user,\n permissive=False,\n pki_dir='',\n skip_extra=False,\n root_dir=ROOT_DIR):\n '''\n Verify that the named directories are in place and that the environment\n can shake the salt\n '''\n if salt.utils.platform.is_windows():\n return win_verify_env(root_dir,\n dirs,\n permissive=permissive,\n skip_extra=skip_extra)\n import pwd # after confirming not running Windows\n try:\n pwnam = pwd.getpwnam(user)\n uid = pwnam[2]\n gid = pwnam[3]\n groups = salt.utils.user.get_gid_list(user, include_default=False)\n\n except KeyError:\n err = ('Failed to prepare the Salt environment for user '\n '{0}. The user is not available.\\n').format(user)\n sys.stderr.write(err)\n sys.exit(salt.defaults.exitcodes.EX_NOUSER)\n for dir_ in dirs:\n if not dir_:\n continue\n if not os.path.isdir(dir_):\n try:\n with salt.utils.files.set_umask(0o022):\n os.makedirs(dir_)\n # If starting the process as root, chown the new dirs\n if os.getuid() == 0:\n os.chown(dir_, uid, gid)\n except OSError as err:\n msg = 'Failed to create directory path \"{0}\" - {1}\\n'\n sys.stderr.write(msg.format(dir_, err))\n sys.exit(err.errno)\n\n mode = os.stat(dir_)\n # If starting the process as root, chown the new dirs\n if os.getuid() == 0:\n fmode = os.stat(dir_)\n if fmode.st_uid != uid or fmode.st_gid != gid:\n if permissive and fmode.st_gid in groups:\n # Allow the directory to be owned by any group root\n # belongs to if we say it's ok to be permissive\n pass\n else:\n # chown the file for the new user\n os.chown(dir_, uid, gid)\n for subdir in [a for a in os.listdir(dir_) if 'jobs' not in a]:\n fsubdir = os.path.join(dir_, subdir)\n if '{0}jobs'.format(os.path.sep) in fsubdir:\n continue\n for root, dirs, files in salt.utils.path.os_walk(fsubdir):\n for name in files:\n if name.startswith('.'):\n continue\n path = os.path.join(root, name)\n try:\n fmode = os.stat(path)\n except (IOError, OSError):\n pass\n if fmode.st_uid != uid or fmode.st_gid != gid:\n if permissive and fmode.st_gid in groups:\n pass\n else:\n # chown the file for the new user\n os.chown(path, uid, gid)\n for name in dirs:\n path = os.path.join(root, name)\n fmode = os.stat(path)\n if fmode.st_uid != uid or fmode.st_gid != gid:\n if permissive and fmode.st_gid in groups:\n pass\n else:\n # chown the file for the new user\n os.chown(path, uid, gid)\n # Allow the pki dir to be 700 or 750, but nothing else.\n # This prevents other users from writing out keys, while\n # allowing the use-case of 3rd-party software (like django)\n # to read in what it needs to integrate.\n #\n # If the permissions aren't correct, default to the more secure 700.\n # If acls are enabled, the pki_dir needs to remain readable, this\n # is still secure because the private keys are still only readable\n # by the user running the master\n if dir_ == pki_dir:\n smode = stat.S_IMODE(mode.st_mode)\n if smode != 448 and smode != 488:\n if os.access(dir_, os.W_OK):\n os.chmod(dir_, 448)\n else:\n msg = 'Unable to securely set the permissions of \"{0}\".'\n msg = msg.format(dir_)\n if is_console_configured():\n log.critical(msg)\n else:\n sys.stderr.write(\"CRITICAL: {0}\\n\".format(msg))\n\n if skip_extra is False:\n # Run the extra verification checks\n zmq_version()\n",
"def get_user():\n '''\n Get the current user\n '''\n if HAS_PWD:\n ret = pwd.getpwuid(os.geteuid()).pw_name\n elif HAS_WIN_FUNCTIONS and salt.utils.win_functions.HAS_WIN32:\n ret = salt.utils.win_functions.get_current_user()\n else:\n raise CommandExecutionError(\n 'Required external library (pwd or win32api) not installed')\n return salt.utils.stringutils.to_unicode(ret)\n",
"def update_bootstrap(config, url=None):\n '''\n Update the salt-bootstrap script\n\n url can be one of:\n\n - The URL to fetch the bootstrap script from\n - The absolute path to the bootstrap\n - The content of the bootstrap script\n '''\n default_url = config.get('bootstrap_script_url',\n 'https://bootstrap.saltstack.com')\n if not url:\n url = default_url\n if not url:\n raise ValueError('Cant get any source to update')\n if url.startswith('http') or '://' in url:\n log.debug('Updating the bootstrap-salt.sh script to latest stable')\n try:\n import requests\n except ImportError:\n return {'error': (\n 'Updating the bootstrap-salt.sh script requires the '\n 'Python requests library to be installed'\n )}\n req = requests.get(url)\n if req.status_code != 200:\n return {'error': (\n 'Failed to download the latest stable version of the '\n 'bootstrap-salt.sh script from {0}. HTTP error: '\n '{1}'.format(\n url, req.status_code\n )\n )}\n script_content = req.text\n if url == default_url:\n script_name = 'bootstrap-salt.sh'\n else:\n script_name = os.path.basename(url)\n elif os.path.exists(url):\n with salt.utils.files.fopen(url) as fic:\n script_content = salt.utils.stringutils.to_unicode(fic.read())\n script_name = os.path.basename(url)\n # in last case, assuming we got a script content\n else:\n script_content = url\n script_name = '{0}.sh'.format(\n hashlib.sha1(script_content).hexdigest()\n )\n\n if not script_content:\n raise ValueError('No content in bootstrap script !')\n\n # Get the path to the built-in deploy scripts directory\n builtin_deploy_dir = os.path.join(\n os.path.dirname(__file__),\n 'deploy'\n )\n\n # Compute the search path from the current loaded opts conf_file\n # value\n deploy_d_from_conf_file = os.path.join(\n os.path.dirname(config['conf_file']),\n 'cloud.deploy.d'\n )\n\n # Compute the search path using the install time defined\n # syspaths.CONF_DIR\n deploy_d_from_syspaths = os.path.join(\n config['config_dir'],\n 'cloud.deploy.d'\n )\n\n # Get a copy of any defined search paths, flagging them not to\n # create parent\n deploy_scripts_search_paths = []\n for entry in config.get('deploy_scripts_search_path', []):\n if entry.startswith(builtin_deploy_dir):\n # We won't write the updated script to the built-in deploy\n # directory\n continue\n\n if entry in (deploy_d_from_conf_file, deploy_d_from_syspaths):\n # Allow parent directories to be made\n deploy_scripts_search_paths.append((entry, True))\n else:\n deploy_scripts_search_paths.append((entry, False))\n\n # In case the user is not using defaults and the computed\n # 'cloud.deploy.d' from conf_file and syspaths is not included, add\n # them\n if deploy_d_from_conf_file not in deploy_scripts_search_paths:\n deploy_scripts_search_paths.append(\n (deploy_d_from_conf_file, True)\n )\n if deploy_d_from_syspaths not in deploy_scripts_search_paths:\n deploy_scripts_search_paths.append(\n (deploy_d_from_syspaths, True)\n )\n\n finished = []\n finished_full = []\n for entry, makedirs in deploy_scripts_search_paths:\n # This handles duplicate entries, which are likely to appear\n if entry in finished:\n continue\n else:\n finished.append(entry)\n\n if makedirs and not os.path.isdir(entry):\n try:\n os.makedirs(entry)\n except (OSError, IOError) as err:\n log.info('Failed to create directory \\'%s\\'', entry)\n continue\n\n if not is_writeable(entry):\n log.debug('The \\'%s\\' is not writeable. Continuing...', entry)\n continue\n\n deploy_path = os.path.join(entry, script_name)\n try:\n finished_full.append(deploy_path)\n with salt.utils.files.fopen(deploy_path, 'w') as fp_:\n fp_.write(salt.utils.stringutils.to_str(script_content))\n except (OSError, IOError) as err:\n log.debug('Failed to write the updated script: %s', err)\n continue\n\n return {'Success': {'Files updated': finished_full}}\n",
"def display_output(data, out=None, opts=None, **kwargs):\n '''\n Print the passed data using the desired output\n '''\n if opts is None:\n opts = {}\n display_data = try_printout(data, out, opts, **kwargs)\n\n output_filename = opts.get('output_file', None)\n log.trace('data = %s', data)\n try:\n # output filename can be either '' or None\n if output_filename:\n if not hasattr(output_filename, 'write'):\n ofh = salt.utils.files.fopen(output_filename, 'a') # pylint: disable=resource-leakage\n fh_opened = True\n else:\n # Filehandle/file-like object\n ofh = output_filename\n fh_opened = False\n\n try:\n fdata = display_data\n if isinstance(fdata, six.text_type):\n try:\n fdata = fdata.encode('utf-8')\n except (UnicodeDecodeError, UnicodeEncodeError):\n # try to let the stream write\n # even if we didn't encode it\n pass\n if fdata:\n ofh.write(salt.utils.stringutils.to_str(fdata))\n ofh.write('\\n')\n finally:\n if fh_opened:\n ofh.close()\n return\n if display_data:\n salt.utils.stringutils.print_cli(display_data)\n except IOError as exc:\n # Only raise if it's NOT a broken pipe\n if exc.errno != errno.EPIPE:\n raise exc\n",
"def check_user(user):\n '''\n Check user and assign process uid/gid.\n '''\n if salt.utils.platform.is_windows():\n return True\n if user == salt.utils.user.get_user():\n return True\n import pwd # after confirming not running Windows\n try:\n pwuser = pwd.getpwnam(user)\n try:\n if hasattr(os, 'initgroups'):\n os.initgroups(user, pwuser.pw_gid) # pylint: disable=minimum-python-version\n else:\n os.setgroups(salt.utils.user.get_gid_list(user, include_default=False))\n os.setgid(pwuser.pw_gid)\n os.setuid(pwuser.pw_uid)\n\n # We could just reset the whole environment but let's just override\n # the variables we can get from pwuser\n if 'HOME' in os.environ:\n os.environ['HOME'] = pwuser.pw_dir\n\n if 'SHELL' in os.environ:\n os.environ['SHELL'] = pwuser.pw_shell\n\n for envvar in ('USER', 'LOGNAME'):\n if envvar in os.environ:\n os.environ[envvar] = pwuser.pw_name\n\n except OSError:\n msg = 'Salt configured to run as user \"{0}\" but unable to switch.'\n msg = msg.format(user)\n if is_console_configured():\n log.critical(msg)\n else:\n sys.stderr.write(\"CRITICAL: {0}\\n\".format(msg))\n return False\n except KeyError:\n msg = 'User not found: \"{0}\"'.format(user)\n if is_console_configured():\n log.critical(msg)\n else:\n sys.stderr.write(\"CRITICAL: {0}\\n\".format(msg))\n return False\n return True\n",
"def verify_log(opts):\n '''\n If an insecre logging configuration is found, show a warning\n '''\n level = LOG_LEVELS.get(str(opts.get('log_level')).lower(), logging.NOTSET)\n\n if level < logging.INFO:\n log.warning('Insecure logging configuration detected! Sensitive data may be logged.')\n",
"def store_password_in_keyring(credential_id, username, password=None):\n '''\n Interactively prompts user for a password and stores it in system keyring\n '''\n try:\n # pylint: disable=import-error\n import keyring\n import keyring.errors\n # pylint: enable=import-error\n if password is None:\n prompt = 'Please enter password for {0}: '.format(credential_id)\n try:\n password = getpass.getpass(prompt)\n except EOFError:\n password = None\n\n if not password:\n # WE should raise something else here to be able to use this\n # as/from an API\n raise RuntimeError('Invalid password provided.')\n\n try:\n _save_password_in_keyring(credential_id, username, password)\n except keyring.errors.PasswordSetError as exc:\n log.debug('Problem saving password in the keyring: %s', exc)\n except ImportError:\n log.error('Tried to store password in keyring, but no keyring module is installed')\n return False\n",
"def map_providers_parallel(self, query='list_nodes', cached=False):\n '''\n Return a mapping of what named VMs are running on what VM providers\n based on what providers are defined in the configuration and VMs\n\n Same as map_providers but query in parallel.\n '''\n if cached is True and query in self.__cached_provider_queries:\n return self.__cached_provider_queries[query]\n\n opts = self.opts.copy()\n multiprocessing_data = []\n\n # Optimize Providers\n opts['providers'] = self._optimize_providers(opts['providers'])\n for alias, drivers in six.iteritems(opts['providers']):\n # Make temp query for this driver to avoid overwrite next\n this_query = query\n for driver, details in six.iteritems(drivers):\n # If driver has function list_nodes_min, just replace it\n # with query param to check existing vms on this driver\n # for minimum information, Otherwise still use query param.\n if opts.get('selected_query_option') is None and '{0}.list_nodes_min'.format(driver) in self.clouds:\n this_query = 'list_nodes_min'\n\n fun = '{0}.{1}'.format(driver, this_query)\n if fun not in self.clouds:\n log.error('Public cloud provider %s is not available', driver)\n continue\n\n multiprocessing_data.append({\n 'fun': fun,\n 'opts': opts,\n 'query': this_query,\n 'alias': alias,\n 'driver': driver\n })\n output = {}\n if not multiprocessing_data:\n return output\n\n data_count = len(multiprocessing_data)\n pool = multiprocessing.Pool(data_count < 10 and data_count or 10,\n init_pool_worker)\n parallel_pmap = enter_mainloop(_run_parallel_map_providers_query,\n multiprocessing_data,\n pool=pool)\n for alias, driver, details in parallel_pmap:\n if not details:\n # There's no providers details?! Skip it!\n continue\n if alias not in output:\n output[alias] = {}\n output[alias][driver] = details\n\n self.__cached_provider_queries[query] = output\n return output\n",
"def location_list(self, lookup='all'):\n '''\n Return a mapping of all location data for available providers\n '''\n data = {}\n\n lookups = self.lookup_providers(lookup)\n if not lookups:\n return data\n\n for alias, driver in lookups:\n fun = '{0}.avail_locations'.format(driver)\n if fun not in self.clouds:\n # The capability to gather locations is not supported by this\n # cloud module\n log.debug(\n 'The \\'%s\\' cloud driver defined under \\'%s\\' provider '\n 'alias is unable to get the locations information',\n driver, alias\n )\n continue\n\n if alias not in data:\n data[alias] = {}\n\n try:\n\n with salt.utils.context.func_globals_inject(\n self.clouds[fun],\n __active_provider_name__=':'.join([alias, driver])\n ):\n data[alias][driver] = self.clouds[fun]()\n except Exception as err:\n log.error(\n 'Failed to get the output of \\'%s()\\': %s',\n fun, err, exc_info_on_loglevel=logging.DEBUG\n )\n return data\n",
"def image_list(self, lookup='all'):\n '''\n Return a mapping of all image data for available providers\n '''\n data = {}\n\n lookups = self.lookup_providers(lookup)\n if not lookups:\n return data\n\n for alias, driver in lookups:\n fun = '{0}.avail_images'.format(driver)\n if fun not in self.clouds:\n # The capability to gather images is not supported by this\n # cloud module\n log.debug(\n 'The \\'%s\\' cloud driver defined under \\'%s\\' provider '\n 'alias is unable to get the images information',\n driver, alias\n )\n continue\n\n if alias not in data:\n data[alias] = {}\n\n try:\n with salt.utils.context.func_globals_inject(\n self.clouds[fun],\n __active_provider_name__=':'.join([alias, driver])\n ):\n data[alias][driver] = self.clouds[fun]()\n except Exception as err:\n log.error(\n 'Failed to get the output of \\'%s()\\': %s',\n fun, err, exc_info_on_loglevel=logging.DEBUG\n )\n return data\n",
"def size_list(self, lookup='all'):\n '''\n Return a mapping of all image data for available providers\n '''\n data = {}\n\n lookups = self.lookup_providers(lookup)\n if not lookups:\n return data\n\n for alias, driver in lookups:\n fun = '{0}.avail_sizes'.format(driver)\n if fun not in self.clouds:\n # The capability to gather sizes is not supported by this\n # cloud module\n log.debug(\n 'The \\'%s\\' cloud driver defined under \\'%s\\' provider '\n 'alias is unable to get the sizes information',\n driver, alias\n )\n continue\n\n if alias not in data:\n data[alias] = {}\n\n try:\n with salt.utils.context.func_globals_inject(\n self.clouds[fun],\n __active_provider_name__=':'.join([alias, driver])\n ):\n data[alias][driver] = self.clouds[fun]()\n except Exception as err:\n log.error(\n 'Failed to get the output of \\'%s()\\': %s',\n fun, err, exc_info_on_loglevel=logging.DEBUG\n )\n return data\n",
"def provider_list(self, lookup='all'):\n '''\n Return a mapping of all image data for available providers\n '''\n data = {}\n lookups = self.lookup_providers(lookup)\n if not lookups:\n return data\n\n for alias, driver in lookups:\n if alias not in data:\n data[alias] = {}\n if driver not in data[alias]:\n data[alias][driver] = {}\n return data\n",
"def profile_list(self, provider, lookup='all'):\n '''\n Return a mapping of all configured profiles\n '''\n data = {}\n lookups = self.lookup_profiles(provider, lookup)\n\n if not lookups:\n return data\n\n for alias, driver in lookups:\n if alias not in data:\n data[alias] = {}\n if driver not in data[alias]:\n data[alias][driver] = {}\n return data\n",
"def run_profile(self, profile, names, vm_overrides=None):\n '''\n Parse over the options passed on the command line and determine how to\n handle them\n '''\n if profile not in self.opts['profiles']:\n msg = 'Profile {0} is not defined'.format(profile)\n log.error(msg)\n return {'Error': msg}\n\n ret = {}\n if not vm_overrides:\n vm_overrides = {}\n\n try:\n with salt.utils.files.fopen(self.opts['conf_file'], 'r') as mcc:\n main_cloud_config = salt.utils.yaml.safe_load(mcc)\n if not main_cloud_config:\n main_cloud_config = {}\n except KeyError:\n main_cloud_config = {}\n except IOError:\n main_cloud_config = {}\n\n if main_cloud_config is None:\n main_cloud_config = {}\n\n mapped_providers = self.map_providers_parallel()\n profile_details = self.opts['profiles'][profile]\n vms = {}\n for prov, val in six.iteritems(mapped_providers):\n prov_name = next(iter(val))\n for node in mapped_providers[prov][prov_name]:\n vms[node] = mapped_providers[prov][prov_name][node]\n vms[node]['provider'] = prov\n vms[node]['driver'] = prov_name\n alias, driver = profile_details['provider'].split(':')\n\n provider_details = self.opts['providers'][alias][driver].copy()\n del provider_details['profiles']\n\n for name in names:\n if name in vms:\n prov = vms[name]['provider']\n driv = vms[name]['driver']\n msg = '{0} already exists under {1}:{2}'.format(\n name, prov, driv\n )\n log.error(msg)\n ret[name] = {'Error': msg}\n continue\n\n vm_ = self.vm_config(\n name,\n main_cloud_config,\n provider_details,\n profile_details,\n vm_overrides,\n )\n if self.opts['parallel']:\n process = multiprocessing.Process(\n target=self.create,\n args=(vm_,)\n )\n process.start()\n ret[name] = {\n 'Provisioning': 'VM being provisioned in parallel. '\n 'PID: {0}'.format(process.pid)\n }\n continue\n\n try:\n # No need to inject __active_provider_name__ into the context\n # here because self.create takes care of that\n ret[name] = self.create(vm_)\n if not ret[name]:\n ret[name] = {'Error': 'Failed to deploy VM'}\n if len(names) == 1:\n raise SaltCloudSystemExit('Failed to deploy VM')\n continue\n if self.opts.get('show_deploy_args', False) is False:\n ret[name].pop('deploy_kwargs', None)\n except (SaltCloudSystemExit, SaltCloudConfigError) as exc:\n if len(names) == 1:\n raise\n ret[name] = {'Error': str(exc)}\n\n return ret\n",
"def do_function(self, prov, func, kwargs):\n '''\n Perform a function against a cloud provider\n '''\n matches = self.lookup_providers(prov)\n if len(matches) > 1:\n raise SaltCloudSystemExit(\n 'More than one results matched \\'{0}\\'. Please specify '\n 'one of: {1}'.format(\n prov,\n ', '.join([\n '{0}:{1}'.format(alias, driver) for\n (alias, driver) in matches\n ])\n )\n )\n\n alias, driver = matches.pop()\n fun = '{0}.{1}'.format(driver, func)\n if fun not in self.clouds:\n raise SaltCloudSystemExit(\n 'The \\'{0}\\' cloud provider alias, for the \\'{1}\\' driver, does '\n 'not define the function \\'{2}\\''.format(alias, driver, func)\n )\n\n log.debug(\n 'Trying to execute \\'%s\\' with the following kwargs: %s',\n fun, kwargs\n )\n\n with salt.utils.context.func_globals_inject(\n self.clouds[fun],\n __active_provider_name__=':'.join([alias, driver])\n ):\n if kwargs:\n return {\n alias: {\n driver: self.clouds[fun](\n call='function', kwargs=kwargs\n )\n }\n }\n return {\n alias: {\n driver: self.clouds[fun](call='function')\n }\n }\n",
"def interpolated_map(self, query='list_nodes', cached=False):\n rendered_map = self.read().copy()\n interpolated_map = {}\n\n for profile, mapped_vms in six.iteritems(rendered_map):\n names = set(mapped_vms)\n if profile not in self.opts['profiles']:\n if 'Errors' not in interpolated_map:\n interpolated_map['Errors'] = {}\n msg = (\n 'No provider for the mapped \\'{0}\\' profile was found. '\n 'Skipped VMS: {1}'.format(\n profile, ', '.join(names)\n )\n )\n log.info(msg)\n interpolated_map['Errors'][profile] = msg\n continue\n\n matching = self.get_running_by_names(names, query, cached)\n for alias, drivers in six.iteritems(matching):\n for driver, vms in six.iteritems(drivers):\n for vm_name, vm_details in six.iteritems(vms):\n if alias not in interpolated_map:\n interpolated_map[alias] = {}\n if driver not in interpolated_map[alias]:\n interpolated_map[alias][driver] = {}\n interpolated_map[alias][driver][vm_name] = vm_details\n try:\n names.remove(vm_name)\n except KeyError:\n # If it's not there, then our job is already done\n pass\n\n if not names:\n continue\n\n profile_details = self.opts['profiles'][profile]\n alias, driver = profile_details['provider'].split(':')\n for vm_name in names:\n if alias not in interpolated_map:\n interpolated_map[alias] = {}\n if driver not in interpolated_map[alias]:\n interpolated_map[alias][driver] = {}\n interpolated_map[alias][driver][vm_name] = 'Absent'\n\n return interpolated_map\n",
"def handle_exception(self, msg, exc):\n if isinstance(exc, SaltCloudException):\n # It's a known exception and we know how to handle it\n if isinstance(exc, SaltCloudSystemExit):\n # This is a salt cloud system exit\n if exc.exit_code > 0:\n # the exit code is bigger than 0, it's an error\n msg = 'Error: {0}'.format(msg)\n self.exit(\n exc.exit_code,\n msg.format(exc).rstrip() + '\\n'\n )\n # It's not a system exit but it's an error we can\n # handle\n self.error(msg.format(exc))\n # This is a generic exception, log it, include traceback if\n # debug logging is enabled and exit.\n # pylint: disable=str-format-in-logging\n log.error(\n msg.format(exc),\n # Show the traceback if the debug logging level is\n # enabled\n exc_info_on_loglevel=logging.DEBUG\n )\n # pylint: enable=str-format-in-logging\n self.exit(salt.defaults.exitcodes.EX_GENERIC)\n",
"def parse_args(self, args=None, values=None):\n try:\n # Late import in order not to break setup\n from salt.cloud import libcloudfuncs\n libcloudfuncs.check_libcloud_version()\n except ImportError as exc:\n self.error(exc)\n return super(SaltCloudParser, self).parse_args(args, values)\n"
] |
class SaltCloud(salt.utils.parsers.SaltCloudParser):
def print_confirm(self, msg):
if self.options.assume_yes:
return True
print(msg)
res = input('Proceed? [N/y] ')
if not res.lower().startswith('y'):
return False
print('... proceeding')
return True
def handle_exception(self, msg, exc):
if isinstance(exc, SaltCloudException):
# It's a known exception and we know how to handle it
if isinstance(exc, SaltCloudSystemExit):
# This is a salt cloud system exit
if exc.exit_code > 0:
# the exit code is bigger than 0, it's an error
msg = 'Error: {0}'.format(msg)
self.exit(
exc.exit_code,
msg.format(exc).rstrip() + '\n'
)
# It's not a system exit but it's an error we can
# handle
self.error(msg.format(exc))
# This is a generic exception, log it, include traceback if
# debug logging is enabled and exit.
# pylint: disable=str-format-in-logging
log.error(
msg.format(exc),
# Show the traceback if the debug logging level is
# enabled
exc_info_on_loglevel=logging.DEBUG
)
# pylint: enable=str-format-in-logging
self.exit(salt.defaults.exitcodes.EX_GENERIC)
|
saltstack/salt
|
salt/states/webutil.py
|
user_exists
|
python
|
def user_exists(name, password=None, htpasswd_file=None, options='',
force=False, runas=None, update=False):
'''
Make sure the user is inside the specified htpasswd file
name
User name
password
User password
htpasswd_file
Path to the htpasswd file
options
See :mod:`salt.modules.htpasswd.useradd`
force
Touch the file even if user already created
runas
The system user to run htpasswd command with
update
Update an existing user's password if it's different from what's in
the htpasswd file (unlike force, which updates regardless)
'''
ret = {'name': name,
'changes': {},
'comment': '',
'result': None}
exists = __salt__['file.grep'](
htpasswd_file, '^{0}:'.format(name))['retcode'] == 0
# If user exists, but we're supposed to update the password, find out if
# it's changed, but not if we're forced to update the file regardless.
password_changed = False
if exists and update and not force:
password_changed = not __salt__['webutil.verify'](
htpasswd_file, name, password, opts=options, runas=runas)
if not exists or password_changed or force:
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'User \'{0}\' is set to be added to htpasswd file'.format(name)
ret['changes'] = {name: True}
return ret
useradd_ret = __salt__['webutil.useradd'](htpasswd_file, name,
password, opts=options,
runas=runas)
if useradd_ret['retcode'] == 0:
ret['result'] = True
ret['comment'] = useradd_ret['stderr']
ret['changes'] = {name: True}
return ret
else:
ret['result'] = False
ret['comment'] = useradd_ret['stderr']
return ret
if __opts__['test'] and ret['changes']:
ret['result'] = None
else:
ret['result'] = True
ret['comment'] = 'User already known'
return ret
|
Make sure the user is inside the specified htpasswd file
name
User name
password
User password
htpasswd_file
Path to the htpasswd file
options
See :mod:`salt.modules.htpasswd.useradd`
force
Touch the file even if user already created
runas
The system user to run htpasswd command with
update
Update an existing user's password if it's different from what's in
the htpasswd file (unlike force, which updates regardless)
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/webutil.py#L36-L104
| null |
# -*- coding: utf-8 -*-
'''
Support for htpasswd module. Requires the apache2-utils package for Debian-based distros.
.. versionadded:: 2014.7.0
.. code-block:: yaml
username:
webutil.user_exists:
- password: secr3t
- htpasswd_file: /etc/nginx/htpasswd
- options: d
- force: true
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
# Import Salt libs
import salt.utils.path
__virtualname__ = 'webutil'
def __virtual__():
'''
depends on webutil module
'''
return __virtualname__ if salt.utils.path.which('htpasswd') else False
def user_absent(name, htpasswd_file=None, runas=None):
'''
Make sure the user is not in the specified htpasswd file
name
User name
htpasswd_file
Path to the htpasswd file
runas
The system user to run htpasswd command with
'''
ret = {'name': name,
'changes': {},
'comment': '',
'result': None}
exists = __salt__['file.grep'](
htpasswd_file, '^{0}:'.format(name))['retcode'] == 0
if not exists:
if __opts__['test']:
ret['result'] = None
else:
ret['result'] = True
ret['comment'] = 'User already not in file'
else:
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'User \'{0}\' is set to be removed from htpasswd file'.format(name)
ret['changes'] = {name: True}
else:
userdel_ret = __salt__['webutil.userdel'](
htpasswd_file, name, runas=runas, all_results=True)
ret['result'] = userdel_ret['retcode'] == 0
ret['comment'] = userdel_ret['stderr']
if ret['result']:
ret['changes'] = {name: True}
return ret
|
saltstack/salt
|
salt/states/webutil.py
|
user_absent
|
python
|
def user_absent(name, htpasswd_file=None, runas=None):
'''
Make sure the user is not in the specified htpasswd file
name
User name
htpasswd_file
Path to the htpasswd file
runas
The system user to run htpasswd command with
'''
ret = {'name': name,
'changes': {},
'comment': '',
'result': None}
exists = __salt__['file.grep'](
htpasswd_file, '^{0}:'.format(name))['retcode'] == 0
if not exists:
if __opts__['test']:
ret['result'] = None
else:
ret['result'] = True
ret['comment'] = 'User already not in file'
else:
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'User \'{0}\' is set to be removed from htpasswd file'.format(name)
ret['changes'] = {name: True}
else:
userdel_ret = __salt__['webutil.userdel'](
htpasswd_file, name, runas=runas, all_results=True)
ret['result'] = userdel_ret['retcode'] == 0
ret['comment'] = userdel_ret['stderr']
if ret['result']:
ret['changes'] = {name: True}
return ret
|
Make sure the user is not in the specified htpasswd file
name
User name
htpasswd_file
Path to the htpasswd file
runas
The system user to run htpasswd command with
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/webutil.py#L107-L150
| null |
# -*- coding: utf-8 -*-
'''
Support for htpasswd module. Requires the apache2-utils package for Debian-based distros.
.. versionadded:: 2014.7.0
.. code-block:: yaml
username:
webutil.user_exists:
- password: secr3t
- htpasswd_file: /etc/nginx/htpasswd
- options: d
- force: true
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
# Import Salt libs
import salt.utils.path
__virtualname__ = 'webutil'
def __virtual__():
'''
depends on webutil module
'''
return __virtualname__ if salt.utils.path.which('htpasswd') else False
def user_exists(name, password=None, htpasswd_file=None, options='',
force=False, runas=None, update=False):
'''
Make sure the user is inside the specified htpasswd file
name
User name
password
User password
htpasswd_file
Path to the htpasswd file
options
See :mod:`salt.modules.htpasswd.useradd`
force
Touch the file even if user already created
runas
The system user to run htpasswd command with
update
Update an existing user's password if it's different from what's in
the htpasswd file (unlike force, which updates regardless)
'''
ret = {'name': name,
'changes': {},
'comment': '',
'result': None}
exists = __salt__['file.grep'](
htpasswd_file, '^{0}:'.format(name))['retcode'] == 0
# If user exists, but we're supposed to update the password, find out if
# it's changed, but not if we're forced to update the file regardless.
password_changed = False
if exists and update and not force:
password_changed = not __salt__['webutil.verify'](
htpasswd_file, name, password, opts=options, runas=runas)
if not exists or password_changed or force:
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'User \'{0}\' is set to be added to htpasswd file'.format(name)
ret['changes'] = {name: True}
return ret
useradd_ret = __salt__['webutil.useradd'](htpasswd_file, name,
password, opts=options,
runas=runas)
if useradd_ret['retcode'] == 0:
ret['result'] = True
ret['comment'] = useradd_ret['stderr']
ret['changes'] = {name: True}
return ret
else:
ret['result'] = False
ret['comment'] = useradd_ret['stderr']
return ret
if __opts__['test'] and ret['changes']:
ret['result'] = None
else:
ret['result'] = True
ret['comment'] = 'User already known'
return ret
|
saltstack/salt
|
salt/modules/celery.py
|
run_task
|
python
|
def run_task(task_name, args=None, kwargs=None, broker=None, backend=None, wait_for_result=False, timeout=None,
propagate=True, interval=0.5, no_ack=True, raise_timeout=True, config=None):
'''
Execute celery tasks. For celery specific parameters see celery documentation.
CLI Example:
.. code-block:: bash
salt '*' celery.run_task tasks.sleep args=[4] broker=redis://localhost \\
backend=redis://localhost wait_for_result=true
task_name
The task name, e.g. tasks.sleep
args
Task arguments as a list
kwargs
Task keyword arguments
broker
Broker for celeryapp, see celery documentation
backend
Result backend for celeryapp, see celery documentation
wait_for_result
Wait until task result is read from result backend and return result, Default: False
timeout
Timeout waiting for result from celery, see celery AsyncResult.get documentation
propagate
Propagate exceptions from celery task, see celery AsyncResult.get documentation, Default: True
interval
Interval to check for task result, see celery AsyncResult.get documentation, Default: 0.5
no_ack
see celery AsyncResult.get documentation. Default: True
raise_timeout
Raise timeout exception if waiting for task result times out. Default: False
config
Config dict for celery app, See celery documentation
'''
if not broker:
raise SaltInvocationError('broker parameter is required')
with Celery(broker=broker, backend=backend, set_as_current=False) as app:
if config:
app.conf.update(config)
with app.connection():
args = args or []
kwargs = kwargs or {}
async_result = app.send_task(task_name, args=args, kwargs=kwargs)
if wait_for_result:
try:
return async_result.get(timeout=timeout, propagate=propagate,
interval=interval, no_ack=no_ack)
except TimeoutError as ex:
log.error('Waiting for the result of a celery task execution timed out.')
if raise_timeout:
raise ex
return False
|
Execute celery tasks. For celery specific parameters see celery documentation.
CLI Example:
.. code-block:: bash
salt '*' celery.run_task tasks.sleep args=[4] broker=redis://localhost \\
backend=redis://localhost wait_for_result=true
task_name
The task name, e.g. tasks.sleep
args
Task arguments as a list
kwargs
Task keyword arguments
broker
Broker for celeryapp, see celery documentation
backend
Result backend for celeryapp, see celery documentation
wait_for_result
Wait until task result is read from result backend and return result, Default: False
timeout
Timeout waiting for result from celery, see celery AsyncResult.get documentation
propagate
Propagate exceptions from celery task, see celery AsyncResult.get documentation, Default: True
interval
Interval to check for task result, see celery AsyncResult.get documentation, Default: 0.5
no_ack
see celery AsyncResult.get documentation. Default: True
raise_timeout
Raise timeout exception if waiting for task result times out. Default: False
config
Config dict for celery app, See celery documentation
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/celery.py#L40-L110
| null |
# -*- coding: utf-8 -*-
'''
Support for scheduling celery tasks. The worker is independent of salt and thus can run in a different
virtualenv or on a different python version, as long as broker, backend and serializer configurations match.
Also note that celery and packages required by the celery broker, e.g. redis must be installed to load
the salt celery execution module.
.. note::
A new app (and thus new connections) is created for each task execution
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import logging
# Import salt libs
from salt.exceptions import SaltInvocationError
log = logging.getLogger(__name__)
# Import third party libs
try:
from celery import Celery
from celery.exceptions import TimeoutError
HAS_CELERY = True
except ImportError:
HAS_CELERY = False
def __virtual__():
'''
Only load if celery libraries exist.
'''
if not HAS_CELERY:
return False, 'The celery module could not be loaded: celery library not found'
return True
|
saltstack/salt
|
salt/client/api.py
|
APIClient.run
|
python
|
def run(self, cmd):
'''
Execute the salt command given by cmd dict.
cmd is a dictionary of the following form:
{
'mode': 'modestring',
'fun' : 'modulefunctionstring',
'kwarg': functionkeywordargdictionary,
'tgt' : 'targetpatternstring',
'tgt_type' : 'targetpatterntype',
'ret' : 'returner namestring',
'timeout': 'functiontimeout',
'arg' : 'functionpositionalarg sequence',
'token': 'salttokenstring',
'username': 'usernamestring',
'password': 'passwordstring',
'eauth': 'eauthtypestring',
}
Implied by the fun is which client is used to run the command, that is, either
the master local minion client, the master runner client, or the master wheel client.
The cmd dict items are as follows:
mode: either 'sync' or 'asynchronous'. Defaults to 'asynchronous' if missing
fun: required. If the function is to be run on the master using either
a wheel or runner client then the fun: includes either
'wheel.' or 'runner.' as a prefix and has three parts separated by '.'.
Otherwise the fun: specifies a module to be run on a minion via the local
minion client.
Example:
fun of 'wheel.config.values' run with master wheel client
fun of 'runner.manage.status' run with master runner client
fun of 'test.ping' run with local minion client
fun of 'wheel.foobar' run with with local minion client not wheel
kwarg: A dictionary of keyword function parameters to be passed to the eventual
salt function specified by fun:
tgt: Pattern string specifying the targeted minions when the implied client is local
tgt_type: Optional target pattern type string when client is local minion.
Defaults to 'glob' if missing
ret: Optional name string of returner when local minion client.
arg: Optional positional argument string when local minion client
token: the salt token. Either token: is required or the set of username:,
password: , and eauth:
username: the salt username. Required if token is missing.
password: the user's password. Required if token is missing.
eauth: the authentication type such as 'pam' or 'ldap'. Required if token is missing
'''
cmd = dict(cmd) # make copy
client = 'minion' # default to local minion client
mode = cmd.get('mode', 'async')
# check for wheel or runner prefix to fun name to use wheel or runner client
funparts = cmd.get('fun', '').split('.')
if len(funparts) > 2 and funparts[0] in ['wheel', 'runner']: # master
client = funparts[0]
cmd['fun'] = '.'.join(funparts[1:]) # strip prefix
if not ('token' in cmd or
('eauth' in cmd and 'password' in cmd and 'username' in cmd)):
raise EauthAuthenticationError('No authentication credentials given')
executor = getattr(self, '{0}_{1}'.format(client, mode))
result = executor(**cmd)
return result
|
Execute the salt command given by cmd dict.
cmd is a dictionary of the following form:
{
'mode': 'modestring',
'fun' : 'modulefunctionstring',
'kwarg': functionkeywordargdictionary,
'tgt' : 'targetpatternstring',
'tgt_type' : 'targetpatterntype',
'ret' : 'returner namestring',
'timeout': 'functiontimeout',
'arg' : 'functionpositionalarg sequence',
'token': 'salttokenstring',
'username': 'usernamestring',
'password': 'passwordstring',
'eauth': 'eauthtypestring',
}
Implied by the fun is which client is used to run the command, that is, either
the master local minion client, the master runner client, or the master wheel client.
The cmd dict items are as follows:
mode: either 'sync' or 'asynchronous'. Defaults to 'asynchronous' if missing
fun: required. If the function is to be run on the master using either
a wheel or runner client then the fun: includes either
'wheel.' or 'runner.' as a prefix and has three parts separated by '.'.
Otherwise the fun: specifies a module to be run on a minion via the local
minion client.
Example:
fun of 'wheel.config.values' run with master wheel client
fun of 'runner.manage.status' run with master runner client
fun of 'test.ping' run with local minion client
fun of 'wheel.foobar' run with with local minion client not wheel
kwarg: A dictionary of keyword function parameters to be passed to the eventual
salt function specified by fun:
tgt: Pattern string specifying the targeted minions when the implied client is local
tgt_type: Optional target pattern type string when client is local minion.
Defaults to 'glob' if missing
ret: Optional name string of returner when local minion client.
arg: Optional positional argument string when local minion client
token: the salt token. Either token: is required or the set of username:,
password: , and eauth:
username: the salt username. Required if token is missing.
password: the user's password. Required if token is missing.
eauth: the authentication type such as 'pam' or 'ldap'. Required if token is missing
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/client/api.py#L70-L137
| null |
class APIClient(object):
'''
Provide a uniform method of accessing the various client interfaces in Salt
in the form of low-data data structures. For example:
'''
def __init__(self, opts=None, listen=True):
if not opts:
opts = salt.config.client_config(
os.environ.get(
'SALT_MASTER_CONFIG',
os.path.join(syspaths.CONFIG_DIR, 'master')
)
)
self.opts = opts
self.localClient = salt.client.get_local_client(self.opts['conf_file'])
self.runnerClient = salt.runner.RunnerClient(self.opts)
self.wheelClient = salt.wheel.Wheel(self.opts)
self.resolver = salt.auth.Resolver(self.opts)
self.event = salt.utils.event.get_event(
'master',
self.opts['sock_dir'],
self.opts['transport'],
opts=self.opts,
listen=listen)
def minion_async(self, **kwargs):
'''
Wrap LocalClient for running :ref:`execution modules <all-salt.modules>`
and immediately return the job ID. The results of the job can then be
retrieved at a later time.
.. seealso:: :ref:`python-api`
'''
return self.localClient.run_job(**kwargs)
def minion_sync(self, **kwargs):
'''
Wrap LocalClient for running :ref:`execution modules <all-salt.modules>`
.. seealso:: :ref:`python-api`
'''
return self.localClient.cmd(**kwargs)
def runner_async(self, **kwargs):
'''
Wrap RunnerClient for executing :ref:`runner modules <all-salt.runners>`
Expects that one of the kwargs is key 'fun' whose value is the namestring
of the function to call
'''
return self.runnerClient.master_call(**kwargs)
runner_sync = runner_async # always runner asynchronous, so works in either mode
def wheel_sync(self, **kwargs):
'''
Wrap Wheel to enable executing :ref:`wheel modules <all-salt.wheel>`
Expects that one of the kwargs is key 'fun' whose value is the namestring
of the function to call
'''
return self.wheelClient.master_call(**kwargs)
wheel_async = wheel_sync # always wheel_sync, so it works either mode
def signature(self, cmd):
'''
Convenience function that returns dict of function signature(s) specified by cmd.
cmd is dict of the form:
{
'module' : 'modulestring',
'tgt' : 'targetpatternstring',
'tgt_type' : 'targetpatterntype',
'token': 'salttokenstring',
'username': 'usernamestring',
'password': 'passwordstring',
'eauth': 'eauthtypestring',
}
The cmd dict items are as follows:
module: required. This is either a module or module function name for
the specified client.
tgt: Optional pattern string specifying the targeted minions when client
is 'minion'
tgt_type: Optional target pattern type string when client is 'minion'.
Example: 'glob' defaults to 'glob' if missing
token: the salt token. Either token: is required or the set of username:,
password: , and eauth:
username: the salt username. Required if token is missing.
password: the user's password. Required if token is missing.
eauth: the authentication type such as 'pam' or 'ldap'. Required if token is missing
Adds client per the command.
'''
cmd['client'] = 'minion'
if len(cmd['module'].split('.')) > 2 and cmd['module'].split('.')[0] in ['runner', 'wheel']:
cmd['client'] = 'master'
return self._signature(cmd)
def _signature(self, cmd):
'''
Expects everything that signature does and also a client type string.
client can either be master or minion.
'''
result = {}
client = cmd.get('client', 'minion')
if client == 'minion':
cmd['fun'] = 'sys.argspec'
cmd['kwarg'] = dict(module=cmd['module'])
result = self.run(cmd)
elif client == 'master':
parts = cmd['module'].split('.')
client = parts[0]
module = '.'.join(parts[1:]) # strip prefix
if client == 'wheel':
functions = self.wheelClient.functions
elif client == 'runner':
functions = self.runnerClient.functions
result = {'master': salt.utils.args.argspec_report(functions, module)}
return result
def create_token(self, creds):
'''
Create token with creds.
Token authorizes salt access if successful authentication
with the credentials in creds.
creds format is as follows:
{
'username': 'namestring',
'password': 'passwordstring',
'eauth': 'eauthtypestring',
}
examples of valid eauth type strings: 'pam' or 'ldap'
Returns dictionary of token information with the following format:
{
'token': 'tokenstring',
'start': starttimeinfractionalseconds,
'expire': expiretimeinfractionalseconds,
'name': 'usernamestring',
'user': 'usernamestring',
'username': 'usernamestring',
'eauth': 'eauthtypestring',
'perms: permslistofstrings,
}
The perms list provides those parts of salt for which the user is authorised
to execute.
example perms list:
[
"grains.*",
"status.*",
"sys.*",
"test.*"
]
'''
try:
tokenage = self.resolver.mk_token(creds)
except Exception as ex:
raise EauthAuthenticationError(
"Authentication failed with {0}.".format(repr(ex)))
if 'token' not in tokenage:
raise EauthAuthenticationError("Authentication failed with provided credentials.")
# Grab eauth config for the current backend for the current user
tokenage_eauth = self.opts['external_auth'][tokenage['eauth']]
if tokenage['name'] in tokenage_eauth:
tokenage['perms'] = tokenage_eauth[tokenage['name']]
else:
tokenage['perms'] = tokenage_eauth['*']
tokenage['user'] = tokenage['name']
tokenage['username'] = tokenage['name']
return tokenage
def verify_token(self, token):
'''
If token is valid Then returns user name associated with token
Else False.
'''
try:
result = self.resolver.get_token(token)
except Exception as ex:
raise EauthAuthenticationError(
"Token validation failed with {0}.".format(repr(ex)))
return result
def get_event(self, wait=0.25, tag='', full=False):
'''
Get a single salt event.
If no events are available, then block for up to ``wait`` seconds.
Return the event if it matches the tag (or ``tag`` is empty)
Otherwise return None
If wait is 0 then block forever or until next event becomes available.
'''
return self.event.get_event(wait=wait, tag=tag, full=full, auto_reconnect=True)
def fire_event(self, data, tag):
'''
fires event with data and tag
This only works if api is running with same user permissions as master
Need to convert this to a master call with appropriate authentication
'''
return self.event.fire_event(data, salt.utils.event.tagify(tag, 'wui'))
|
saltstack/salt
|
salt/client/api.py
|
APIClient.signature
|
python
|
def signature(self, cmd):
'''
Convenience function that returns dict of function signature(s) specified by cmd.
cmd is dict of the form:
{
'module' : 'modulestring',
'tgt' : 'targetpatternstring',
'tgt_type' : 'targetpatterntype',
'token': 'salttokenstring',
'username': 'usernamestring',
'password': 'passwordstring',
'eauth': 'eauthtypestring',
}
The cmd dict items are as follows:
module: required. This is either a module or module function name for
the specified client.
tgt: Optional pattern string specifying the targeted minions when client
is 'minion'
tgt_type: Optional target pattern type string when client is 'minion'.
Example: 'glob' defaults to 'glob' if missing
token: the salt token. Either token: is required or the set of username:,
password: , and eauth:
username: the salt username. Required if token is missing.
password: the user's password. Required if token is missing.
eauth: the authentication type such as 'pam' or 'ldap'. Required if token is missing
Adds client per the command.
'''
cmd['client'] = 'minion'
if len(cmd['module'].split('.')) > 2 and cmd['module'].split('.')[0] in ['runner', 'wheel']:
cmd['client'] = 'master'
return self._signature(cmd)
|
Convenience function that returns dict of function signature(s) specified by cmd.
cmd is dict of the form:
{
'module' : 'modulestring',
'tgt' : 'targetpatternstring',
'tgt_type' : 'targetpatterntype',
'token': 'salttokenstring',
'username': 'usernamestring',
'password': 'passwordstring',
'eauth': 'eauthtypestring',
}
The cmd dict items are as follows:
module: required. This is either a module or module function name for
the specified client.
tgt: Optional pattern string specifying the targeted minions when client
is 'minion'
tgt_type: Optional target pattern type string when client is 'minion'.
Example: 'glob' defaults to 'glob' if missing
token: the salt token. Either token: is required or the set of username:,
password: , and eauth:
username: the salt username. Required if token is missing.
password: the user's password. Required if token is missing.
eauth: the authentication type such as 'pam' or 'ldap'. Required if token is missing
Adds client per the command.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/client/api.py#L177-L211
|
[
"def _signature(self, cmd):\n '''\n Expects everything that signature does and also a client type string.\n client can either be master or minion.\n '''\n result = {}\n\n client = cmd.get('client', 'minion')\n if client == 'minion':\n cmd['fun'] = 'sys.argspec'\n cmd['kwarg'] = dict(module=cmd['module'])\n result = self.run(cmd)\n elif client == 'master':\n parts = cmd['module'].split('.')\n client = parts[0]\n module = '.'.join(parts[1:]) # strip prefix\n if client == 'wheel':\n functions = self.wheelClient.functions\n elif client == 'runner':\n functions = self.runnerClient.functions\n result = {'master': salt.utils.args.argspec_report(functions, module)}\n return result\n"
] |
class APIClient(object):
'''
Provide a uniform method of accessing the various client interfaces in Salt
in the form of low-data data structures. For example:
'''
def __init__(self, opts=None, listen=True):
if not opts:
opts = salt.config.client_config(
os.environ.get(
'SALT_MASTER_CONFIG',
os.path.join(syspaths.CONFIG_DIR, 'master')
)
)
self.opts = opts
self.localClient = salt.client.get_local_client(self.opts['conf_file'])
self.runnerClient = salt.runner.RunnerClient(self.opts)
self.wheelClient = salt.wheel.Wheel(self.opts)
self.resolver = salt.auth.Resolver(self.opts)
self.event = salt.utils.event.get_event(
'master',
self.opts['sock_dir'],
self.opts['transport'],
opts=self.opts,
listen=listen)
def run(self, cmd):
'''
Execute the salt command given by cmd dict.
cmd is a dictionary of the following form:
{
'mode': 'modestring',
'fun' : 'modulefunctionstring',
'kwarg': functionkeywordargdictionary,
'tgt' : 'targetpatternstring',
'tgt_type' : 'targetpatterntype',
'ret' : 'returner namestring',
'timeout': 'functiontimeout',
'arg' : 'functionpositionalarg sequence',
'token': 'salttokenstring',
'username': 'usernamestring',
'password': 'passwordstring',
'eauth': 'eauthtypestring',
}
Implied by the fun is which client is used to run the command, that is, either
the master local minion client, the master runner client, or the master wheel client.
The cmd dict items are as follows:
mode: either 'sync' or 'asynchronous'. Defaults to 'asynchronous' if missing
fun: required. If the function is to be run on the master using either
a wheel or runner client then the fun: includes either
'wheel.' or 'runner.' as a prefix and has three parts separated by '.'.
Otherwise the fun: specifies a module to be run on a minion via the local
minion client.
Example:
fun of 'wheel.config.values' run with master wheel client
fun of 'runner.manage.status' run with master runner client
fun of 'test.ping' run with local minion client
fun of 'wheel.foobar' run with with local minion client not wheel
kwarg: A dictionary of keyword function parameters to be passed to the eventual
salt function specified by fun:
tgt: Pattern string specifying the targeted minions when the implied client is local
tgt_type: Optional target pattern type string when client is local minion.
Defaults to 'glob' if missing
ret: Optional name string of returner when local minion client.
arg: Optional positional argument string when local minion client
token: the salt token. Either token: is required or the set of username:,
password: , and eauth:
username: the salt username. Required if token is missing.
password: the user's password. Required if token is missing.
eauth: the authentication type such as 'pam' or 'ldap'. Required if token is missing
'''
cmd = dict(cmd) # make copy
client = 'minion' # default to local minion client
mode = cmd.get('mode', 'async')
# check for wheel or runner prefix to fun name to use wheel or runner client
funparts = cmd.get('fun', '').split('.')
if len(funparts) > 2 and funparts[0] in ['wheel', 'runner']: # master
client = funparts[0]
cmd['fun'] = '.'.join(funparts[1:]) # strip prefix
if not ('token' in cmd or
('eauth' in cmd and 'password' in cmd and 'username' in cmd)):
raise EauthAuthenticationError('No authentication credentials given')
executor = getattr(self, '{0}_{1}'.format(client, mode))
result = executor(**cmd)
return result
def minion_async(self, **kwargs):
'''
Wrap LocalClient for running :ref:`execution modules <all-salt.modules>`
and immediately return the job ID. The results of the job can then be
retrieved at a later time.
.. seealso:: :ref:`python-api`
'''
return self.localClient.run_job(**kwargs)
def minion_sync(self, **kwargs):
'''
Wrap LocalClient for running :ref:`execution modules <all-salt.modules>`
.. seealso:: :ref:`python-api`
'''
return self.localClient.cmd(**kwargs)
def runner_async(self, **kwargs):
'''
Wrap RunnerClient for executing :ref:`runner modules <all-salt.runners>`
Expects that one of the kwargs is key 'fun' whose value is the namestring
of the function to call
'''
return self.runnerClient.master_call(**kwargs)
runner_sync = runner_async # always runner asynchronous, so works in either mode
def wheel_sync(self, **kwargs):
'''
Wrap Wheel to enable executing :ref:`wheel modules <all-salt.wheel>`
Expects that one of the kwargs is key 'fun' whose value is the namestring
of the function to call
'''
return self.wheelClient.master_call(**kwargs)
wheel_async = wheel_sync # always wheel_sync, so it works either mode
def _signature(self, cmd):
'''
Expects everything that signature does and also a client type string.
client can either be master or minion.
'''
result = {}
client = cmd.get('client', 'minion')
if client == 'minion':
cmd['fun'] = 'sys.argspec'
cmd['kwarg'] = dict(module=cmd['module'])
result = self.run(cmd)
elif client == 'master':
parts = cmd['module'].split('.')
client = parts[0]
module = '.'.join(parts[1:]) # strip prefix
if client == 'wheel':
functions = self.wheelClient.functions
elif client == 'runner':
functions = self.runnerClient.functions
result = {'master': salt.utils.args.argspec_report(functions, module)}
return result
def create_token(self, creds):
'''
Create token with creds.
Token authorizes salt access if successful authentication
with the credentials in creds.
creds format is as follows:
{
'username': 'namestring',
'password': 'passwordstring',
'eauth': 'eauthtypestring',
}
examples of valid eauth type strings: 'pam' or 'ldap'
Returns dictionary of token information with the following format:
{
'token': 'tokenstring',
'start': starttimeinfractionalseconds,
'expire': expiretimeinfractionalseconds,
'name': 'usernamestring',
'user': 'usernamestring',
'username': 'usernamestring',
'eauth': 'eauthtypestring',
'perms: permslistofstrings,
}
The perms list provides those parts of salt for which the user is authorised
to execute.
example perms list:
[
"grains.*",
"status.*",
"sys.*",
"test.*"
]
'''
try:
tokenage = self.resolver.mk_token(creds)
except Exception as ex:
raise EauthAuthenticationError(
"Authentication failed with {0}.".format(repr(ex)))
if 'token' not in tokenage:
raise EauthAuthenticationError("Authentication failed with provided credentials.")
# Grab eauth config for the current backend for the current user
tokenage_eauth = self.opts['external_auth'][tokenage['eauth']]
if tokenage['name'] in tokenage_eauth:
tokenage['perms'] = tokenage_eauth[tokenage['name']]
else:
tokenage['perms'] = tokenage_eauth['*']
tokenage['user'] = tokenage['name']
tokenage['username'] = tokenage['name']
return tokenage
def verify_token(self, token):
'''
If token is valid Then returns user name associated with token
Else False.
'''
try:
result = self.resolver.get_token(token)
except Exception as ex:
raise EauthAuthenticationError(
"Token validation failed with {0}.".format(repr(ex)))
return result
def get_event(self, wait=0.25, tag='', full=False):
'''
Get a single salt event.
If no events are available, then block for up to ``wait`` seconds.
Return the event if it matches the tag (or ``tag`` is empty)
Otherwise return None
If wait is 0 then block forever or until next event becomes available.
'''
return self.event.get_event(wait=wait, tag=tag, full=full, auto_reconnect=True)
def fire_event(self, data, tag):
'''
fires event with data and tag
This only works if api is running with same user permissions as master
Need to convert this to a master call with appropriate authentication
'''
return self.event.fire_event(data, salt.utils.event.tagify(tag, 'wui'))
|
saltstack/salt
|
salt/client/api.py
|
APIClient._signature
|
python
|
def _signature(self, cmd):
'''
Expects everything that signature does and also a client type string.
client can either be master or minion.
'''
result = {}
client = cmd.get('client', 'minion')
if client == 'minion':
cmd['fun'] = 'sys.argspec'
cmd['kwarg'] = dict(module=cmd['module'])
result = self.run(cmd)
elif client == 'master':
parts = cmd['module'].split('.')
client = parts[0]
module = '.'.join(parts[1:]) # strip prefix
if client == 'wheel':
functions = self.wheelClient.functions
elif client == 'runner':
functions = self.runnerClient.functions
result = {'master': salt.utils.args.argspec_report(functions, module)}
return result
|
Expects everything that signature does and also a client type string.
client can either be master or minion.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/client/api.py#L213-L234
| null |
class APIClient(object):
'''
Provide a uniform method of accessing the various client interfaces in Salt
in the form of low-data data structures. For example:
'''
def __init__(self, opts=None, listen=True):
if not opts:
opts = salt.config.client_config(
os.environ.get(
'SALT_MASTER_CONFIG',
os.path.join(syspaths.CONFIG_DIR, 'master')
)
)
self.opts = opts
self.localClient = salt.client.get_local_client(self.opts['conf_file'])
self.runnerClient = salt.runner.RunnerClient(self.opts)
self.wheelClient = salt.wheel.Wheel(self.opts)
self.resolver = salt.auth.Resolver(self.opts)
self.event = salt.utils.event.get_event(
'master',
self.opts['sock_dir'],
self.opts['transport'],
opts=self.opts,
listen=listen)
def run(self, cmd):
'''
Execute the salt command given by cmd dict.
cmd is a dictionary of the following form:
{
'mode': 'modestring',
'fun' : 'modulefunctionstring',
'kwarg': functionkeywordargdictionary,
'tgt' : 'targetpatternstring',
'tgt_type' : 'targetpatterntype',
'ret' : 'returner namestring',
'timeout': 'functiontimeout',
'arg' : 'functionpositionalarg sequence',
'token': 'salttokenstring',
'username': 'usernamestring',
'password': 'passwordstring',
'eauth': 'eauthtypestring',
}
Implied by the fun is which client is used to run the command, that is, either
the master local minion client, the master runner client, or the master wheel client.
The cmd dict items are as follows:
mode: either 'sync' or 'asynchronous'. Defaults to 'asynchronous' if missing
fun: required. If the function is to be run on the master using either
a wheel or runner client then the fun: includes either
'wheel.' or 'runner.' as a prefix and has three parts separated by '.'.
Otherwise the fun: specifies a module to be run on a minion via the local
minion client.
Example:
fun of 'wheel.config.values' run with master wheel client
fun of 'runner.manage.status' run with master runner client
fun of 'test.ping' run with local minion client
fun of 'wheel.foobar' run with with local minion client not wheel
kwarg: A dictionary of keyword function parameters to be passed to the eventual
salt function specified by fun:
tgt: Pattern string specifying the targeted minions when the implied client is local
tgt_type: Optional target pattern type string when client is local minion.
Defaults to 'glob' if missing
ret: Optional name string of returner when local minion client.
arg: Optional positional argument string when local minion client
token: the salt token. Either token: is required or the set of username:,
password: , and eauth:
username: the salt username. Required if token is missing.
password: the user's password. Required if token is missing.
eauth: the authentication type such as 'pam' or 'ldap'. Required if token is missing
'''
cmd = dict(cmd) # make copy
client = 'minion' # default to local minion client
mode = cmd.get('mode', 'async')
# check for wheel or runner prefix to fun name to use wheel or runner client
funparts = cmd.get('fun', '').split('.')
if len(funparts) > 2 and funparts[0] in ['wheel', 'runner']: # master
client = funparts[0]
cmd['fun'] = '.'.join(funparts[1:]) # strip prefix
if not ('token' in cmd or
('eauth' in cmd and 'password' in cmd and 'username' in cmd)):
raise EauthAuthenticationError('No authentication credentials given')
executor = getattr(self, '{0}_{1}'.format(client, mode))
result = executor(**cmd)
return result
def minion_async(self, **kwargs):
'''
Wrap LocalClient for running :ref:`execution modules <all-salt.modules>`
and immediately return the job ID. The results of the job can then be
retrieved at a later time.
.. seealso:: :ref:`python-api`
'''
return self.localClient.run_job(**kwargs)
def minion_sync(self, **kwargs):
'''
Wrap LocalClient for running :ref:`execution modules <all-salt.modules>`
.. seealso:: :ref:`python-api`
'''
return self.localClient.cmd(**kwargs)
def runner_async(self, **kwargs):
'''
Wrap RunnerClient for executing :ref:`runner modules <all-salt.runners>`
Expects that one of the kwargs is key 'fun' whose value is the namestring
of the function to call
'''
return self.runnerClient.master_call(**kwargs)
runner_sync = runner_async # always runner asynchronous, so works in either mode
def wheel_sync(self, **kwargs):
'''
Wrap Wheel to enable executing :ref:`wheel modules <all-salt.wheel>`
Expects that one of the kwargs is key 'fun' whose value is the namestring
of the function to call
'''
return self.wheelClient.master_call(**kwargs)
wheel_async = wheel_sync # always wheel_sync, so it works either mode
def signature(self, cmd):
'''
Convenience function that returns dict of function signature(s) specified by cmd.
cmd is dict of the form:
{
'module' : 'modulestring',
'tgt' : 'targetpatternstring',
'tgt_type' : 'targetpatterntype',
'token': 'salttokenstring',
'username': 'usernamestring',
'password': 'passwordstring',
'eauth': 'eauthtypestring',
}
The cmd dict items are as follows:
module: required. This is either a module or module function name for
the specified client.
tgt: Optional pattern string specifying the targeted minions when client
is 'minion'
tgt_type: Optional target pattern type string when client is 'minion'.
Example: 'glob' defaults to 'glob' if missing
token: the salt token. Either token: is required or the set of username:,
password: , and eauth:
username: the salt username. Required if token is missing.
password: the user's password. Required if token is missing.
eauth: the authentication type such as 'pam' or 'ldap'. Required if token is missing
Adds client per the command.
'''
cmd['client'] = 'minion'
if len(cmd['module'].split('.')) > 2 and cmd['module'].split('.')[0] in ['runner', 'wheel']:
cmd['client'] = 'master'
return self._signature(cmd)
def create_token(self, creds):
'''
Create token with creds.
Token authorizes salt access if successful authentication
with the credentials in creds.
creds format is as follows:
{
'username': 'namestring',
'password': 'passwordstring',
'eauth': 'eauthtypestring',
}
examples of valid eauth type strings: 'pam' or 'ldap'
Returns dictionary of token information with the following format:
{
'token': 'tokenstring',
'start': starttimeinfractionalseconds,
'expire': expiretimeinfractionalseconds,
'name': 'usernamestring',
'user': 'usernamestring',
'username': 'usernamestring',
'eauth': 'eauthtypestring',
'perms: permslistofstrings,
}
The perms list provides those parts of salt for which the user is authorised
to execute.
example perms list:
[
"grains.*",
"status.*",
"sys.*",
"test.*"
]
'''
try:
tokenage = self.resolver.mk_token(creds)
except Exception as ex:
raise EauthAuthenticationError(
"Authentication failed with {0}.".format(repr(ex)))
if 'token' not in tokenage:
raise EauthAuthenticationError("Authentication failed with provided credentials.")
# Grab eauth config for the current backend for the current user
tokenage_eauth = self.opts['external_auth'][tokenage['eauth']]
if tokenage['name'] in tokenage_eauth:
tokenage['perms'] = tokenage_eauth[tokenage['name']]
else:
tokenage['perms'] = tokenage_eauth['*']
tokenage['user'] = tokenage['name']
tokenage['username'] = tokenage['name']
return tokenage
def verify_token(self, token):
'''
If token is valid Then returns user name associated with token
Else False.
'''
try:
result = self.resolver.get_token(token)
except Exception as ex:
raise EauthAuthenticationError(
"Token validation failed with {0}.".format(repr(ex)))
return result
def get_event(self, wait=0.25, tag='', full=False):
'''
Get a single salt event.
If no events are available, then block for up to ``wait`` seconds.
Return the event if it matches the tag (or ``tag`` is empty)
Otherwise return None
If wait is 0 then block forever or until next event becomes available.
'''
return self.event.get_event(wait=wait, tag=tag, full=full, auto_reconnect=True)
def fire_event(self, data, tag):
'''
fires event with data and tag
This only works if api is running with same user permissions as master
Need to convert this to a master call with appropriate authentication
'''
return self.event.fire_event(data, salt.utils.event.tagify(tag, 'wui'))
|
saltstack/salt
|
salt/client/api.py
|
APIClient.create_token
|
python
|
def create_token(self, creds):
'''
Create token with creds.
Token authorizes salt access if successful authentication
with the credentials in creds.
creds format is as follows:
{
'username': 'namestring',
'password': 'passwordstring',
'eauth': 'eauthtypestring',
}
examples of valid eauth type strings: 'pam' or 'ldap'
Returns dictionary of token information with the following format:
{
'token': 'tokenstring',
'start': starttimeinfractionalseconds,
'expire': expiretimeinfractionalseconds,
'name': 'usernamestring',
'user': 'usernamestring',
'username': 'usernamestring',
'eauth': 'eauthtypestring',
'perms: permslistofstrings,
}
The perms list provides those parts of salt for which the user is authorised
to execute.
example perms list:
[
"grains.*",
"status.*",
"sys.*",
"test.*"
]
'''
try:
tokenage = self.resolver.mk_token(creds)
except Exception as ex:
raise EauthAuthenticationError(
"Authentication failed with {0}.".format(repr(ex)))
if 'token' not in tokenage:
raise EauthAuthenticationError("Authentication failed with provided credentials.")
# Grab eauth config for the current backend for the current user
tokenage_eauth = self.opts['external_auth'][tokenage['eauth']]
if tokenage['name'] in tokenage_eauth:
tokenage['perms'] = tokenage_eauth[tokenage['name']]
else:
tokenage['perms'] = tokenage_eauth['*']
tokenage['user'] = tokenage['name']
tokenage['username'] = tokenage['name']
return tokenage
|
Create token with creds.
Token authorizes salt access if successful authentication
with the credentials in creds.
creds format is as follows:
{
'username': 'namestring',
'password': 'passwordstring',
'eauth': 'eauthtypestring',
}
examples of valid eauth type strings: 'pam' or 'ldap'
Returns dictionary of token information with the following format:
{
'token': 'tokenstring',
'start': starttimeinfractionalseconds,
'expire': expiretimeinfractionalseconds,
'name': 'usernamestring',
'user': 'usernamestring',
'username': 'usernamestring',
'eauth': 'eauthtypestring',
'perms: permslistofstrings,
}
The perms list provides those parts of salt for which the user is authorised
to execute.
example perms list:
[
"grains.*",
"status.*",
"sys.*",
"test.*"
]
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/client/api.py#L236-L293
| null |
class APIClient(object):
'''
Provide a uniform method of accessing the various client interfaces in Salt
in the form of low-data data structures. For example:
'''
def __init__(self, opts=None, listen=True):
if not opts:
opts = salt.config.client_config(
os.environ.get(
'SALT_MASTER_CONFIG',
os.path.join(syspaths.CONFIG_DIR, 'master')
)
)
self.opts = opts
self.localClient = salt.client.get_local_client(self.opts['conf_file'])
self.runnerClient = salt.runner.RunnerClient(self.opts)
self.wheelClient = salt.wheel.Wheel(self.opts)
self.resolver = salt.auth.Resolver(self.opts)
self.event = salt.utils.event.get_event(
'master',
self.opts['sock_dir'],
self.opts['transport'],
opts=self.opts,
listen=listen)
def run(self, cmd):
'''
Execute the salt command given by cmd dict.
cmd is a dictionary of the following form:
{
'mode': 'modestring',
'fun' : 'modulefunctionstring',
'kwarg': functionkeywordargdictionary,
'tgt' : 'targetpatternstring',
'tgt_type' : 'targetpatterntype',
'ret' : 'returner namestring',
'timeout': 'functiontimeout',
'arg' : 'functionpositionalarg sequence',
'token': 'salttokenstring',
'username': 'usernamestring',
'password': 'passwordstring',
'eauth': 'eauthtypestring',
}
Implied by the fun is which client is used to run the command, that is, either
the master local minion client, the master runner client, or the master wheel client.
The cmd dict items are as follows:
mode: either 'sync' or 'asynchronous'. Defaults to 'asynchronous' if missing
fun: required. If the function is to be run on the master using either
a wheel or runner client then the fun: includes either
'wheel.' or 'runner.' as a prefix and has three parts separated by '.'.
Otherwise the fun: specifies a module to be run on a minion via the local
minion client.
Example:
fun of 'wheel.config.values' run with master wheel client
fun of 'runner.manage.status' run with master runner client
fun of 'test.ping' run with local minion client
fun of 'wheel.foobar' run with with local minion client not wheel
kwarg: A dictionary of keyword function parameters to be passed to the eventual
salt function specified by fun:
tgt: Pattern string specifying the targeted minions when the implied client is local
tgt_type: Optional target pattern type string when client is local minion.
Defaults to 'glob' if missing
ret: Optional name string of returner when local minion client.
arg: Optional positional argument string when local minion client
token: the salt token. Either token: is required or the set of username:,
password: , and eauth:
username: the salt username. Required if token is missing.
password: the user's password. Required if token is missing.
eauth: the authentication type such as 'pam' or 'ldap'. Required if token is missing
'''
cmd = dict(cmd) # make copy
client = 'minion' # default to local minion client
mode = cmd.get('mode', 'async')
# check for wheel or runner prefix to fun name to use wheel or runner client
funparts = cmd.get('fun', '').split('.')
if len(funparts) > 2 and funparts[0] in ['wheel', 'runner']: # master
client = funparts[0]
cmd['fun'] = '.'.join(funparts[1:]) # strip prefix
if not ('token' in cmd or
('eauth' in cmd and 'password' in cmd and 'username' in cmd)):
raise EauthAuthenticationError('No authentication credentials given')
executor = getattr(self, '{0}_{1}'.format(client, mode))
result = executor(**cmd)
return result
def minion_async(self, **kwargs):
'''
Wrap LocalClient for running :ref:`execution modules <all-salt.modules>`
and immediately return the job ID. The results of the job can then be
retrieved at a later time.
.. seealso:: :ref:`python-api`
'''
return self.localClient.run_job(**kwargs)
def minion_sync(self, **kwargs):
'''
Wrap LocalClient for running :ref:`execution modules <all-salt.modules>`
.. seealso:: :ref:`python-api`
'''
return self.localClient.cmd(**kwargs)
def runner_async(self, **kwargs):
'''
Wrap RunnerClient for executing :ref:`runner modules <all-salt.runners>`
Expects that one of the kwargs is key 'fun' whose value is the namestring
of the function to call
'''
return self.runnerClient.master_call(**kwargs)
runner_sync = runner_async # always runner asynchronous, so works in either mode
def wheel_sync(self, **kwargs):
'''
Wrap Wheel to enable executing :ref:`wheel modules <all-salt.wheel>`
Expects that one of the kwargs is key 'fun' whose value is the namestring
of the function to call
'''
return self.wheelClient.master_call(**kwargs)
wheel_async = wheel_sync # always wheel_sync, so it works either mode
def signature(self, cmd):
'''
Convenience function that returns dict of function signature(s) specified by cmd.
cmd is dict of the form:
{
'module' : 'modulestring',
'tgt' : 'targetpatternstring',
'tgt_type' : 'targetpatterntype',
'token': 'salttokenstring',
'username': 'usernamestring',
'password': 'passwordstring',
'eauth': 'eauthtypestring',
}
The cmd dict items are as follows:
module: required. This is either a module or module function name for
the specified client.
tgt: Optional pattern string specifying the targeted minions when client
is 'minion'
tgt_type: Optional target pattern type string when client is 'minion'.
Example: 'glob' defaults to 'glob' if missing
token: the salt token. Either token: is required or the set of username:,
password: , and eauth:
username: the salt username. Required if token is missing.
password: the user's password. Required if token is missing.
eauth: the authentication type such as 'pam' or 'ldap'. Required if token is missing
Adds client per the command.
'''
cmd['client'] = 'minion'
if len(cmd['module'].split('.')) > 2 and cmd['module'].split('.')[0] in ['runner', 'wheel']:
cmd['client'] = 'master'
return self._signature(cmd)
def _signature(self, cmd):
'''
Expects everything that signature does and also a client type string.
client can either be master or minion.
'''
result = {}
client = cmd.get('client', 'minion')
if client == 'minion':
cmd['fun'] = 'sys.argspec'
cmd['kwarg'] = dict(module=cmd['module'])
result = self.run(cmd)
elif client == 'master':
parts = cmd['module'].split('.')
client = parts[0]
module = '.'.join(parts[1:]) # strip prefix
if client == 'wheel':
functions = self.wheelClient.functions
elif client == 'runner':
functions = self.runnerClient.functions
result = {'master': salt.utils.args.argspec_report(functions, module)}
return result
def verify_token(self, token):
'''
If token is valid Then returns user name associated with token
Else False.
'''
try:
result = self.resolver.get_token(token)
except Exception as ex:
raise EauthAuthenticationError(
"Token validation failed with {0}.".format(repr(ex)))
return result
def get_event(self, wait=0.25, tag='', full=False):
'''
Get a single salt event.
If no events are available, then block for up to ``wait`` seconds.
Return the event if it matches the tag (or ``tag`` is empty)
Otherwise return None
If wait is 0 then block forever or until next event becomes available.
'''
return self.event.get_event(wait=wait, tag=tag, full=full, auto_reconnect=True)
def fire_event(self, data, tag):
'''
fires event with data and tag
This only works if api is running with same user permissions as master
Need to convert this to a master call with appropriate authentication
'''
return self.event.fire_event(data, salt.utils.event.tagify(tag, 'wui'))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.